esx_driver.c 104.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 31
 * 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 "virterror_internal.h"
#include "domain_conf.h"
32
#include "authhelper.h"
33 34 35 36 37
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
#include "esx_driver.h"
38 39 40 41 42 43
#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"
#include "esx_private.h"
44 45 46 47 48 49 50
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
#include "esx_vmx.h"

#define VIR_FROM_THIS VIR_FROM_ESX

51
#define ESX_ERROR(code, ...)                                                  \
52
    virReportErrorHelper(NULL, VIR_FROM_ESX, code, __FILE__, __FUNCTION__,    \
53
                         __LINE__, __VA_ARGS__)
54 55 56 57 58

static int esxDomainGetMaxVcpus(virDomainPtr domain);



59
static esxVI_Boolean
60
esxSupportsLongMode(esxPrivate *priv)
61 62 63 64 65 66 67 68 69 70 71 72 73
{
    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;
    }

74
    if (esxVI_EnsureSession(priv->host) < 0) {
75 76 77
        goto failure;
    }

78
    if (esxVI_String_AppendValueToList(&propertyNameList,
79
                                       "hardware.cpuFeature") < 0 ||
80
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
81 82
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
83 84 85 86
        goto failure;
    }

    if (hostSystem == NULL) {
87
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
88 89 90 91 92 93 94 95
                  "Could not retrieve the HostSystem object");
        goto failure;
    }

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

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

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

118 119
#undef _SKIP4
#undef _SKIP12
120 121 122 123 124 125

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
126
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
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 155 156 157 158
                                  "Bit 29 (Long Mode) of HostSystem property "
                                  "'hardware.cpuFeature[].edx' with value '%s' "
                                  "has unexpected value '%c', expecting '0' "
                                  "or '1'", hostCpuIdInfo->edx, edxLongModeBit);
                        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;
}



159
static virCapsPtr
160
esxCapsInit(esxPrivate *priv)
161
{
162
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
163 164 165
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

166 167 168 169 170 171 172 173 174
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
177
        virReportOOMError();
178 179 180
        return NULL;
    }

181
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
182 183
    virCapabilitiesAddHostMigrateTransport(caps, "esx");

184 185 186
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
187 188 189 190 191 192 193 194 195 196 197 198 199 200

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

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    /* 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;
        }
    }

220 221 222 223 224 225 226 227 228 229
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



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

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

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

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

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
297
        virReportOOMError();
298 299 300
        goto failure;
    }

M
Matthias Bolte 已提交
301 302
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
303
    priv->supportsLongMode = esxVI_Boolean_Undefined;
304
    priv->autoAnswer = esxVI_Boolean_False;
305 306
    priv->usedCpuTimeCounterId = -1;

307
    if (esxUtil_ParseQuery(conn->uri, &priv->transport, &vCenter, &noVerify,
308
                           &autoAnswer) < 0) {
M
Matthias Bolte 已提交
309 310 311
        goto failure;
    }

312 313 314 315
    if (autoAnswer) {
        priv->autoAnswer = esxVI_Boolean_True;
    }

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

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

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

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

        if (username == NULL) {
354
            virReportOOMError();
355 356
            goto failure;
        }
M
Matthias Bolte 已提交
357
    } else {
358
        username = virRequestUsername(auth, "root", conn->uri->server);
359

M
Matthias Bolte 已提交
360
        if (username == NULL) {
361
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "Username request failed");
362 363
            goto failure;
        }
M
Matthias Bolte 已提交
364
    }
365

366
    if (esxVI_Context_Alloc(&priv->host) < 0) {
M
Matthias Bolte 已提交
367 368
        goto failure;
    }
369

370
    password = virRequestPassword(auth, username, conn->uri->server);
M
Matthias Bolte 已提交
371 372

    if (password == NULL) {
373
        ESX_ERROR(VIR_ERR_AUTH_FAILED, "Password request failed");
M
Matthias Bolte 已提交
374 375 376
        goto failure;
    }

377 378
    if (esxVI_Context_Connect(priv->host, url, hostIpAddress, username,
                              password, noVerify) < 0) {
M
Matthias Bolte 已提交
379 380 381 382 383 384
        goto failure;
    }

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

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

    /* Warn if host is in maintenance mode */
    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.inMaintenanceMode")) {
411
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
412 413 414 415 416 417 418 419 420 421 422 423
                                         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 已提交
424 425
    /* Login to vCenter */
    if (vCenter != NULL) {
426 427 428 429 430 431
        VIR_FREE(url);
        VIR_FREE(password);
        VIR_FREE(username);

        /* If a vCenter is specified resolve the hostname */
        if (STRNEQ(vCenter, "*") &&
432
            esxUtil_ResolveHostname(vCenter, vCenterIpAddress,
433 434 435 436 437 438 439
                                    NI_MAXHOST) < 0) {
            goto failure;
        }

        /* Lookup the vCenter from the ESX host */
        for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
440
            if (STREQ(dynamicProperty->name, "summary.managementServerIp")) {
441
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
442 443 444 445 446 447 448 449 450 451 452
                                             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) {
453
                        virReportOOMError();
454 455 456 457 458
                        goto failure;
                    }

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

                break;
            }
        }

        if (STREQ(vCenter, "*")) {
480
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
481 482 483 484
                      "This host is not managed by a vCenter");
            goto failure;
        }

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

491
        if (esxVI_Context_Alloc(&priv->vCenter) < 0) {
M
Matthias Bolte 已提交
492
            goto failure;
493 494
        }

495
        username = virRequestUsername(auth, "administrator", vCenter);
M
Matthias Bolte 已提交
496 497

        if (username == NULL) {
498
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "Username request failed");
499 500 501
            goto failure;
        }

502
        password = virRequestPassword(auth, username, vCenter);
503 504

        if (password == NULL) {
505
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "Password request failed");
506 507 508
            goto failure;
        }

