esx_driver.c 118.1 KB
Newer Older
1 2

/*
3
 * esx_driver.c: core driver functions for managing VMware ESX hosts
4
 *
E
Eric Blake 已提交
5
 * Copyright (C) 2010 Red Hat, Inc.
6
 * Copyright (C) 2009-2010 Matthias Bolte <matthias.bolte@googlemail.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 * Copyright (C) 2009 Maximilian Wilhelm <max@rfc2324.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

#include <config.h>

#include <netdb.h>

#include "internal.h"
#include "domain_conf.h"
31
#include "authhelper.h"
32 33 34 35 36
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
#include "esx_driver.h"
37 38 39 40 41
#include "esx_interface_driver.h"
#include "esx_network_driver.h"
#include "esx_storage_driver.h"
#include "esx_device_monitor.h"
#include "esx_secret_driver.h"
M
Matthias Bolte 已提交
42
#include "esx_nwfilter_driver.h"
43
#include "esx_private.h"
44 45 46 47 48 49 50 51 52 53 54
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
#include "esx_vmx.h"

#define VIR_FROM_THIS VIR_FROM_ESX

static int esxDomainGetMaxVcpus(virDomainPtr domain);



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

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

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

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

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

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

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

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

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
111
                        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
112 113 114 115
                                  _("Bit 29 (Long Mode) of HostSystem property "
                                    "'hardware.cpuFeature[].edx' with value '%s' "
                                    "has unexpected value '%c', expecting '0' "
                                    "or '1'"), hostCpuIdInfo->edx, edxLongModeBit);
M
Matthias Bolte 已提交
116
                        goto cleanup;
117 118 119 120 121 122 123 124 125 126 127 128 129
                    }

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
130 131 132 133
    /*
     * If we goto cleanup in case of an error then priv->supportsLongMode
     * is still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
134 135 136 137 138 139 140 141 142
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

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

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

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

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

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

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

    result = 0;

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

    return result;
}



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

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

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

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

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

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

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

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

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

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

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

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

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

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



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

328
    /* Decline if the URI is NULL or the scheme is neither 'esx' nor 'gsx' */
329
    if (conn->uri == NULL || conn->uri->scheme == NULL ||
330 331
        (STRCASENEQ(conn->uri->scheme, "esx") &&
         STRCASENEQ(conn->uri->scheme, "gsx"))) {
332 333 334
        return VIR_DRV_OPEN_DECLINED;
    }

M
Matthias Bolte 已提交
335 336 337
    /* Decline URIs without server part, or missing auth */
    if (conn->uri->server == NULL || auth == NULL || auth->cb == NULL) {
        return VIR_DRV_OPEN_DECLINED;
338 339
    }

340 341
    if (conn->uri->path != NULL && STRNEQ(conn->uri->path, "") &&
        STRNEQ(conn->uri->path, "/")) {
M
Matthias Bolte 已提交
342
        VIR_WARN("Ignoring unexpected path '%s' in URI", conn->uri->path);
343 344 345 346
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
347
        virReportOOMError();
M
Matthias Bolte 已提交
348
        goto cleanup;
349 350
    }

351 352 353 354 355 356 357
    if (esxUtil_ParseQuery(&parsedQuery, conn->uri) < 0) {
        goto cleanup;
    }

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

M
Matthias Bolte 已提交
358 359
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
360
    priv->supportsLongMode = esxVI_Boolean_Undefined;
361 362
    priv->autoAnswer = parsedQuery->autoAnswer ? esxVI_Boolean_True
                                               : esxVI_Boolean_False;
363 364
    priv->usedCpuTimeCounterId = -1;

M
Matthias Bolte 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    /*
     * 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;
            }
384
        }
M
Matthias Bolte 已提交
385
    }
386

M
Matthias Bolte 已提交
387
    /* Login to host */
388
    if (esxUtil_ResolveHostname(conn->uri->server, hostIpAddress,
389
                                NI_MAXHOST) < 0) {
M
Matthias Bolte 已提交
390
        goto cleanup;
391 392
    }

M
Matthias Bolte 已提交
393 394
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->transport,
                    conn->uri->server, conn->uri->port) < 0) {
395
        virReportOOMError();
M
Matthias Bolte 已提交
396
        goto cleanup;
M
Matthias Bolte 已提交
397 398 399 400 401 402
    }

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

        if (username == NULL) {
403
            virReportOOMError();
M
Matthias Bolte 已提交
404
            goto cleanup;
405
        }
M
Matthias Bolte 已提交
406
    } else {
407
        username = virRequestUsername(auth, "root", conn->uri->server);
408

M
Matthias Bolte 已提交
409
        if (username == NULL) {
410
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
M
Matthias Bolte 已提交
411
            goto cleanup;
412
        }
M
Matthias Bolte 已提交
413
    }
414

415
    password = virRequestPassword(auth, username, conn->uri->server);
M
Matthias Bolte 已提交
416 417

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

422 423 424
    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, hostIpAddress, username,
                              password, parsedQuery->noVerify) < 0) {
M
Matthias Bolte 已提交
425
        goto cleanup;
M
Matthias Bolte 已提交
426 427 428 429 430
    }

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

444
    /* Query the host for maintenance mode and vCenter IP address */
445
    if (esxVI_String_AppendValueListToList(&propertyNameList,
446 447
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
448 449
        esxVI_LookupHostSystemByIp(priv->host, hostIpAddress, propertyNameList,
                                   &hostSystem) < 0) {
M
Matthias Bolte 已提交
450
        goto cleanup;
451 452 453 454 455 456
    }

    /* Warn if host is in maintenance mode */
    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.inMaintenanceMode")) {
457
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
458
                                         esxVI_Type_Boolean) < 0) {
M
Matthias Bolte 已提交
459
                goto cleanup;
460 461 462 463 464 465 466 467 468 469
            }

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

            break;
        }
    }

M
Matthias Bolte 已提交
470 471
    /* Login to vCenter */
    if (vCenter != NULL) {
472 473 474 475 476 477
        VIR_FREE(url);
        VIR_FREE(password);
        VIR_FREE(username);

        /* If a vCenter is specified resolve the hostname */
        if (STRNEQ(vCenter, "*") &&
478
            esxUtil_ResolveHostname(vCenter, vCenterIpAddress,
479
                                    NI_MAXHOST) < 0) {
M
Matthias Bolte 已提交
480
            goto cleanup;
481 482 483 484 485
        }

        /* Lookup the vCenter from the ESX host */
        for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
486
            if (STREQ(dynamicProperty->name, "summary.managementServerIp")) {
487
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
488
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
489
                    goto cleanup;
490 491 492 493 494 495 496 497 498
                }

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

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

                    if (vCenter == NULL) {
499
                        virReportOOMError();
M
Matthias Bolte 已提交
500
                        goto cleanup;
501 502 503 504
                    }

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

                break;
            }
        }

        if (STREQ(vCenter, "*")) {
527 528
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
529
            goto cleanup;
530 531
        }

M
Matthias Bolte 已提交
532 533
        if (virAsprintf(&url, "%s://%s/sdk", priv->transport,
                        vCenter) < 0) {
534
            virReportOOMError();
M
Matthias Bolte 已提交
535
            goto cleanup;
M
Matthias Bolte 已提交
536
        }
537

538
        if (esxVI_Context_Alloc(&priv->vCenter) < 0) {
M
Matthias Bolte 已提交
539
            goto cleanup;
540 541
        }

542
        username = virRequestUsername(auth, "administrator", vCenter);