509 510
        if (esxVI_Context_Connect(priv->vCenter, url, vCenterIpAddress,
                                  username, password, noVerify) < 0) {
511 512 513
            goto failure;
        }

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

    conn->privateData = priv;
524

M
Matthias Bolte 已提交
525
    /* Setup capabilities */
526
    priv->caps = esxCapsInit(priv);
527

M
Matthias Bolte 已提交
528 529
    if (priv->caps == NULL) {
        goto failure;
530 531
    }

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

540 541 542
    return result;

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

547 548
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
549
        VIR_FREE(priv->transport);
550 551 552
        VIR_FREE(priv);
    }

553 554 555
    result = VIR_DRV_OPEN_ERROR;

    goto cleanup;
556 557 558 559 560 561 562
}



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

E
Eric Blake 已提交
566 567 568 569
    if (esxVI_EnsureSession(priv->host) < 0 ||
        esxVI_Logout(priv->host) < 0) {
        result = -1;
    }
M
Matthias Bolte 已提交
570
    esxVI_Context_Free(&priv->host);
571

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

580 581
    virCapabilitiesFree(priv->caps);

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

    conn->privateData = NULL;

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



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

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

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

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

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

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

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

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

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

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

    goto cleanup;
}



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

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

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

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

      default:
        return 0;
    }
}



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



static int
esxGetVersion(virConnectPtr conn, unsigned long *version)
{
M
Matthias Bolte 已提交
686
    esxPrivate *priv = conn->privateData;
687 688 689 690 691 692
    char *temp;
    unsigned int major, minor, release;

    temp = (char *)priv->host->service->about->version;

    /* Expecting 'major.minor.release' format */
693
    if (virStrToLong_ui(temp, &temp, 10, &major) < 0 || *temp != '.') {
694 695 696
        goto failure;
    }

697
    if (virStrToLong_ui(temp + 1, &temp, 10, &minor) < 0 || *temp != '.') {
698 699 700 701 702 703 704 705 706 707 708 709
        goto failure;
    }

    if (virStrToLong_ui(temp + 1, NULL, 10, &release) < 0) {
        goto failure;
    }

    *version = 1000000 * major + 1000 * minor + release;

    return 0;

  failure:
710
    ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
711 712 713 714 715 716 717 718 719 720 721
              "Expecting version to match 'major.minor.release', but got '%s'",
              priv->host->service->about->version);

    return -1;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
722
    esxPrivate *priv = conn->privateData;
723 724 725 726 727 728 729
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

730
    if (esxVI_EnsureSession(priv->host) < 0) {
731 732 733 734
        goto failure;
    }

    if (esxVI_String_AppendValueListToList
735
          (&propertyNameList,
736 737
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
738
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
739 740
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
741 742 743 744
        goto failure;
    }

    if (hostSystem == NULL) {
745
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
746 747 748 749 750 751 752 753
                  "Could not retrieve the HostSystem object");
        goto failure;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
754
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
755 756 757 758 759 760 761
                                         esxVI_Type_String) < 0) {
                goto failure;
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
762
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
763 764 765 766 767 768 769 770 771 772
                                         esxVI_Type_String) < 0) {
                goto failure;
            }

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

M
Matthias Bolte 已提交
773
    if (hostName == NULL || strlen(hostName) < 1) {
774
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
775 776 777 778
                  "Missing or empty 'hostName' property");
        goto failure;
    }

M
Matthias Bolte 已提交
779
    if (domainName == NULL || strlen(domainName) < 1) {
780
        complete = strdup(hostName);
781

782
        if (complete == NULL) {
783
            virReportOOMError();
784 785 786 787
            goto failure;
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
788
            virReportOOMError();
789 790
            goto failure;
        }
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    }

  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 已提交
811
    esxPrivate *priv = conn->privateData;
812 813 814 815 816 817 818 819 820 821 822
    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 已提交
823
    memset(nodeinfo, 0, sizeof(virNodeInfo));
824

825
    if (esxVI_EnsureSession(priv->host) < 0) {
826 827 828
        goto failure;
    }

829
    if (esxVI_String_AppendValueListToList(&propertyNameList,
830 831 832 833 834 835 836
                                           "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 ||
837
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
838 839
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
840 841 842 843
        goto failure;
    }

    if (hostSystem == NULL) {
844
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
845 846 847 848 849 850 851
                  "Could not retrieve the HostSystem object");
        goto failure;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
852
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
853 854 855 856 857 858 859
                                         esxVI_Type_Long) < 0) {
                goto failure;
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
860
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
861 862 863 864 865 866 867
                                         esxVI_Type_Short) < 0) {
                goto failure;
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
868
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
869 870 871 872 873 874 875
                                         esxVI_Type_Short) < 0) {
                goto failure;
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
876
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
877 878 879 880 881 882
                                         esxVI_Type_Short) < 0) {
                goto failure;
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
883
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
884 885 886 887 888 889 890
                                         esxVI_Type_Long) < 0) {
                goto failure;
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
891
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
892 893 894 895 896 897 898
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
899
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
900 901 902 903 904 905 906 907
                                         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 已提交
908 909
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
910
                    continue;
911
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
912
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
913
                    continue;
914 915 916
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
917 918 919 920 921
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
922 923 924
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
925
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
926 927 928 929
                          "CPU Model %s too long for destination",
                          dynamicProperty->val->string);
                goto failure;
            }
930 931 932 933 934 935 936
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
937
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
    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;
}



961 962 963
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
964
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
965
    char *xml = virCapabilitiesFormatXML(priv->caps);
966 967

    if (xml == NULL) {
968
        virReportOOMError();
969 970 971 972 973 974 975 976
        return NULL;
    }

    return xml;
}



977 978 979
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
980
    esxPrivate *priv = conn->privateData;
981 982 983 984 985 986 987 988 989 990 991 992 993 994
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

    if (ids == NULL || maxids < 0) {
        goto failure;
    }

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

995
    if (esxVI_EnsureSession(priv->host) < 0) {
996 997 998
        goto failure;
    }

999
    if (esxVI_String_AppendValueToList(&propertyNameList,
1000
                                       "runtime.powerState") < 0 ||
1001
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
1002 1003 1004
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
1005 1006 1007 1008 1009
        goto failure;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1010
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
                                              &powerState) < 0) {
            goto failure;
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1022
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
                      "Failed to parse positive integer from '%s'",
                      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 已提交
1052
    esxPrivate *priv = conn->privateData;
1053

1054
    if (esxVI_EnsureSession(priv->host) < 0) {
1055 1056 1057
        return -1;
    }

1058
    return esxVI_LookupNumberOfDomainsByPowerState
1059
             (priv->host, esxVI_VirtualMachinePowerState_PoweredOn,
1060 1061 1062 1063 1064 1065 1066 1067
              esxVI_Boolean_False);
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1068
    esxPrivate *priv = conn->privateData;
1069 1070 1071 1072
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1073 1074 1075
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1076 1077
    virDomainPtr domain = NULL;

1078
    if (esxVI_EnsureSession(priv->host) < 0) {
1079 1080 1081
        goto failure;
    }

1082
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1083
                                           "configStatus\0"
1084 1085
                                           "name\0"
                                           "runtime.powerState\0"
1086
                                           "config.uuid\0") < 0 ||
1087
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
1088 1089 1090
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
1091 1092 1093 1094 1095
        goto failure;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1096
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1097 1098 1099 1100 1101 1102 1103 1104 1105
                                              &powerState) < 0) {
            goto failure;
        }

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

M
Matthias Bolte 已提交
1106
        VIR_FREE(name_candidate);
1107

1108
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1109 1110
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
1111 1112 1113
            goto failure;
        }

M
Matthias Bolte 已提交
1114
        if (id != id_candidate) {
1115 1116 1117
            continue;
        }

M
Matthias Bolte 已提交
1118
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

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

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1130
        ESX_ERROR(VIR_ERR_NO_DOMAIN, "No domain with ID %d", id);
1131 1132 1133 1134 1135
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1136
    VIR_FREE(name_candidate);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150

    return domain;

  failure:
    domain = NULL;

    goto cleanup;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1151
    esxPrivate *priv = conn->privateData;
1152 1153 1154
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1155 1156
    int id = -1;
    char *name = NULL;
1157 1158
    virDomainPtr domain = NULL;

1159
    if (esxVI_EnsureSession(priv->host) < 0) {
1160 1161 1162
        goto failure;
    }

1163
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1164
                                           "name\0"
1165
                                           "runtime.powerState\0") < 0 ||
1166 1167
        esxVI_LookupVirtualMachineByUuid(priv->host, uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
1168
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1169 1170
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1171 1172 1173
        goto failure;
    }

1174
    domain = virGetDomain(conn, name, uuid);
1175 1176

    if (domain == NULL) {
1177 1178
        goto failure;
    }
1179

1180 1181 1182 1183 1184
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1185 1186 1187 1188
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1189 1190
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204

    return domain;

  failure:
    domain = NULL;

    goto cleanup;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1205
    esxPrivate *priv = conn->privateData;
1206 1207 1208
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1209 1210
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1211 1212
    virDomainPtr domain = NULL;

1213
    if (esxVI_EnsureSession(priv->host) < 0) {
1214 1215 1216
        goto failure;
    }

1217
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1218
                                           "configStatus\0"
1219
                                           "runtime.powerState\0"
1220
                                           "config.uuid\0") < 0 ||
1221 1222 1223
        esxVI_LookupVirtualMachineByName(priv->host, name, propertyNameList,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
1224 1225 1226
        goto failure;
    }

1227 1228 1229 1230
    if (virtualMachine == NULL) {
        ESX_ERROR(VIR_ERR_NO_DOMAIN, "No domain with name '%s'", name);
        goto failure;
    }
1231 1232


1233 1234 1235
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0) {
        goto failure;
    }
M
Matthias Bolte 已提交
1236

1237 1238 1239 1240
    if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                          &powerState) < 0) {
        goto failure;
    }
1241

1242
    domain = virGetDomain(conn, name, uuid);
1243

1244 1245
    if (domain == NULL) {
        goto failure;
1246 1247
    }

1248 1249 1250 1251 1252
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1253 1254 1255 1256
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1257
    esxVI_ObjectContent_Free(&virtualMachine);
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

    return domain;

  failure:
    domain = NULL;

    goto cleanup;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
1273
    esxPrivate *priv = domain->conn->privateData;
1274 1275 1276 1277 1278 1279
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1280
    if (esxVI_EnsureSession(priv->host) < 0) {
1281 1282 1283
        goto failure;
    }

1284
    if (esxVI_String_AppendValueToList(&propertyNameList,
1285
                                       "runtime.powerState") < 0 ||
1286
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1287 1288 1289
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1290 1291 1292 1293
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1294
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "Domain is not powered on");
1295 1296 1297
        goto failure;
    }

1298 1299 1300
    if (esxVI_SuspendVM_Task(priv->host, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1301 1302 1303 1304
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1305
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not suspend domain");
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
        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 已提交
1328
    esxPrivate *priv = domain->conn->privateData;
1329 1330 1331 1332 1333 1334
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1335
    if (esxVI_EnsureSession(priv->host) < 0) {
1336 1337 1338
        goto failure;
    }

1339
    if (esxVI_String_AppendValueToList(&propertyNameList,
1340
                                       "runtime.powerState") < 0 ||
1341
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1342 1343 1344
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1345 1346 1347 1348
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1349
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "Domain is not suspended");
1350 1351 1352
        goto failure;
    }

1353 1354 1355
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1356 1357 1358 1359
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1360
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not resume domain");
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        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 已提交
1383
    esxPrivate *priv = domain->conn->privateData;
1384 1385 1386 1387
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1388
    if (esxVI_EnsureSession(priv->host) < 0) {
1389 1390 1391
        goto failure;
    }

1392
    if (esxVI_String_AppendValueToList(&propertyNameList,
1393
                                       "runtime.powerState") < 0 ||
1394 1395
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1396
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1397
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1398 1399 1400 1401
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1402
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "Domain is not powered on");
1403 1404 1405
        goto failure;
    }