M
Matthias Bolte 已提交
543 544

        if (username == NULL) {
545
            ESX_ERROR(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
M
Matthias Bolte 已提交
546
            goto cleanup;
547 548
        }

549
        password = virRequestPassword(auth, username, vCenter);
550 551

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

556
        if (esxVI_Context_Connect(priv->vCenter, url, vCenterIpAddress,
557 558
                                  username, password,
                                  parsedQuery->noVerify) < 0) {
M
Matthias Bolte 已提交
559
            goto cleanup;
560 561
        }

M
Matthias Bolte 已提交
562 563
        if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
            priv->vCenter->productVersion != esxVI_ProductVersion_VPX40) {
564
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
565 566
                      _("%s is neither a vCenter 2.5 server nor a vCenter "
                        "4.0 server"), conn->uri->server);
M
Matthias Bolte 已提交
567
            goto cleanup;
568
        }
569 570 571
    }

    conn->privateData = priv;
572

M
Matthias Bolte 已提交
573
    /* Setup capabilities */
574
    priv->caps = esxCapsInit(priv);
575

M
Matthias Bolte 已提交
576
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
577
        goto cleanup;
578 579
    }

M
Matthias Bolte 已提交
580
    result = VIR_DRV_OPEN_SUCCESS;
581

M
Matthias Bolte 已提交
582 583
  cleanup:
    if (result == VIR_DRV_OPEN_ERROR && priv != NULL) {
584
        esxVI_Context_Free(&priv->host);
M
Matthias Bolte 已提交
585
        esxVI_Context_Free(&priv->vCenter);
586

587 588
        virCapabilitiesFree(priv->caps);

M
Matthias Bolte 已提交
589
        VIR_FREE(priv->transport);
590 591 592
        VIR_FREE(priv);
    }

593 594

    esxUtil_FreeParsedQuery(&parsedQuery);
M
Matthias Bolte 已提交
595 596 597 598 599 600
    VIR_FREE(url);
    VIR_FREE(vCenter);
    VIR_FREE(password);
    VIR_FREE(username);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
601

M
Matthias Bolte 已提交
602
    return result;
603 604 605 606 607 608 609
}



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

E
Eric Blake 已提交
613 614 615 616
    if (esxVI_EnsureSession(priv->host) < 0 ||
        esxVI_Logout(priv->host) < 0) {
        result = -1;
    }
617

M
Matthias Bolte 已提交
618
    esxVI_Context_Free(&priv->host);
619

M
Matthias Bolte 已提交
620
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
621 622 623 624
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
625

M
Matthias Bolte 已提交
626
        esxVI_Context_Free(&priv->vCenter);
627 628
    }

629 630
    virCapabilitiesFree(priv->caps);

631 632 633 634 635
    VIR_FREE(priv->transport);
    VIR_FREE(priv);

    conn->privateData = NULL;

E
Eric Blake 已提交
636
    return result;
637 638 639 640 641
}



static esxVI_Boolean
642
esxSupportsVMotion(esxPrivate *priv)
643 644 645 646 647
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
648 649
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
650 651
    }

652
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
653
        return esxVI_Boolean_Undefined;
654 655
    }

656
    if (esxVI_String_AppendValueToList(&propertyNameList,
657
                                       "capability.vmotionSupported") < 0 ||
658
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
659 660
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
M
Matthias Bolte 已提交
661
        goto cleanup;
662 663 664
    }

    if (hostSystem == NULL) {
665 666
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
667
        goto cleanup;
668 669 670 671 672
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.vmotionSupported")) {
673
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
674
                                         esxVI_Type_Boolean) < 0) {
M
Matthias Bolte 已提交
675
                goto cleanup;
676 677
            }

M
Matthias Bolte 已提交
678
            priv->supportsVMotion = dynamicProperty->val->boolean;
679 680 681 682 683 684 685
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

  cleanup:
M
Matthias Bolte 已提交
686 687 688 689
    /*
     * If we goto cleanup in case of an error then priv->supportsVMotion is
     * still esxVI_Boolean_Undefined, therefore we don't need to set it.
     */
690 691 692
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
693
    return priv->supportsVMotion;
694 695 696 697 698 699 700
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
701
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
702
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
703 704 705

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
706
        supportsVMotion = esxSupportsVMotion(priv);
707

M
Matthias Bolte 已提交
708
        if (supportsVMotion == esxVI_Boolean_Undefined) {
709 710 711
            return -1;
        }

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

      default:
        return 0;
    }
}



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



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

736 737 738
    if (virParseVersionString(priv->host->service->about->version,
                              version) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
739
                  _("Could not parse version number from '%s'"),
740
                  priv->host->service->about->version);
741

742
        return -1;
743 744 745 746 747 748 749 750 751 752
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
753
    esxPrivate *priv = conn->privateData;
754 755 756 757 758 759 760
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

761
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
762
        return NULL;
763 764 765
    }

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

    if (hostSystem == NULL) {
776 777
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
778
        goto cleanup;
779 780 781 782 783 784
    }

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

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

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

M
Matthias Bolte 已提交
804
    if (hostName == NULL || strlen(hostName) < 1) {
805 806
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
807
        goto cleanup;
808 809
    }

M
Matthias Bolte 已提交
810
    if (domainName == NULL || strlen(domainName) < 1) {
811
        complete = strdup(hostName);
812

813
        if (complete == NULL) {
814
            virReportOOMError();
M
Matthias Bolte 已提交
815
            goto cleanup;
816 817 818
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
819
            virReportOOMError();
M
Matthias Bolte 已提交
820
            goto cleanup;
821
        }
822 823 824
    }

  cleanup:
M
Matthias Bolte 已提交
825 826 827 828 829
    /*
     * If we goto cleanup in case of an error then complete is still NULL,
     * either strdup returned NULL or virAsprintf failed. When virAsprintf
     * fails it guarantees setting complete to NULL
     */
830 831 832 833 834 835 836 837 838 839 840
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



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

856
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
857
        return -1;
858 859
    }

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

    if (hostSystem == NULL) {
875 876
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
877
        goto cleanup;
878 879 880 881 882
    }

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

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
891
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
892
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
893
                goto cleanup;
894 895 896 897 898
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
899
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
900
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
901
                goto cleanup;
902 903 904 905 906
            }

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

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
914
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
915
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
916
                goto cleanup;
917 918 919 920 921
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
922
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
923
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
924
                goto cleanup;
925 926 927 928 929
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
930
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
931
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
932
                goto cleanup;
933 934 935 936 937 938
            }

            ptr = dynamicProperty->val->string;

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

                ++ptr;
            }

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

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
968
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
969 970 971 972 973 974 975 976 977
    nodeinfo->nodes = numaInfo_numNodes;
    nodeinfo->sockets = cpuInfo_numCpuPackages;
    nodeinfo->cores = cpuInfo_numCpuPackages > 0
                        ? cpuInfo_numCpuCores / cpuInfo_numCpuPackages
                        : 0;
    nodeinfo->threads = cpuInfo_numCpuCores > 0
                          ? cpuInfo_numCpuThreads / cpuInfo_numCpuCores
                          : 0;

M
Matthias Bolte 已提交
978 979
    result = 0;

980 981 982 983 984 985 986 987 988
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



989 990 991
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
992
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
993
    char *xml = virCapabilitiesFormatXML(priv->caps);
994 995

    if (xml == NULL) {
996
        virReportOOMError();
997 998 999 1000 1001 1002 1003 1004
        return NULL;
    }

    return xml;
}



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

    if (ids == NULL || maxids < 0) {
1017 1018
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
1019 1020 1021 1022 1023 1024
    }

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

1025
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1026
        return -1;
1027 1028
    }

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

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1040
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1041
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1042
            goto cleanup;
1043 1044 1045 1046 1047 1048 1049 1050 1051
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

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

        count++;

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