1406
    if (esxVI_ShutdownGuest(priv->host, virtualMachine->obj) < 0) {
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
        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 已提交
1428
    esxPrivate *priv = domain->conn->privateData;
1429 1430 1431 1432
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1433
    if (esxVI_EnsureSession(priv->host) < 0) {
1434 1435 1436
        goto failure;
    }

1437
    if (esxVI_String_AppendValueToList(&propertyNameList,
1438
                                       "runtime.powerState") < 0 ||
1439 1440
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1441
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1442
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1443 1444 1445 1446
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1447
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "Domain is not powered on");
1448 1449 1450
        goto failure;
    }

1451
    if (esxVI_RebootGuest(priv->host, virtualMachine->obj) < 0) {
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
        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 已提交
1473
    esxPrivate *priv = domain->conn->privateData;
1474
    esxVI_Context *ctx = NULL;
1475 1476 1477 1478 1479 1480
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1481 1482 1483 1484 1485 1486
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1487
    if (esxVI_EnsureSession(ctx) < 0) {
1488 1489 1490
        goto failure;
    }

1491
    if (esxVI_String_AppendValueToList(&propertyNameList,
1492
                                       "runtime.powerState") < 0 ||
1493
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1494
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1495
           priv->autoAnswer) < 0 ||
1496
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
1497 1498 1499 1500
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1501
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "Domain is not powered on");
1502 1503 1504
        goto failure;
    }

1505 1506 1507
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid, priv->autoAnswer,
                                    &taskInfoState) < 0) {
1508 1509 1510 1511
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1512
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not destroy domain");
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static char *
1532
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
1533
{
1534 1535 1536
    char *osType = strdup("hvm");

    if (osType == NULL) {
1537
        virReportOOMError();
1538 1539 1540 1541
        return NULL;
    }

    return osType;
1542 1543 1544 1545 1546 1547 1548
}



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

1555
    if (esxVI_EnsureSession(priv->host) < 0) {
1556 1557 1558
        goto failure;
    }

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

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1570
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1571 1572 1573 1574 1575
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

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

1612
    if (esxVI_EnsureSession(priv->host) < 0) {
1613 1614 1615
        goto failure;
    }

1616
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1617
          (priv->host, domain->uuid, NULL, &virtualMachine,
1618
           priv->autoAnswer) < 0 ||
1619 1620
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
1621 1622 1623 1624 1625 1626
        goto failure;
    }

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

1627 1628 1629 1630
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1631 1632 1633 1634
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1635
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
                  "Could not set max-memory to %lu kilobytes", memory);
        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 已提交
1659
    esxPrivate *priv = domain->conn->privateData;
1660 1661 1662 1663 1664
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1665
    if (esxVI_EnsureSession(priv->host) < 0) {
1666 1667 1668
        goto failure;
    }

1669
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1670
          (priv->host, domain->uuid, NULL, &virtualMachine,
1671
           priv->autoAnswer) < 0 ||
1672 1673 1674
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
1675 1676 1677 1678 1679 1680
        goto failure;
    }

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

1681 1682 1683 1684
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
1685 1686 1687 1688
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1689
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
                  "Could not set memory to %lu kilobytes", memory);
        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 已提交
1713
    esxPrivate *priv = domain->conn->privateData;
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
    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;
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfEntityMetric *perfEntityMetricList = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;

1731
    if (esxVI_EnsureSession(priv->host) < 0) {
1732 1733 1734
        goto failure;
    }

1735
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1736 1737 1738 1739
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
1740 1741
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1742
                                         esxVI_Occurrence_RequiredItem) < 0) {
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
        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
1756
                  (dynamicProperty->val, &powerState) < 0) {
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
                goto failure;
            }

            switch (powerState) {
              case esxVI_VirtualMachinePowerState_PoweredOff:
                info->state = VIR_DOMAIN_SHUTOFF;
                break;

              case esxVI_VirtualMachinePowerState_PoweredOn:
                info->state = VIR_DOMAIN_RUNNING;
                break;

              case esxVI_VirtualMachinePowerState_Suspended:
                info->state = VIR_DOMAIN_PAUSED;
                break;

              default:
                info->state = VIR_DOMAIN_NOSTATE;
                break;
            }
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1778
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1779 1780 1781 1782 1783 1784
                                         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")) {
1785
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1786 1787 1788 1789 1790 1791 1792
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
1793
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
                                         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) {
1813
        if (esxVI_Int_Alloc(&counterId) < 0) {
1814 1815 1816 1817 1818
            goto failure;
        }

        counterId->value = priv->usedCpuTimeCounterId;

1819
        if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
1820 1821 1822
            goto failure;
        }

1823
        if (esxVI_QueryPerfCounter(priv->host, counterIdList,
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
                                   &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) {
1846 1847 1848
        if (esxVI_QueryAvailablePerfMetric(priv->host, virtualMachine->obj,
                                           NULL, NULL, NULL,
                                           &perfMetricIdList) < 0) {
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
            goto failure;
        }

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

            counterId = NULL;

1859 1860
            if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
1861 1862 1863 1864
                goto failure;
            }
        }

1865
        if (esxVI_QueryPerfCounter(priv->host, counterIdList,
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
                                   &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);

1901 1902 1903 1904
        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) {
1905 1906 1907 1908 1909 1910 1911 1912 1913
            goto failure;
        }

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

1914
        if (esxVI_QueryPerf(priv->host, querySpec, &perfEntityMetricList) < 0) {
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
            goto failure;
        }

        for (perfEntityMetric = perfEntityMetricList; perfEntityMetric != NULL;
             perfEntityMetric = perfEntityMetric->_next) {
            VIR_DEBUG0("perfEntityMetric ...");

1925 1926 1927 1928 1929 1930 1931 1932
            perfMetricIntSeries =
              esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);

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

            for (; perfMetricIntSeries != NULL;
1933 1934 1935 1936 1937 1938
                 perfMetricIntSeries = perfMetricIntSeries->_next) {
                VIR_DEBUG0("perfMetricIntSeries ...");

                for (value = perfMetricIntSeries->value;
                     value != NULL;
                     value = value->_next) {
1939
                    VIR_DEBUG("value %lld", (long long int)value->value);
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
                }
            }
        }

        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);
    esxVI_PerfEntityMetric_Free(&perfEntityMetricList);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
    int result = 0;
M
Matthias Bolte 已提交
1974
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
1975
    int maxVcpus;
1976 1977 1978 1979 1980 1981
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

    if (nvcpus < 1) {
1982 1983
        ESX_ERROR(VIR_ERR_INVALID_ARG,
                  "Requested number of virtual CPUs must at least be 1");
1984 1985 1986
        goto failure;
    }

1987
    if (esxVI_EnsureSession(priv->host) < 0) {
1988 1989 1990
        goto failure;
    }

M
Matthias Bolte 已提交
1991
    maxVcpus = esxDomainGetMaxVcpus(domain);
1992

M
Matthias Bolte 已提交
1993
    if (maxVcpus < 0) {
1994 1995 1996
        goto failure;
    }

M
Matthias Bolte 已提交
1997
    if (nvcpus > maxVcpus) {
1998
        ESX_ERROR(VIR_ERR_INVALID_ARG,
1999 2000
                  "Requested number of virtual CPUs is greater than max "
                  "allowable number of virtual CPUs for the domain: %d > %d",
M
Matthias Bolte 已提交
2001
                  nvcpus, maxVcpus);
2002 2003 2004
        goto failure;
    }

2005
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2006
          (priv->host, domain->uuid, NULL, &virtualMachine,
2007
           priv->autoAnswer) < 0 ||
2008 2009
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
2010 2011 2012 2013 2014
        goto failure;
    }

    spec->numCPUs->value = nvcpus;

2015 2016 2017 2018
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
2019 2020 2021 2022
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2023
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
                  "Could not set number of virtual CPUs to %d", nvcpus);
        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 已提交
2046
    esxPrivate *priv = domain->conn->privateData;
2047 2048 2049 2050
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

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

2055
    if (esxVI_EnsureSession(priv->host) < 0) {
2056 2057 2058
        goto failure;
    }

2059
    if (esxVI_String_AppendValueToList(&propertyNameList,
2060
                                       "capability.maxSupportedVcpus") < 0 ||
2061 2062 2063
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
2064 2065 2066 2067
        goto failure;
    }

    if (hostSystem == NULL) {
2068
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2069 2070 2071 2072 2073 2074 2075
                  "Could not retrieve the HostSystem object");
        goto failure;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2076
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2077 2078 2079 2080
                                         esxVI_Type_Int) < 0) {
                goto failure;
            }

M
Matthias Bolte 已提交
2081
            priv->maxVcpus = dynamicProperty->val->int32;
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2092
    return priv->maxVcpus;
2093 2094

  failure:
M
Matthias Bolte 已提交
2095
    priv->maxVcpus = -1;
2096 2097 2098 2099 2100 2101 2102 2103 2104

    goto cleanup;
}



static char *
esxDomainDumpXML(virDomainPtr domain, int flags)
{
M
Matthias Bolte 已提交
2105
    esxPrivate *priv = domain->conn->privateData;
2106 2107 2108 2109 2110
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *vmPathName = NULL;
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2111 2112
    char *directoryName = NULL;
    char *fileName = NULL;
2113
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2114 2115 2116 2117 2118
    char *url = NULL;
    char *vmx = NULL;
    virDomainDefPtr def = NULL;
    char *xml = NULL;

2119
    if (esxVI_EnsureSession(priv->host) < 0) {
2120 2121 2122
        goto failure;
    }

2123
    if (esxVI_String_AppendValueToList(&propertyNameList,
2124
                                       "config.files.vmPathName") < 0 ||
2125 2126
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2127
                                         esxVI_Occurrence_RequiredItem) < 0) {
2128 2129 2130 2131 2132 2133
        goto failure;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.files.vmPathName")) {
2134
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2135 2136 2137 2138 2139 2140 2141 2142 2143
                                         esxVI_Type_String) < 0) {
                goto failure;
            }

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

2144 2145
    if (esxUtil_ParseDatastoreRelatedPath(vmPathName, &datastoreName,
                                          &directoryName, &fileName) < 0) {
2146 2147 2148
        goto failure;
    }

2149 2150
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
M
Matthias Bolte 已提交
2151 2152 2153 2154 2155 2156 2157

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

    virBufferURIEncodeString(&buffer, fileName);
2158 2159 2160 2161 2162 2163
    virBufferAddLit(&buffer, "?dcPath=");
    virBufferURIEncodeString(&buffer, priv->host->datacenter->value);
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2164
        virReportOOMError();
2165 2166 2167
        goto failure;
    }

2168 2169
    url = virBufferContentAndReset(&buffer);

2170
    if (esxVI_Context_DownloadFile(priv->host, url, &vmx) < 0) {
2171 2172 2173
        goto failure;
    }

2174 2175
    def = esxVMX_ParseConfig(priv->host, vmx, datastoreName, directoryName,
                             priv->host->apiVersion);
2176 2177

    if (def != NULL) {
2178
        xml = virDomainDefFormat(def, flags);
2179 2180 2181
    }

  cleanup:
2182 2183
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2184
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2185 2186
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
2187 2188
    VIR_FREE(url);
    VIR_FREE(vmx);
2189
    virDomainDefFree(def);
2190 2191 2192 2193

    return xml;

  failure:
2194
    virBufferFreeAndReset(&buffer);
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
    VIR_FREE(xml);

    goto cleanup;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2207
    esxPrivate *priv = conn->privateData;
2208 2209 2210 2211
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2212
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2213
                  "Unsupported config format '%s'", nativeFormat);