M
Matthias Bolte 已提交
1065 1066
    success = true;

1067 1068 1069 1070
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1071
    return success ? count : -1;
1072 1073 1074 1075 1076 1077 1078
}



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

1081
    if (esxVI_EnsureSession(priv->host) < 0) {
1082 1083 1084
        return -1;
    }

1085
    return esxVI_LookupNumberOfDomainsByPowerState
1086
             (priv->host, esxVI_VirtualMachinePowerState_PoweredOn,
1087 1088 1089 1090 1091 1092 1093 1094
              esxVI_Boolean_False);
}



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

1105
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1106
        return NULL;
1107 1108
    }

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

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

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

M
Matthias Bolte 已提交
1133
        VIR_FREE(name_candidate);
1134

1135
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1136 1137
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1138
            goto cleanup;
1139 1140
        }

M
Matthias Bolte 已提交
1141
        if (id != id_candidate) {
1142 1143 1144
            continue;
        }

M
Matthias Bolte 已提交
1145
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1146 1147

        if (domain == NULL) {
M
Matthias Bolte 已提交
1148
            goto cleanup;
1149 1150 1151 1152 1153 1154 1155 1156
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1157
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1158 1159 1160 1161 1162
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1163
    VIR_FREE(name_candidate);
1164 1165 1166 1167 1168 1169 1170 1171 1172

    return domain;
}



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

1181
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1182
        return NULL;
1183 1184
    }

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

1196
    domain = virGetDomain(conn, name, uuid);
1197 1198

    if (domain == NULL) {
M
Matthias Bolte 已提交
1199
        goto cleanup;
1200
    }
1201

1202 1203 1204 1205 1206
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1207 1208 1209 1210
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1211 1212
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1213 1214 1215 1216 1217 1218 1219 1220 1221

    return domain;
}



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

1230
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1231
        return NULL;
1232 1233
    }

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

1244
    if (virtualMachine == NULL) {
1245
        ESX_ERROR(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1246
        goto cleanup;
1247
    }
1248 1249


M
Matthias Bolte 已提交
1250 1251 1252
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1253
    }
1254

1255
    domain = virGetDomain(conn, name, uuid);
1256

1257
    if (domain == NULL) {
M
Matthias Bolte 已提交
1258
        goto cleanup;
1259 1260
    }

1261 1262 1263 1264 1265
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1266 1267 1268 1269
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1270
    esxVI_ObjectContent_Free(&virtualMachine);
1271 1272 1273 1274 1275 1276 1277 1278 1279

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1280
    int result = -1;
M
Matthias Bolte 已提交
1281
    esxPrivate *priv = domain->conn->privateData;
1282 1283 1284 1285 1286 1287
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1288
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1289
        return -1;
1290 1291
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1302 1303
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1304
        goto cleanup;
1305 1306
    }

1307 1308 1309
    if (esxVI_SuspendVM_Task(priv->host, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1310
        goto cleanup;
1311 1312 1313
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1314
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not suspend domain"));
M
Matthias Bolte 已提交
1315
        goto cleanup;
1316 1317
    }

M
Matthias Bolte 已提交
1318 1319
    result = 0;

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1333
    int result = -1;
M
Matthias Bolte 已提交
1334
    esxPrivate *priv = domain->conn->privateData;
1335 1336 1337 1338 1339 1340
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1341
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1342
        return -1;
1343 1344
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1355
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1356
        goto cleanup;
1357 1358
    }

1359 1360
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, NULL,
                             &task) < 0 ||
1361 1362
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1363
        goto cleanup;
1364 1365 1366
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1367
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not resume domain"));
M
Matthias Bolte 已提交
1368
        goto cleanup;
1369 1370
    }

M
Matthias Bolte 已提交
1371 1372
    result = 0;

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainShutdown(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1386
    int result = -1;
M
Matthias Bolte 已提交
1387
    esxPrivate *priv = domain->conn->privateData;
1388 1389 1390 1391
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1392
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1393
        return -1;
1394 1395
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1406 1407
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1408
        goto cleanup;
1409 1410
    }

1411
    if (esxVI_ShutdownGuest(priv->host, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1412
        goto cleanup;
1413 1414
    }

M
Matthias Bolte 已提交
1415 1416
    result = 0;

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainReboot(virDomainPtr domain, unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
1429
    int result = -1;
M
Matthias Bolte 已提交
1430
    esxPrivate *priv = domain->conn->privateData;
1431 1432 1433 1434
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1435
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1436
        return -1;
1437 1438
    }

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

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1449 1450
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1451
        goto cleanup;
1452 1453
    }

1454
    if (esxVI_RebootGuest(priv->host, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1455
        goto cleanup;
1456 1457
    }

M
Matthias Bolte 已提交
1458 1459
    result = 0;

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
esxDomainDestroy(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1472
    int result = -1;
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) {
M
Matthias Bolte 已提交
1488
        return -1;
1489 1490
    }

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) {
M
Matthias Bolte 已提交
1497
        goto cleanup;
1498 1499 1500
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1501 1502
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered on"));
M
Matthias Bolte 已提交
1503
        goto cleanup;
1504 1505
    }

1506 1507 1508
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid, priv->autoAnswer,
                                    &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1509
        goto cleanup;
1510 1511 1512
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1513
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not destroy domain"));
M
Matthias Bolte 已提交
1514
        goto cleanup;
1515 1516
    }

M
Matthias Bolte 已提交
1517 1518
    result = 0;

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



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

    if (osType == NULL) {
1535
        virReportOOMError();
1536 1537 1538 1539
        return NULL;
    }

    return osType;
1540 1541 1542 1543 1544 1545 1546
}



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

1553
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1554
        return 0;
1555 1556
    }

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

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
1568
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1569
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1570
                goto cleanup;
1571 1572 1573
            }

            if (dynamicProperty->val->int32 < 0) {
1574 1575
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                          _("Got invalid memory size %d"),
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
                          dynamicProperty->val->int32);
            } else {
                memoryMB = dynamicProperty->val->int32;
            }

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

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

    return memoryMB * 1024; /* Scale from megabyte to kilobyte */
}



static int
esxDomainSetMaxMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
1599
    int result = -1;
M
Matthias Bolte 已提交
1600
    esxPrivate *priv = domain->conn->privateData;
1601 1602 1603 1604 1605
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

1606
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1607
        return -1;
1608 1609
    }

1610
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1611
          (priv->host, domain->uuid, NULL, &virtualMachine,
1612
           priv->autoAnswer) < 0 ||
1613 1614
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
1615
        goto cleanup;
1616 1617 1618 1619 1620
    }

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

1621 1622 1623 1624
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1625
        goto cleanup;
1626 1627 1628
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1629
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1630
                  _("Could not set max-memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
1631
        goto cleanup;
1632 1633
    }

M
Matthias Bolte 已提交
1634 1635
    result = 0;

1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



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

1656
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1657
        return -1;
1658 1659
    }

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

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

1672 1673 1674 1675
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
1676
        goto cleanup;
1677 1678 1679
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1680
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
1681
                  _("Could not set memory to %lu kilobytes"), memory);
M
Matthias Bolte 已提交
1682
        goto cleanup;
1683 1684
    }

M
Matthias Bolte 已提交
1685 1686
    result = 0;

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



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

M
Matthias Bolte 已提交
1720 1721
    memset(info, 0, sizeof (*info));

1722
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1723
        return -1;