2214
        return NULL;
2215 2216
    }

2217
    def = esxVMX_ParseConfig(priv->host, nativeConfig, "?", "?",
M
Matthias Bolte 已提交
2218
                             priv->host->apiVersion);
2219 2220

    if (def != NULL) {
2221
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2222 2223 2224 2225 2226 2227 2228 2229 2230
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2231 2232 2233 2234 2235
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2236
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2237 2238 2239 2240
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2241
        ESX_ERROR(VIR_ERR_INVALID_ARG,
M
Matthias Bolte 已提交
2242 2243 2244 2245
                  "Unsupported config format '%s'", nativeFormat);
        return NULL;
    }

2246
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2247 2248 2249 2250 2251

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

2252
    vmx = esxVMX_FormatConfig(priv->host, def, priv->host->apiVersion);
M
Matthias Bolte 已提交
2253 2254 2255 2256 2257 2258 2259 2260

    virDomainDefFree(def);

    return vmx;
}



2261 2262 2263
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2264
    esxPrivate *priv = conn->privateData;
2265 2266 2267 2268 2269 2270
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2271
    int i;
2272 2273 2274 2275 2276 2277 2278 2279 2280

    if (names == NULL || maxnames < 0) {
        goto failure;
    }

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

2281
    if (esxVI_EnsureSession(priv->host) < 0) {
2282 2283 2284
        goto failure;
    }

2285
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2286 2287
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2288
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
2289 2290 2291
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
2292 2293 2294 2295 2296
        goto failure;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2297
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
                                              &powerState) < 0) {
            goto failure;
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2310
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2311 2312 2313 2314 2315 2316 2317
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

                if (names[count] == NULL) {
2318
                    virReportOOMError();
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
                    goto failure;
                }

                count++;
                break;
            }
        }

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

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

    return count;

  failure:
2339 2340 2341 2342
    for (i = 0; i < count; ++i) {
        VIR_FREE(names[i]);
    }

2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
    count = -1;

    goto cleanup;

}



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

2356
    if (esxVI_EnsureSession(priv->host) < 0) {
2357 2358 2359
        return -1;
    }

2360
    return esxVI_LookupNumberOfDomainsByPowerState
2361
             (priv->host, esxVI_VirtualMachinePowerState_PoweredOn,
2362 2363 2364 2365 2366 2367 2368 2369 2370
              esxVI_Boolean_True);
}



static int
esxDomainCreate(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
2371
    esxPrivate *priv = domain->conn->privateData;
2372 2373 2374 2375 2376 2377
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2378
    if (esxVI_EnsureSession(priv->host) < 0) {
2379 2380 2381
        goto failure;
    }

2382
    if (esxVI_String_AppendValueToList(&propertyNameList,
2383
                                       "runtime.powerState") < 0 ||
2384
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2385 2386 2387
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine,
2388 2389 2390 2391 2392
                                          &powerState) < 0) {
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2393
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "Domain is not powered off");
2394 2395 2396
        goto failure;
    }

2397 2398 2399
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
2400 2401 2402 2403
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2404
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not start domain");
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
        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 已提交
2423 2424 2425
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2426
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2427 2428
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2429 2430
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
    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;

2445
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2446 2447 2448 2449
        goto failure;
    }

    /* Parse domain XML */
2450
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
2451 2452 2453 2454 2455 2456 2457
                                  VIR_DOMAIN_XML_INACTIVE);

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

    /* Check if an existing domain should be edited */
2458
    if (esxVI_LookupVirtualMachineByUuid(priv->host, def->uuid, NULL,
M
Matthias Bolte 已提交
2459
                                         &virtualMachine,
M
Matthias Bolte 已提交
2460
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2461 2462 2463 2464 2465
        goto failure;
    }

    if (virtualMachine != NULL) {
        /* FIXME */
2466
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
2467 2468 2469 2470 2471 2472
                  "Domain already exists, editing existing domains is not "
                  "supported yet");
        goto failure;
    }

    /* Build VMX from domain XML */
2473
    vmx = esxVMX_FormatConfig(priv->host, def, priv->host->apiVersion);
M
Matthias Bolte 已提交
2474 2475 2476 2477 2478

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

2479 2480 2481 2482 2483 2484 2485
    /*
     * 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 已提交
2486
    if (def->ndisks < 1) {
2487
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
                  "Domain XML doesn't contain any disks, cannot deduce "
                  "datastore and path for VMX file");
        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) {
2502
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2503 2504
                  "Domain XML doesn't contain any file-based harddisks, "
                  "cannot deduce datastore and path for VMX file");
M
Matthias Bolte 已提交
2505 2506 2507
        goto failure;
    }

2508
    if (disk->src == NULL) {
2509
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2510 2511
                  "First file-based harddisk has no source, cannot deduce "
                  "datastore and path for VMX file");
M
Matthias Bolte 已提交
2512 2513 2514
        goto failure;
    }

2515
    if (esxUtil_ParseDatastoreRelatedPath(disk->src, &datastoreName,
2516
                                          &directoryName, &fileName) < 0) {
M
Matthias Bolte 已提交
2517 2518 2519
        goto failure;
    }

2520
    if (! virFileHasSuffix(fileName, ".vmdk")) {
2521
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2522 2523
                  "Expecting source '%s' of first file-based harddisk to be a "
                  "VMDK image", disk->src);
M
Matthias Bolte 已提交
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
        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)) {
2542
        virReportOOMError();
M
Matthias Bolte 已提交
2543 2544 2545 2546 2547 2548 2549 2550
        goto failure;
    }

    url = virBufferContentAndReset(&buffer);

    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
                        directoryName, def->name) < 0) {
2551
            virReportOOMError();
M
Matthias Bolte 已提交
2552 2553 2554 2555 2556
            goto failure;
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
                        def->name) < 0) {
2557
            virReportOOMError();
M
Matthias Bolte 已提交
2558 2559 2560 2561 2562
            goto failure;
        }
    }

    /* Get resource pool */
2563 2564
    if (esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->host, priv->host->ipAddress,
M
Matthias Bolte 已提交
2565 2566 2567 2568
                                   propertyNameList, &hostSystem) < 0) {
        goto failure;
    }

2569
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
2570
                                             &resourcePool) < 0) {
M
Matthias Bolte 已提交
2571 2572 2573 2574 2575 2576 2577
        goto failure;
    }

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

    /* Upload VMX file */
2578
    if (esxVI_Context_UploadFile(priv->host, url, vmx) < 0) {
M
Matthias Bolte 已提交
2579 2580 2581 2582
        goto failure;
    }

    /* Register the domain */
2583
    if (esxVI_RegisterVM_Task(priv->host, priv->host->vmFolder,
M
Matthias Bolte 已提交
2584 2585
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
                              resourcePool, hostSystem->obj, &task) < 0 ||
2586 2587
        esxVI_WaitForTaskCompletion(priv->host, task, def->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2588 2589 2590 2591
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2592
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not define domain");
M
Matthias Bolte 已提交
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
        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:
2621 2622
    virBufferFreeAndReset(&buffer);

M
Matthias Bolte 已提交
2623 2624 2625 2626 2627 2628 2629
    domain = NULL;

    goto cleanup;
}



2630 2631 2632 2633
static int
esxDomainUndefine(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
2634
    esxPrivate *priv = domain->conn->privateData;
2635
    esxVI_Context *ctx = NULL;
2636 2637 2638 2639
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

2640 2641 2642 2643 2644 2645
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

2646
    if (esxVI_EnsureSession(ctx) < 0) {
2647 2648 2649
        goto failure;
    }

2650
    if (esxVI_String_AppendValueToList(&propertyNameList,
2651
                                       "runtime.powerState") < 0 ||
2652 2653
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
2654
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2655
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
2656 2657 2658 2659 2660
        goto failure;
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2661
        ESX_ERROR(VIR_ERR_OPERATION_INVALID,
2662 2663 2664 2665
                  "Domain is not suspended or powered off");
        goto failure;
    }

2666
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
/*
 * 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)
 *
2696
 *   The amount of CPU resource that is guaranteed to be available to the domain.
2697 2698 2699 2700
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
2701 2702
 *   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
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
 *   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'.
 */
2714
static char *
2715
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
2716 2717 2718 2719
{
    char *type = strdup("allocation");

    if (type == NULL) {
2720
        virReportOOMError();
2721
        return NULL;
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
    }

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

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
    int result = 0;
M
Matthias Bolte 已提交
2736
    esxPrivate *priv = domain->conn->privateData;
2737 2738 2739 2740 2741 2742 2743 2744
    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) {
2745
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2746 2747 2748 2749
                  "Parameter array must have space for 3 items");
        goto failure;
    }

2750
    if (esxVI_EnsureSession(priv->host) < 0) {
2751 2752 2753
        goto failure;
    }

2754
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2755 2756 2757
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
2758 2759
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2760
                                         esxVI_Occurrence_RequiredItem) < 0) {
2761 2762 2763 2764 2765 2766 2767
        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 已提交
2768
            ! (mask & (1 << 0))) {
2769 2770 2771 2772 2773
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2774
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2775 2776 2777 2778 2779 2780 2781 2782 2783
                                         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 已提交
2784
                   ! (mask & (1 << 1))) {
2785 2786 2787 2788 2789
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2790
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2791 2792 2793 2794 2795 2796 2797 2798 2799
                                         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 已提交
2800
                   ! (mask & (1 << 2))) {
2801 2802 2803 2804 2805
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "shares");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

2806
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828
                                                 &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:
2829
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2830 2831
                          "Shares level has unknown value %d",
                          (int)sharesInfo->level);
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
                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 已提交
2865
    esxPrivate *priv = domain->conn->privateData;
2866 2867 2868 2869 2870 2871 2872
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

2873
    if (esxVI_EnsureSession(priv->host) < 0) {
2874 2875 2876
        goto failure;
    }

2877
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2878
          (priv->host, domain->uuid, NULL, &virtualMachine,
2879
           priv->autoAnswer) < 0 ||
2880 2881
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
2882 2883 2884 2885 2886 2887
        goto failure;
    }

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

            if (params[i].value.l < 0) {
2893
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2894 2895 2896 2897 2898 2899 2900 2901
                          "Could not set reservation to %lld MHz, expecting "
                          "positive value", params[i].value.l);
                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) {
2902
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
2903 2904 2905 2906
                goto failure;
            }

            if (params[i].value.l < -1) {
2907
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2908 2909 2910 2911 2912 2913 2914 2915
                          "Could not set limit to %lld MHz, expecting "
                          "positive value or -1 (unlimited)",
                          params[i].value.l);
                goto failure;
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
2916
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
2917 2918
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
2919 2920 2921 2922 2923
                goto failure;
            }

            spec->cpuAllocation->shares = sharesInfo;

2924
            if (params[i].value.i >= 0) {
2925
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
2926
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
2927
            } else {
2928
                switch (params[i].value.i) {
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946
                  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:
2947
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
2948 2949 2950 2951 2952 2953 2954
                              "Could not set shares to %d, expecting positive "
                              "value or -1 (low), -2 (normal) or -3 (high)",
                              params[i].value.i);
                    goto failure;
                }
            }
        } else {
2955 2956
            ESX_ERROR(VIR_ERR_INVALID_ARG, "Unknown field '%s'",
                      params[i].field);
2957 2958 2959 2960
            goto failure;
        }
    }