1724 1725
    }

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

    info->state = VIR_DOMAIN_NOSTATE;

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

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

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

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

            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) {
1785
        if (esxVI_Int_Alloc(&counterId) < 0) {
M
Matthias Bolte 已提交
1786
            goto cleanup;
1787 1788 1789 1790
        }

        counterId->value = priv->usedCpuTimeCounterId;

1791
        if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
M
Matthias Bolte 已提交
1792
            goto cleanup;
1793 1794
        }

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

        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) {
1818 1819 1820
        if (esxVI_QueryAvailablePerfMetric(priv->host, virtualMachine->obj,
                                           NULL, NULL, NULL,
                                           &perfMetricIdList) < 0) {
M
Matthias Bolte 已提交
1821
            goto cleanup;
1822 1823 1824 1825 1826 1827 1828 1829 1830
        }

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

            counterId = NULL;

1831 1832
            if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
M
Matthias Bolte 已提交
1833
                goto cleanup;
1834 1835 1836
            }
        }

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

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

1873 1874 1875 1876
        if (esxVI_PerfQuerySpec_Alloc(&querySpec) < 0 ||
            esxVI_Int_Alloc(&querySpec->maxSample) < 0 ||
            esxVI_PerfMetricId_Alloc(&querySpec->metricId) < 0 ||
            esxVI_Int_Alloc(&querySpec->metricId->counterId) < 0) {
M
Matthias Bolte 已提交
1877
            goto cleanup;
1878 1879 1880 1881 1882 1883 1884 1885
        }

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

1886 1887
        if (esxVI_QueryPerf(priv->host, querySpec,
                            &perfEntityMetricBaseList) < 0) {
1888 1889 1890
            querySpec->entity = NULL;
            querySpec->metricId->instance = NULL;
            querySpec->format = NULL;
M
Matthias Bolte 已提交
1891
            goto cleanup;
1892 1893
        }

1894 1895 1896
        for (perfEntityMetricBase = perfEntityMetricBaseList;
             perfEntityMetricBase != NULL;
             perfEntityMetricBase = perfEntityMetricBase->_next) {
1897 1898
            VIR_DEBUG0("perfEntityMetric ...");

1899 1900 1901 1902
            perfEntityMetric =
              esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);

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

1906 1907 1908 1909
            perfMetricIntSeries =
              esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);

            if (perfMetricIntSeries == NULL) {
1910
                VIR_ERROR0(_("QueryPerf returned object with unexpected type"));
1911 1912 1913
            }

            for (; perfMetricIntSeries != NULL;
1914 1915 1916 1917 1918 1919
                 perfMetricIntSeries = perfMetricIntSeries->_next) {
                VIR_DEBUG0("perfMetricIntSeries ...");

                for (value = perfMetricIntSeries->value;
                     value != NULL;
                     value = value->_next) {
1920
                    VIR_DEBUG("value %lld", (long long int)value->value);
1921 1922 1923 1924 1925 1926 1927 1928 1929
                }
            }
        }

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

        VIR_DEBUG("usedCpuTimeCounterId %d END", priv->usedCpuTimeCounterId);
M
Matthias Bolte 已提交
1930 1931 1932 1933 1934

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

M
Matthias Bolte 已提交
1937 1938
    result = 0;

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

    return result;
}



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

    if (nvcpus < 1) {
1965 1966
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
1967
        return -1;
1968 1969
    }

1970
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
1971
        return -1;
1972 1973
    }

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

M
Matthias Bolte 已提交
1976
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
1977
        return -1;
1978 1979
    }

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

1988
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1989
          (priv->host, domain->uuid, NULL, &virtualMachine,
1990
           priv->autoAnswer) < 0 ||
1991 1992
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
1993
        goto cleanup;
1994 1995 1996 1997
    }

    spec->numCPUs->value = nvcpus;

1998 1999 2000 2001
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2002
        goto cleanup;
2003 2004 2005
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2006
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2007
                  _("Could not set number of virtual CPUs to %d"), nvcpus);
M
Matthias Bolte 已提交
2008
        goto cleanup;
2009 2010
    }

M
Matthias Bolte 已提交
2011 2012
    result = 0;

2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2026
    esxPrivate *priv = domain->conn->privateData;
2027 2028 2029 2030
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

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

M
Matthias Bolte 已提交
2035 2036
    priv->maxVcpus = -1;

2037
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2038
        return -1;
2039 2040
    }

2041
    if (esxVI_String_AppendValueToList(&propertyNameList,
2042
                                       "capability.maxSupportedVcpus") < 0 ||
2043 2044 2045
        esxVI_LookupObjectContentByType(priv->host, priv->host->hostFolder,
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_True, &hostSystem) < 0) {
M
Matthias Bolte 已提交
2046
        goto cleanup;
2047 2048 2049
    }

    if (hostSystem == NULL) {
2050 2051
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve the HostSystem object"));
M
Matthias Bolte 已提交
2052
        goto cleanup;
2053 2054 2055 2056 2057
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2058
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2059
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2060
                goto cleanup;
2061 2062
            }

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

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

M
Matthias Bolte 已提交
2074
    return priv->maxVcpus;
2075 2076 2077 2078 2079 2080 2081
}



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

2096
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2097
        return NULL;
2098 2099
    }

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

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

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

2121 2122
    if (esxUtil_ParseDatastoreRelatedPath(vmPathName, &datastoreName,
                                          &directoryName, &fileName) < 0) {
M
Matthias Bolte 已提交
2123
        goto cleanup;
2124 2125
    }

2126 2127
    virBufferVSprintf(&buffer, "%s://%s:%d/folder/", priv->transport,
                      domain->conn->uri->server, domain->conn->uri->port);
M
Matthias Bolte 已提交
2128 2129 2130 2131 2132 2133 2134

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

    virBufferURIEncodeString(&buffer, fileName);
2135 2136 2137 2138 2139 2140
    virBufferAddLit(&buffer, "?dcPath=");
    virBufferURIEncodeString(&buffer, priv->host->datacenter->value);
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2141
        virReportOOMError();
M
Matthias Bolte 已提交
2142
        goto cleanup;
2143 2144
    }

2145 2146
    url = virBufferContentAndReset(&buffer);

2147
    if (esxVI_Context_DownloadFile(priv->host, url, &vmx) < 0) {
M
Matthias Bolte 已提交
2148
        goto cleanup;
2149 2150
    }

2151
    def = esxVMX_ParseConfig(priv->host, vmx, datastoreName, directoryName,
2152
                             priv->host->productVersion);
2153 2154

    if (def != NULL) {
2155
        xml = virDomainDefFormat(def, flags);
2156 2157 2158
    }

  cleanup:
M
Matthias Bolte 已提交
2159 2160 2161 2162
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2163 2164
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2165
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2166 2167
    VIR_FREE(directoryName);
    VIR_FREE(fileName);
2168 2169
    VIR_FREE(url);
    VIR_FREE(vmx);
2170
    virDomainDefFree(def);
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
                       unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2182
    esxPrivate *priv = conn->privateData;
2183 2184 2185 2186
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2187
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2188
                  _("Unsupported config format '%s'"), nativeFormat);
2189
        return NULL;
2190 2191
    }

2192
    def = esxVMX_ParseConfig(priv->host, nativeConfig, "?", "?",
2193
                             priv->host->productVersion);
2194 2195

    if (def != NULL) {
2196
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2197 2198 2199 2200 2201 2202 2203 2204 2205
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2206 2207 2208 2209 2210
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
                     unsigned int flags ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2211
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2212 2213 2214 2215
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2216
        ESX_ERROR(VIR_ERR_INVALID_ARG,
2217
                  _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2218 2219 2220
        return NULL;
    }

2221
    def = virDomainDefParseString(priv->caps, domainXml, 0);
M
Matthias Bolte 已提交
2222 2223 2224 2225 2226

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

2227
    vmx = esxVMX_FormatConfig(priv->host, def, priv->host->productVersion);
M
Matthias Bolte 已提交
2228 2229 2230 2231 2232 2233 2234 2235

    virDomainDefFree(def);

    return vmx;
}



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

    if (names == NULL || maxnames < 0) {
2250 2251
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
2252 2253 2254 2255 2256 2257
    }

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