2961 2962 2963 2964
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
2965 2966 2967 2968
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2969
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001
                  "Could not change scheduler parameters");
        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) {
3002
        if (esxUtil_ParseQuery(dconn->uri, &transport, NULL, NULL, NULL) < 0) {
3003 3004 3005
            return -1;
        }

3006 3007
        if (virAsprintf(uri_out, "%s://%s:%d/sdk", transport,
                        dconn->uri->server, dconn->uri->port) < 0) {
3008
            virReportOOMError();
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
            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 已提交
3036
    esxPrivate *priv = domain->conn->privateData;
3037
    xmlURIPtr xmlUri = NULL;
M
Matthias Bolte 已提交
3038
    char hostIpAddress[NI_MAXHOST] = "";
3039 3040 3041 3042 3043 3044 3045 3046
    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 已提交
3047
    if (priv->vCenter == NULL) {
3048
        ESX_ERROR(VIR_ERR_INVALID_ARG,
M
Matthias Bolte 已提交
3049
                  "Migration not possible without a vCenter");
3050 3051 3052 3053
        goto failure;
    }

    if (dname != NULL) {
3054
        ESX_ERROR(VIR_ERR_INVALID_ARG,
3055 3056 3057 3058
                  "Renaming domains on migration not supported");
        goto failure;
    }

3059
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
3060 3061 3062 3063 3064 3065 3066
        goto failure;
    }

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

    if (xmlUri == NULL) {
3067
        virReportOOMError();
3068 3069 3070
        goto failure;
    }

3071
    if (esxUtil_ResolveHostname(xmlUri->server, hostIpAddress,
3072 3073 3074 3075 3076
                                NI_MAXHOST) < 0) {
        goto failure;
    }

    /* Lookup VirtualMachine, HostSystem and ResourcePool */
3077
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3078
          (priv->vCenter, domain->uuid, NULL, &virtualMachine,
3079
           priv->autoAnswer) < 0 ||
3080 3081
        esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->vCenter, hostIpAddress,
M
Matthias Bolte 已提交
3082
                                   propertyNameList, &hostSystem) < 0) {
3083 3084 3085
        goto failure;
    }

3086 3087
    if (esxVI_LookupResourcePoolByHostSystem(priv->vCenter, hostSystem,
                                             &resourcePool) < 0) {
3088 3089 3090 3091
        goto failure;
    }

    /* Validate the purposed migration */
3092
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
                                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) {
3105
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3106 3107 3108
                      "Could not migrate domain, validation reported a "
                      "problem: %s", eventList->fullFormattedMessage);
        } else {
3109
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3110 3111 3112 3113 3114 3115 3116 3117
                      "Could not migrate domain, validation reported a "
                      "problem");
        }

        goto failure;
    }

    /* Perform the purposed migration */
3118
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj, resourcePool,
3119 3120 3121 3122
                             hostSystem->obj,
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3123 3124
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
3125 3126 3127 3128
        goto failure;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3129
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
                  "Could not migrate domain, migration task finished with "
                  "an error");
        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 已提交
3166 3167 3168 3169
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3170
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3171 3172 3173 3174 3175 3176 3177
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3178
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3179 3180 3181 3182
        goto failure;
    }

    /* Lookup host system with its resource pool */
3183 3184
    if (esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->host, priv->host->ipAddress,
M
Matthias Bolte 已提交
3185 3186 3187 3188
                                   propertyNameList, &hostSystem) < 0) {
        goto failure;
    }

3189
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
3190
                                             &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
3191 3192 3193 3194 3195 3196
        goto failure;
    }

    esxVI_String_Free(&propertyNameList);

    /* Get memory usage of resource pool */
3197
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3198
                                       "runtime.memory") < 0 ||
3199
        esxVI_LookupObjectContentByType(priv->host, managedObjectReference,
3200 3201 3202
                                        "ResourcePool", propertyNameList,
                                        esxVI_Boolean_False,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3203 3204 3205 3206 3207 3208 3209
        goto failure;
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3210
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
                goto failure;
            }

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

    if (resourcePoolResourceUsage == NULL) {
3221
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244
                  "Could not retrieve memory usage of resource pool");
        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;
}



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

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



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3262
    esxPrivate *priv = conn->privateData;
3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276

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



static int
esxDomainIsActive(virDomainPtr domain)
{
    int result = 0;
M
Matthias Bolte 已提交
3277
    esxPrivate *priv = domain->conn->privateData;
3278 3279 3280 3281
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3282
    if (esxVI_EnsureSession(priv->host) < 0) {
3283 3284 3285
        goto failure;
    }

3286
    if (esxVI_String_AppendValueToList(&propertyNameList,
3287
                                       "runtime.powerState") < 0 ||
3288 3289
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3290
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3291
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323
        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;
}



3324 3325 3326 3327 3328 3329 3330 3331
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
3332
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
3333 3334 3335
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
3336
    esxGetCapabilities,              /* getCapabilities */
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
    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 */
3363
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
3364
    esxDomainXMLToNative,            /* domainXMLToNative */
3365 3366 3367
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
M
Matthias Bolte 已提交
3368
    esxDomainDefineXML,              /* domainDefineXML */
3369
    esxDomainUndefine,               /* domainUndefine */
3370
    NULL,                            /* domainAttachDevice */
3371
    NULL,                            /* domainAttachDeviceFlags */
3372
    NULL,                            /* domainDetachDevice */
3373
    NULL,                            /* domainDetachDeviceFlags */
3374
    NULL,                            /* domainUpdateDeviceFlags */
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
3385
    NULL,                            /* domainMemoryStats */
3386 3387 3388
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
3389
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
3390 3391 3392 3393 3394 3395 3396
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
3397
    NULL,                            /* domainMigratePrepareTunnel */
3398 3399 3400 3401
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
3402
    NULL,                            /* cpuCompare */
3403
    NULL,                            /* cpuBaseline */
3404
    NULL, /* domainGetJobInfo */
3405
    NULL, /* domainAbortJob */
3406
    NULL, /* domainMigrateSetMaxDowntime */
3407 3408
    NULL, /* domainEventRegisterAny */
    NULL, /* domainEventDeregisterAny */
3409 3410 3411 3412 3413 3414 3415
};



int
esxRegister(void)
{
3416 3417 3418 3419 3420 3421 3422 3423
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
        esxSecretRegister() < 0) {
        return -1;
    }
3424 3425 3426

    return 0;
}