2258
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2259
        return -1;
2260 2261
    }

2262
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2263 2264
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2265
        esxVI_LookupObjectContentByType(priv->host, priv->host->vmFolder,
2266 2267 2268
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2269
        goto cleanup;
2270 2271 2272 2273
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2274
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2275
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2276
            goto cleanup;
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2287
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2288
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2289
                    goto cleanup;
2290 2291 2292 2293 2294
                }

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

                if (names[count] == NULL) {
2295
                    virReportOOMError();
M
Matthias Bolte 已提交
2296
                    goto cleanup;
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
                }

                count++;
                break;
            }
        }

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

M
Matthias Bolte 已提交
2309
    success = true;
2310

M
Matthias Bolte 已提交
2311 2312 2313 2314 2315
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2316

M
Matthias Bolte 已提交
2317
        count = -1;
2318 2319
    }

M
Matthias Bolte 已提交
2320 2321
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2322

M
Matthias Bolte 已提交
2323
    return count;
2324 2325 2326 2327 2328 2329 2330
}



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

2333
    if (esxVI_EnsureSession(priv->host) < 0) {
2334 2335 2336
        return -1;
    }

2337
    return esxVI_LookupNumberOfDomainsByPowerState
2338
             (priv->host, esxVI_VirtualMachinePowerState_PoweredOn,
2339 2340 2341 2342 2343 2344 2345 2346
              esxVI_Boolean_True);
}



static int
esxDomainCreate(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2347
    int result = -1;
M
Matthias Bolte 已提交
2348
    esxPrivate *priv = domain->conn->privateData;
2349 2350 2351 2352 2353 2354
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

2355
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2356
        return -1;
2357 2358
    }

2359
    if (esxVI_String_AppendValueToList(&propertyNameList,
2360
                                       "runtime.powerState") < 0 ||
2361
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2362 2363 2364
          (priv->host, domain->uuid, propertyNameList, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine,
2365
                                          &powerState) < 0) {
M
Matthias Bolte 已提交
2366
        goto cleanup;
2367 2368 2369
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2370 2371
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not powered off"));
M
Matthias Bolte 已提交
2372
        goto cleanup;
2373 2374
    }

2375 2376
    if (esxVI_PowerOnVM_Task(priv->host, virtualMachine->obj, NULL,
                             &task) < 0 ||
2377 2378
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2379
        goto cleanup;
2380 2381 2382
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2383
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not start domain"));
M
Matthias Bolte 已提交
2384
        goto cleanup;
2385 2386
    }

M
Matthias Bolte 已提交
2387 2388
    result = 0;

2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



M
Matthias Bolte 已提交
2399 2400 2401
static virDomainPtr
esxDomainDefineXML(virConnectPtr conn, const char *xml ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2402
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
2403 2404
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
2405 2406
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
    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;

2421
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2422
        return NULL;
M
Matthias Bolte 已提交
2423 2424 2425
    }

    /* Parse domain XML */
2426
    def = virDomainDefParseString(priv->caps, xml,
M
Matthias Bolte 已提交
2427 2428 2429
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
2430
        return NULL;
M
Matthias Bolte 已提交
2431 2432 2433
    }

    /* Check if an existing domain should be edited */
2434
    if (esxVI_LookupVirtualMachineByUuid(priv->host, def->uuid, NULL,
M
Matthias Bolte 已提交
2435
                                         &virtualMachine,
M
Matthias Bolte 已提交
2436
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
2437
        goto cleanup;
M
Matthias Bolte 已提交
2438 2439 2440 2441
    }

    if (virtualMachine != NULL) {
        /* FIXME */
2442 2443 2444
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain already exists, editing existing domains is not "
                    "supported yet"));
M
Matthias Bolte 已提交
2445
        goto cleanup;
M
Matthias Bolte 已提交
2446 2447 2448
    }

    /* Build VMX from domain XML */
2449
    vmx = esxVMX_FormatConfig(priv->host, def, priv->host->productVersion);
M
Matthias Bolte 已提交
2450 2451

    if (vmx == NULL) {
M
Matthias Bolte 已提交
2452
        goto cleanup;
M
Matthias Bolte 已提交
2453 2454
    }

2455 2456 2457 2458 2459 2460 2461
    /*
     * 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 已提交
2462
    if (def->ndisks < 1) {
2463 2464 2465
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain XML doesn't contain any disks, cannot deduce "
                    "datastore and path for VMX file"));
M
Matthias Bolte 已提交
2466
        goto cleanup;
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
    }

    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) {
2478 2479 2480
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Domain XML doesn't contain any file-based harddisks, "
                    "cannot deduce datastore and path for VMX file"));
M
Matthias Bolte 已提交
2481
        goto cleanup;
M
Matthias Bolte 已提交
2482 2483
    }

2484
    if (disk->src == NULL) {
2485 2486 2487
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("First file-based harddisk has no source, cannot deduce "
                    "datastore and path for VMX file"));
M
Matthias Bolte 已提交
2488
        goto cleanup;
M
Matthias Bolte 已提交
2489 2490
    }

2491
    if (esxUtil_ParseDatastoreRelatedPath(disk->src, &datastoreName,
2492
                                          &directoryName, &fileName) < 0) {
M
Matthias Bolte 已提交
2493
        goto cleanup;
M
Matthias Bolte 已提交
2494 2495
    }

2496
    if (! virFileHasSuffix(fileName, ".vmdk")) {
2497
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2498 2499
                  _("Expecting source '%s' of first file-based harddisk to "
                    "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
2500
        goto cleanup;
M
Matthias Bolte 已提交
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
    }

    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)) {
2518
        virReportOOMError();
M
Matthias Bolte 已提交
2519
        goto cleanup;
M
Matthias Bolte 已提交
2520 2521 2522 2523 2524 2525 2526
    }

    url = virBufferContentAndReset(&buffer);

    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
                        directoryName, def->name) < 0) {
2527
            virReportOOMError();
M
Matthias Bolte 已提交
2528
            goto cleanup;
M
Matthias Bolte 已提交
2529 2530 2531 2532
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
                        def->name) < 0) {
2533
            virReportOOMError();
M
Matthias Bolte 已提交
2534
            goto cleanup;
M
Matthias Bolte 已提交
2535 2536 2537 2538
        }
    }

    /* Get resource pool */
2539 2540
    if (esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->host, priv->host->ipAddress,
M
Matthias Bolte 已提交
2541
                                   propertyNameList, &hostSystem) < 0) {
M
Matthias Bolte 已提交
2542
        goto cleanup;
M
Matthias Bolte 已提交
2543 2544
    }

2545
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
2546
                                             &resourcePool) < 0) {
M
Matthias Bolte 已提交
2547
        goto cleanup;
M
Matthias Bolte 已提交
2548 2549 2550 2551 2552 2553
    }

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

    /* Upload VMX file */
2554
    if (esxVI_Context_UploadFile(priv->host, url, vmx) < 0) {
M
Matthias Bolte 已提交
2555
        goto cleanup;
M
Matthias Bolte 已提交
2556 2557 2558
    }

    /* Register the domain */
2559
    if (esxVI_RegisterVM_Task(priv->host, priv->host->vmFolder,
M
Matthias Bolte 已提交
2560 2561
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
                              resourcePool, hostSystem->obj, &task) < 0 ||
2562 2563
        esxVI_WaitForTaskCompletion(priv->host, task, def->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2564
        goto cleanup;
M
Matthias Bolte 已提交
2565 2566 2567
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2568
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not define domain"));
M
Matthias Bolte 已提交
2569
        goto cleanup;
M
Matthias Bolte 已提交
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
    }

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

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

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

  cleanup:
M
Matthias Bolte 已提交
2581 2582 2583 2584
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
    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;
}



2603 2604 2605
static int
esxDomainUndefine(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2606
    int result = -1;
M
Matthias Bolte 已提交
2607
    esxPrivate *priv = domain->conn->privateData;
2608
    esxVI_Context *ctx = NULL;
2609 2610 2611 2612
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

2613 2614 2615 2616 2617 2618
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

2619
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
2620
        return -1;
2621 2622
    }

2623
    if (esxVI_String_AppendValueToList(&propertyNameList,
2624
                                       "runtime.powerState") < 0 ||
2625 2626
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
2627
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2628
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
2629
        goto cleanup;
2630 2631 2632 2633
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2634 2635
        ESX_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                  _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
2636
        goto cleanup;
2637 2638
    }

2639
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
2640
        goto cleanup;
2641 2642
    }

M
Matthias Bolte 已提交
2643 2644
    result = 0;

2645 2646 2647 2648 2649 2650 2651 2652 2653
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665
/*
 * 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)
 *
2666
 *   The amount of CPU resource that is guaranteed to be available to the domain.
2667 2668 2669 2670
 *
 *
 * - limit (VIR_DOMAIN_SCHED_FIELD_LLONG >= 0, or -1, in megaherz)
 *
2671 2672
 *   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
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
 *   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'.
 */
2684
static char *
2685
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
2686 2687 2688 2689
{
    char *type = strdup("allocation");

    if (type == NULL) {
2690
        virReportOOMError();
2691
        return NULL;
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
    }

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

    return type;
}



static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int *nparams)
{
M
Matthias Bolte 已提交
2705
    int result = -1;
M
Matthias Bolte 已提交
2706
    esxPrivate *priv = domain->conn->privateData;
2707 2708 2709 2710 2711 2712 2713 2714
    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) {
2715 2716
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Parameter array must have space for 3 items"));
M
Matthias Bolte 已提交
2717
        return -1;
2718 2719
    }

2720
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2721
        return -1;
2722 2723
    }

2724
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2725 2726 2727
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
2728 2729
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2730
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2731
        goto cleanup;
2732 2733 2734 2735 2736 2737
    }

    for (dynamicProperty = virtualMachine->propSet;
         dynamicProperty != NULL && mask != 7 && i < 3;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
2738
            ! (mask & (1 << 0))) {
2739 2740 2741 2742 2743
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "reservation");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

2744
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2745
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2746
                goto cleanup;
2747 2748 2749 2750 2751 2752 2753
            }

            params[i].value.l = dynamicProperty->val->int64;
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
2754
                   ! (mask & (1 << 1))) {
2755 2756 2757 2758 2759
            snprintf (params[i].field, VIR_DOMAIN_SCHED_FIELD_LENGTH, "%s",
                      "limit");

            params[i].type = VIR_DOMAIN_SCHED_FIELD_LLONG;

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

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

            params[i].type = VIR_DOMAIN_SCHED_FIELD_INT;

2776
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
2777
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
2778
                goto cleanup;
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
            }

            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:
2799
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
2800
                          _("Shares level has unknown value %d"),
2801
                          (int)sharesInfo->level);
M
Matthias Bolte 已提交
2802
                goto cleanup;
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
2815
    result = 0;
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829

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

    return result;
}



static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virSchedParameterPtr params, int nparams)
{
M
Matthias Bolte 已提交
2830
    int result = -1;
M
Matthias Bolte 已提交
2831
    esxPrivate *priv = domain->conn->privateData;
2832 2833 2834 2835 2836 2837 2838
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    int i;

2839
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
2840
        return -1;
2841 2842
    }

2843
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2844
          (priv->host, domain->uuid, NULL, &virtualMachine,
2845
           priv->autoAnswer) < 0 ||
2846 2847
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
2848
        goto cleanup;
2849 2850 2851 2852 2853
    }

    for (i = 0; i < nparams; ++i) {
        if (STREQ (params[i].field, "reservation") &&
            params[i].type == VIR_DOMAIN_SCHED_FIELD_LLONG) {
2854
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
2855
                goto cleanup;
2856 2857 2858
            }

            if (params[i].value.l < 0) {
2859
                ESX_ERROR(VIR_ERR_INVALID_ARG,
2860 2861
                          _("Could not set reservation to %lld MHz, expecting "
                            "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
2862
                goto cleanup;
2863 2864 2865 2866 2867
            }

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

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

            spec->cpuAllocation->limit->value = params[i].value.l;
        } else if (STREQ (params[i].field, "shares") &&
2882
                   params[i].type == VIR_DOMAIN_SCHED_FIELD_INT) {
2883 2884
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
2885
                goto cleanup;
2886 2887 2888 2889
            }

            spec->cpuAllocation->shares = sharesInfo;

2890
            if (params[i].value.i >= 0) {
2891
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
2892
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
2893
            } else {
2894
                switch (params[i].value.i) {
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
                  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:
2913
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
2914 2915
                              _("Could not set shares to %d, expecting positive "
                                "value or -1 (low), -2 (normal) or -3 (high)"),
2916
                              params[i].value.i);
M
Matthias Bolte 已提交
2917
                    goto cleanup;
2918 2919 2920
                }
            }
        } else {
2921
            ESX_ERROR(VIR_ERR_INVALID_ARG, _("Unknown field '%s'"),
2922
                      params[i].field);
M
Matthias Bolte 已提交
2923
            goto cleanup;
2924 2925 2926
        }
    }

2927 2928 2929 2930
    if (esxVI_ReconfigVM_Task(priv->host, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
2931
        goto cleanup;
2932 2933 2934
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2935 2936
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not change scheduler parameters"));
M
Matthias Bolte 已提交
2937
        goto cleanup;
2938 2939
    }

M
Matthias Bolte 已提交
2940 2941
    result = 0;

2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
                        const char *uri_in, char **uri_out,
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2961
    int result = -1;
2962
    esxUtil_ParsedQuery *parsedQuery = NULL;
2963 2964

    if (uri_in == NULL) {
2965
        if (esxUtil_ParseQuery(&parsedQuery, dconn->uri) < 0) {
2966 2967 2968
            return -1;
        }

2969
        if (virAsprintf(uri_out, "%s://%s:%d/sdk", parsedQuery->transport,
2970
                        dconn->uri->server, dconn->uri->port) < 0) {
2971
            virReportOOMError();
M
Matthias Bolte 已提交
2972
            goto cleanup;
2973 2974 2975
        }
    }

M
Matthias Bolte 已提交
2976 2977
    result = 0;

2978
  cleanup:
2979
    esxUtil_FreeParsedQuery(&parsedQuery);
2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994

    return result;
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
                        unsigned long flags ATTRIBUTE_UNUSED,
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
2995
    int result = -1;
M
Matthias Bolte 已提交
2996
    esxPrivate *priv = domain->conn->privateData;
2997
    xmlURIPtr xmlUri = NULL;
M
Matthias Bolte 已提交
2998
    char hostIpAddress[NI_MAXHOST] = "";
2999 3000 3001 3002 3003 3004 3005 3006
    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 已提交
3007
    if (priv->vCenter == NULL) {
3008 3009
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3010
        return -1;
3011 3012 3013
    }

    if (dname != NULL) {
3014 3015
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                  _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3016
        return -1;
3017 3018
    }

3019
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3020
        return -1;
3021 3022 3023 3024 3025 3026
    }

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

    if (xmlUri == NULL) {
3027
        virReportOOMError();
M
Matthias Bolte 已提交
3028
        return -1;
3029 3030
    }

3031
    if (esxUtil_ResolveHostname(xmlUri->server, hostIpAddress,
3032
                                NI_MAXHOST) < 0) {
M
Matthias Bolte 已提交
3033
        goto cleanup;
3034 3035 3036
    }

    /* Lookup VirtualMachine, HostSystem and ResourcePool */
3037
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3038
          (priv->vCenter, domain->uuid, NULL, &virtualMachine,
3039
           priv->autoAnswer) < 0 ||
3040 3041
        esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->vCenter, hostIpAddress,
M
Matthias Bolte 已提交
3042
                                   propertyNameList, &hostSystem) < 0) {
M
Matthias Bolte 已提交
3043
        goto cleanup;
3044 3045
    }

3046 3047
    if (esxVI_LookupResourcePoolByHostSystem(priv->vCenter, hostSystem,
                                             &resourcePool) < 0) {
M
Matthias Bolte 已提交
3048
        goto cleanup;
3049 3050 3051
    }

    /* Validate the purposed migration */
3052
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3053 3054 3055
                                esxVI_VirtualMachinePowerState_Undefined,
                                NULL, resourcePool, hostSystem->obj,
                                &eventList) < 0) {
M
Matthias Bolte 已提交
3056
        goto cleanup;
3057 3058 3059 3060 3061 3062 3063 3064
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3065
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
3066 3067
                      _("Could not migrate domain, validation reported a "
                        "problem: %s"), eventList->fullFormattedMessage);
3068
        } else {
3069 3070 3071
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                      _("Could not migrate domain, validation reported a "
                        "problem"));
3072 3073
        }

M
Matthias Bolte 已提交
3074
        goto cleanup;
3075 3076 3077
    }

    /* Perform the purposed migration */
3078
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj, resourcePool,
3079 3080 3081 3082
                             hostSystem->obj,
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
3083 3084
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3085
        goto cleanup;
3086 3087 3088
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3089 3090 3091
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not migrate domain, migration task finished with "
                    "an error"));
M
Matthias Bolte 已提交
3092
        goto cleanup;
3093 3094
    }

M
Matthias Bolte 已提交
3095 3096
    result = 0;

3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
  cleanup:
    xmlFreeURI(xmlUri);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_ManagedObjectReference_Free(&resourcePool);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



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



M
Matthias Bolte 已提交
3123 3124 3125 3126
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
3127
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3128 3129 3130 3131 3132 3133 3134
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

3135
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3136
        return 0;
M
Matthias Bolte 已提交
3137 3138 3139
    }

    /* Lookup host system with its resource pool */
3140 3141
    if (esxVI_String_AppendValueToList(&propertyNameList, "parent") < 0 ||
        esxVI_LookupHostSystemByIp(priv->host, priv->host->ipAddress,
M
Matthias Bolte 已提交
3142
                                   propertyNameList, &hostSystem) < 0) {
M
Matthias Bolte 已提交
3143
        goto cleanup;
M
Matthias Bolte 已提交
3144 3145
    }

3146
    if (esxVI_LookupResourcePoolByHostSystem(priv->host, hostSystem,
3147
                                             &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
3148
        goto cleanup;
M
Matthias Bolte 已提交
3149 3150 3151 3152 3153
    }

    esxVI_String_Free(&propertyNameList);

    /* Get memory usage of resource pool */
3154
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
3155
                                       "runtime.memory") < 0 ||
3156
        esxVI_LookupObjectContentByType(priv->host, managedObjectReference,
3157 3158 3159
                                        "ResourcePool", propertyNameList,
                                        esxVI_Boolean_False,
                                        &resourcePool) < 0) {
M
Matthias Bolte 已提交
3160
        goto cleanup;
M
Matthias Bolte 已提交
3161 3162 3163 3164 3165 3166
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
3167
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
3168
                goto cleanup;
M
Matthias Bolte 已提交
3169 3170 3171 3172 3173 3174 3175 3176 3177
            }

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

    if (resourcePoolResourceUsage == NULL) {
3178 3179
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
3180
        goto cleanup;
M
Matthias Bolte 已提交
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
    }

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



3197 3198 3199
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
3200
    esxPrivate *priv = conn->privateData;
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213

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



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

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



static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
3228
    int result = -1;
M
Matthias Bolte 已提交
3229
    esxPrivate *priv = domain->conn->privateData;
3230 3231 3232 3233
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3234
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3235
        return -1;
3236 3237
    }

3238
    if (esxVI_String_AppendValueToList(&propertyNameList,
3239
                                       "runtime.powerState") < 0 ||
3240 3241
        esxVI_LookupVirtualMachineByUuid(priv->host, domain->uuid,
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3242
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3243
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3244
        goto cleanup;
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
    }

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

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

    return result;
}



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



3271 3272
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
3273
                           unsigned int flags)
3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
{
    esxPrivate *priv = domain->conn->privateData;
    virDomainSnapshotDefPtr def = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    virDomainSnapshotPtr snapshot = NULL;

3285 3286
    virCheckFlags(0, NULL);

3287
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3288
        return NULL;
3289 3290 3291 3292 3293
    }

    def = virDomainSnapshotDefParseString(xmlDesc, 1);

    if (def == NULL) {
M
Matthias Bolte 已提交
3294
        return NULL;
3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
    }

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->host, domain->uuid, NULL, &virtualMachine,
           priv->autoAnswer) < 0 ||
        esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3305
        goto cleanup;
3306 3307 3308 3309 3310
    }

    if (snapshotTree != NULL) {
        ESX_ERROR(VIR_ERR_OPERATION_INVALID,
                  _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
3311
        goto cleanup;
3312 3313 3314 3315 3316 3317 3318 3319
    }

    if (esxVI_CreateSnapshot_Task(priv->host, virtualMachine->obj,
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3320
        goto cleanup;
3321 3322 3323 3324
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create snapshot"));
M
Matthias Bolte 已提交
3325
        goto cleanup;
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342
    }

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

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

    return snapshot;
}



static char *
esxDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
3343
                         unsigned int flags)
3344 3345 3346 3347 3348 3349 3350 3351 3352
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotDef def;
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
    char *xml = NULL;

3353 3354
    virCheckFlags(0, NULL);

M
Matthias Bolte 已提交
3355
    memset(&def, 0, sizeof (def));
3356 3357

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3358
        return NULL;
3359 3360 3361 3362 3363 3364 3365
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3366
        goto cleanup;
3367 3368 3369 3370 3371 3372 3373 3374
    }

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

    if (esxVI_DateTime_ConvertToCalendarTime(snapshotTree->createTime,
                                             &def.creationTime) < 0) {
M
Matthias Bolte 已提交
3375
        goto cleanup;
3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393
    }

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

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

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

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
3394
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
3395
{
M
Matthias Bolte 已提交
3396
    int count;
3397 3398 3399
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3400 3401
    virCheckFlags(0, -1);

3402
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3403
        return -1;
3404 3405 3406 3407
    }

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

M
Matthias Bolte 已提交
3411
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList);
3412 3413 3414

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
3415
    return count;
3416 3417 3418 3419 3420 3421
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
3422
                           unsigned int flags)
3423
{
M
Matthias Bolte 已提交
3424
    int result;
3425 3426 3427
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;

3428 3429
    virCheckFlags(0, -1);

3430 3431 3432 3433 3434 3435 3436 3437 3438 3439
    if (names == NULL || nameslen < 0) {
        ESX_ERROR(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
        return -1;
    }

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

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3440
        return -1;
3441 3442 3443 3444
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, domain->uuid,
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3445
        return -1;
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
    }

    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen);

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
3459
                              unsigned int flags)
3460 3461 3462 3463 3464 3465 3466
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr snapshot = NULL;

3467 3468
    virCheckFlags(0, NULL);

3469
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3470
        return NULL;
3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
    }

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

    snapshot = virGetDomainSnapshot(domain, name);

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return snapshot;
}



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

3497
    virCheckFlags(0, -1);
3498 3499

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3500
        return -1;
3501 3502 3503 3504 3505
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->host, domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3506
        return -1;
3507 3508 3509
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
3510 3511
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
3512 3513
    }

M
Matthias Bolte 已提交
3514
    return 0;
3515 3516 3517 3518 3519 3520 3521 3522 3523
}



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

3526
    virCheckFlags(0, NULL);
3527 3528

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3529
        return NULL;
3530 3531 3532 3533 3534
    }

    if (esxVI_LookupCurrentSnapshotTree(priv->host, domain->uuid,
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3535
        return NULL;
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}



static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
3550
    int result = -1;
3551 3552 3553 3554 3555 3556 3557
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

3558
    virCheckFlags(0, -1);
3559 3560

    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3561
        return -1;
3562 3563 3564 3565 3566 3567 3568
    }

    if (esxVI_LookupRootSnapshotTreeList(priv->host, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3569
        goto cleanup;
3570 3571 3572 3573 3574 3575
    }

    if (esxVI_RevertToSnapshot_Task(priv->host, snapshotTree->snapshot, NULL,
                                    &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, snapshot->domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3576
        goto cleanup;
3577 3578 3579 3580 3581
    }

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

M
Matthias Bolte 已提交
3585 3586
    result = 0;

3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
3599
    int result = -1;
3600 3601 3602 3603 3604 3605 3606 3607
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    esxVI_Boolean removeChildren = esxVI_Boolean_False;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;

3608 3609
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

3610
    if (esxVI_EnsureSession(priv->host) < 0) {
M
Matthias Bolte 已提交
3611
        return -1;
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
    }

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

    if (esxVI_LookupRootSnapshotTreeList(priv->host, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3623
        goto cleanup;
3624 3625 3626 3627 3628 3629
    }

    if (esxVI_RemoveSnapshot_Task(priv->host, snapshotTree->snapshot,
                                  removeChildren, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->host, task, snapshot->domain->uuid,
                                    priv->autoAnswer, &taskInfoState) < 0) {
M
Matthias Bolte 已提交
3630
        goto cleanup;
3631 3632 3633 3634 3635
    }

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

M
Matthias Bolte 已提交
3639 3640
    result = 0;

3641 3642 3643 3644 3645 3646 3647 3648 3649
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);

    return result;
}



3650 3651 3652 3653 3654 3655 3656 3657
static virDriver esxDriver = {
    VIR_DRV_ESX,
    "ESX",
    esxOpen,                         /* open */
    esxClose,                        /* close */
    esxSupportsFeature,              /* supports_feature */
    esxGetType,                      /* type */
    esxGetVersion,                   /* version */
3658
    NULL,                            /* libvirtVersion (impl. in libvirt.c) */
3659 3660 3661
    esxGetHostname,                  /* hostname */
    NULL,                            /* getMaxVcpus */
    esxNodeGetInfo,                  /* nodeGetInfo */
3662
    esxGetCapabilities,              /* getCapabilities */
3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688
    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 */
3689
    esxDomainXMLFromNative,          /* domainXMLFromNative */
M
Matthias Bolte 已提交
3690
    esxDomainXMLToNative,            /* domainXMLToNative */
3691 3692 3693
    esxListDefinedDomains,           /* listDefinedDomains */
    esxNumberOfDefinedDomains,       /* numOfDefinedDomains */
    esxDomainCreate,                 /* domainCreate */
M
Matthias Bolte 已提交
3694
    esxDomainDefineXML,              /* domainDefineXML */
3695
    esxDomainUndefine,               /* domainUndefine */
3696
    NULL,                            /* domainAttachDevice */
3697
    NULL,                            /* domainAttachDeviceFlags */
3698
    NULL,                            /* domainDetachDevice */
3699
    NULL,                            /* domainDetachDeviceFlags */
3700
    NULL,                            /* domainUpdateDeviceFlags */
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
    NULL,                            /* domainGetAutostart */
    NULL,                            /* domainSetAutostart */
    esxDomainGetSchedulerType,       /* domainGetSchedulerType */
    esxDomainGetSchedulerParameters, /* domainGetSchedulerParameters */
    esxDomainSetSchedulerParameters, /* domainSetSchedulerParameters */
    esxDomainMigratePrepare,         /* domainMigratePrepare */
    esxDomainMigratePerform,         /* domainMigratePerform */
    esxDomainMigrateFinish,          /* domainMigrateFinish */
    NULL,                            /* domainBlockStats */
    NULL,                            /* domainInterfaceStats */
3711
    NULL,                            /* domainMemoryStats */
3712 3713
    NULL,                            /* domainBlockPeek */
    NULL,                            /* domainMemoryPeek */
3714
    NULL,                            /* domainGetBlockInfo */
3715
    NULL,                            /* nodeGetCellsFreeMemory */
M
Matthias Bolte 已提交
3716
    esxNodeGetFreeMemory,            /* nodeGetFreeMemory */
3717 3718 3719 3720 3721 3722 3723
    NULL,                            /* domainEventRegister */
    NULL,                            /* domainEventDeregister */
    NULL,                            /* domainMigratePrepare2 */
    NULL,                            /* domainMigrateFinish2 */
    NULL,                            /* nodeDeviceDettach */
    NULL,                            /* nodeDeviceReAttach */
    NULL,                            /* nodeDeviceReset */
C
Chris Lalancette 已提交
3724
    NULL,                            /* domainMigratePrepareTunnel */
3725 3726 3727 3728
    esxIsEncrypted,                  /* isEncrypted */
    esxIsSecure,                     /* isSecure */
    esxDomainIsActive,               /* domainIsActive */
    esxDomainIsPersistent,           /* domainIsPersistent */
J
Jiri Denemark 已提交
3729
    NULL,                            /* cpuCompare */
3730
    NULL,                            /* cpuBaseline */
3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747
    NULL,                            /* domainGetJobInfo */
    NULL,                            /* domainAbortJob */
    NULL,                            /* domainMigrateSetMaxDowntime */
    NULL,                            /* domainEventRegisterAny */
    NULL,                            /* domainEventDeregisterAny */
    NULL,                            /* domainManagedSave */
    NULL,                            /* domainHasManagedSaveImage */
    NULL,                            /* domainManagedSaveRemove */
    esxDomainSnapshotCreateXML,      /* domainSnapshotCreateXML */
    esxDomainSnapshotDumpXML,        /* domainSnapshotDumpXML */
    esxDomainSnapshotNum,            /* domainSnapshotNum */
    esxDomainSnapshotListNames,      /* domainSnapshotListNames */
    esxDomainSnapshotLookupByName,   /* domainSnapshotLookupByName */
    esxDomainHasCurrentSnapshot,     /* domainHasCurrentSnapshot */
    esxDomainSnapshotCurrent,        /* domainSnapshotCurrent */
    esxDomainRevertToSnapshot,       /* domainRevertToSnapshot */
    esxDomainSnapshotDelete,         /* domainSnapshotDelete */
3748 3749 3750 3751 3752 3753 3754
};



int
esxRegister(void)
{
3755 3756 3757 3758 3759
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
3760 3761
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
3762 3763
        return -1;
    }
3764 3765 3766

    return 0;
}