You need to sign in or sign up before continuing.
esx_driver.c 169.5 KB
Newer Older
1 2

/*
3
 * esx_driver.c: core driver functions for managing VMware ESX hosts
4
 *
5
 * Copyright (C) 2010-2012 Red Hat, Inc.
6
 * Copyright (C) 2009-2012 Matthias Bolte <matthias.bolte@googlemail.com>
7 8 9 10 11 12 13 14 15 16 17 18 19
 * 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
20
 * License along with this library.  If not, see
O
Osier Yang 已提交
21
 * <http://www.gnu.org/licenses/>.
22 23 24 25 26 27 28
 *
 */

#include <config.h>

#include "internal.h"
#include "domain_conf.h"
29
#include "snapshot_conf.h"
30
#include "virauth.h"
31 32 33 34
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
35
#include "vmx.h"
36
#include "virtypedparam.h"
37
#include "esx_driver.h"
38 39 40 41 42
#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 已提交
43
#include "esx_nwfilter_driver.h"
44
#include "esx_private.h"
45 46 47
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
M
Martin Kletzander 已提交
48
#include "viruri.h"
49 50 51 52 53

#define VIR_FROM_THIS VIR_FROM_ESX

static int esxDomainGetMaxVcpus(virDomainPtr domain);

54 55 56 57
typedef struct _esxVMX_Data esxVMX_Data;

struct _esxVMX_Data {
    esxVI_Context *ctx;
58
    char *datastorePathWithoutFileName;
59 60 61 62
};



63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
static void
esxFreePrivate(esxPrivate **priv)
{
    if (priv == NULL || *priv == NULL) {
        return;
    }

    esxVI_Context_Free(&(*priv)->host);
    esxVI_Context_Free(&(*priv)->vCenter);
    esxUtil_FreeParsedUri(&(*priv)->parsedUri);
    virCapabilitiesFree((*priv)->caps);
    VIR_FREE(*priv);
}



79
/*
80 81
 * Parse a file name from a .vmx file and convert it to datastore path format
 * if possbile. A .vmx file can contain file names in various formats:
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
 *
 * - A single name referencing a file in the same directory as the .vmx file:
 *
 *     test1.vmdk
 *
 * - An absolute file name referencing a file in a datastore that is mounted at
 *   /vmfs/volumes/<datastore>:
 *
 *     /vmfs/volumes/b24b7a78-9d82b4f5/test1/test1.vmdk
 *     /vmfs/volumes/datastore1/test1/test1.vmdk
 *
 *   The actual mount directory is /vmfs/volumes/b24b7a78-9d82b4f5, the second
 *   form is a symlink to it using the datastore name. This is the typical
 *   setup on an ESX(i) server.
 *
 * - With GSX installed on Windows there are also Windows style file names
 *   including UNC file names:
 *
 *     C:\Virtual Machines\test1\test1.vmdk
 *     \\nas1\storage1\test1\test1.vmdk
 *
103 104 105 106 107 108 109 110
 * - There might also be absolute file names referencing files outside of a
 *   datastore:
 *
 *     /usr/lib/vmware/isoimages/linux.iso
 *
 *   Such file names are left as is and are not converted to datastore path
 *   format because this is not possible.
 *
111 112 113 114 115 116 117
 * The datastore path format typically looks like this:
 *
 *  [datastore1] test1/test1.vmdk
 *
 * Firstly this functions checks if the given file name contains a separator.
 * If it doesn't then the referenced file is in the same directory as the .vmx
 * file. The datastore name and directory of the .vmx file are passed to this
118
 * function via the opaque parameter by the caller of virVMXParseConfig.
119 120 121 122 123 124 125 126 127
 *
 * Otherwise query for all known datastores and their mount directories. Then
 * try to find a datastore with a mount directory that is a prefix to the given
 * file name. This mechanism covers the Windows style file names too.
 *
 * The symlinks using the datastore name (/vmfs/volumes/datastore1) are an
 * exception and need special handling. Parse the datastore name and use it
 * to lookup the datastore by name to verify that it exists.
 */
128
static char *
129
esxParseVMXFileName(const char *fileName, void *opaque)
130
{
131
    char *result = NULL;
132
    esxVMX_Data *data = opaque;
133
    esxVI_String *propertyNameList = NULL;
134
    esxVI_ObjectContent *datastoreList = NULL;
135
    esxVI_ObjectContent *datastore = NULL;
136 137 138 139 140 141 142 143 144 145
    esxVI_DatastoreHostMount *hostMount = NULL;
    char *datastoreName;
    char *tmp;
    char *saveptr;
    char *strippedFileName = NULL;
    char *copyOfFileName = NULL;
    char *directoryAndFileName;

    if (strchr(fileName, '/') == NULL && strchr(fileName, '\\') == NULL) {
        /* Plain file name, use same directory as for the .vmx file */
146
        if (virAsprintf(&result, "%s/%s",
147
                        data->datastorePathWithoutFileName, fileName) < 0) {
148 149 150 151 152 153 154 155 156 157
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "summary.name") < 0 ||
            esxVI_LookupDatastoreList(data->ctx, propertyNameList,
                                      &datastoreList) < 0) {
            return NULL;
        }
158

159 160 161 162 163
        /* Search for datastore by mount path */
        for (datastore = datastoreList; datastore != NULL;
             datastore = datastore->_next) {
            esxVI_DatastoreHostMount_Free(&hostMount);
            datastoreName = NULL;
164

165 166 167 168 169 170
            if (esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                               &hostMount) < 0 ||
                esxVI_GetStringValue(datastore, "summary.name", &datastoreName,
                                     esxVI_Occurrence_RequiredItem) < 0) {
                goto cleanup;
            }
171

172
            tmp = (char *)STRSKIP(fileName, hostMount->mountInfo->path);
173

174 175 176
            if (tmp == NULL) {
                continue;
            }
177

178 179 180 181
            /* Found a match. Strip leading separators */
            while (*tmp == '/' || *tmp == '\\') {
                ++tmp;
            }
182

183 184 185
            if (esxVI_String_DeepCopyValue(&strippedFileName, tmp) < 0) {
                goto cleanup;
            }
186

187
            tmp = strippedFileName;
188

189 190 191 192 193
            /* Convert \ to / */
            while (*tmp != '\0') {
                if (*tmp == '\\') {
                    *tmp = '/';
                }
194

195 196
                ++tmp;
            }
197

198
            if (virAsprintf(&result, "[%s] %s", datastoreName,
199 200 201 202
                            strippedFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
203

204 205
            break;
        }
206

207
        /* Fallback to direct datastore name match */
208
        if (result == NULL && STRPREFIX(fileName, "/vmfs/volumes/")) {
209 210 211
            if (esxVI_String_DeepCopyValue(&copyOfFileName, fileName) < 0) {
                goto cleanup;
            }
212

213 214 215 216
            /* Expected format: '/vmfs/volumes/<datastore>/<path>' */
            if ((tmp = STRSKIP(copyOfFileName, "/vmfs/volumes/")) == NULL ||
                (datastoreName = strtok_r(tmp, "/", &saveptr)) == NULL ||
                (directoryAndFileName = strtok_r(NULL, "", &saveptr)) == NULL) {
217 218 219
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("File name '%s' doesn't have expected format "
                                 "'/vmfs/volumes/<datastore>/<path>'"), fileName);
220 221
                goto cleanup;
            }
222

223
            esxVI_ObjectContent_Free(&datastoreList);
224

225 226 227 228 229
            if (esxVI_LookupDatastoreByName(data->ctx, datastoreName,
                                            NULL, &datastoreList,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
230

231
            if (datastoreList == NULL) {
232 233 234
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("File name '%s' refers to non-existing datastore '%s'"),
                               fileName, datastoreName);
235 236
                goto cleanup;
            }
237

238
            if (virAsprintf(&result, "[%s] %s", datastoreName,
239 240 241 242
                            directoryAndFileName) < 0) {
                virReportOOMError();
                goto cleanup;
            }
243 244
        }

245 246 247 248 249 250 251 252 253
        /* If it's an absolute path outside of a datastore just use it as is */
        if (result == NULL && *fileName == '/') {
            /* FIXME: need to deal with Windows paths here too */
            if (esxVI_String_DeepCopyValue(&result, fileName) < 0) {
                goto cleanup;
            }
        }

        if (result == NULL) {
254 255
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not handle file name '%s'"), fileName);
256
            goto cleanup;
257
        }
258
    }
259

260 261 262 263 264 265
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
    esxVI_DatastoreHostMount_Free(&hostMount);
    VIR_FREE(strippedFileName);
    VIR_FREE(copyOfFileName);
266

267
    return result;
268 269 270 271
}



272
/*
E
Eric Blake 已提交
273
 * This function does the inverse of esxParseVMXFileName. It takes a file name
274 275
 * in datastore path format or in absolute format and converts it to a file
 * name that can be used in a .vmx file.
276 277 278 279 280 281
 *
 * The datastore path format and the formats found in a .vmx file are described
 * in the documentation of esxParseVMXFileName.
 *
 * Firstly parse the datastore path. Then use the datastore name to lookup the
 * datastore and it's mount path. Finally concatenate the mount path, directory
E
Eric Blake 已提交
282
 * and file name to an absolute path and return it. Detect the separator type
283 284
 * based on the mount path.
 */
285
static char *
286
esxFormatVMXFileName(const char *fileName, void *opaque)
287 288
{
    bool success = false;
289
    char *result = NULL;
290
    esxVMX_Data *data = opaque;
291
    char *datastoreName = NULL;
292
    char *directoryAndFileName = NULL;
293 294 295 296 297
    esxVI_ObjectContent *datastore = NULL;
    esxVI_DatastoreHostMount *hostMount = NULL;
    char separator = '/';
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *tmp;
298
    size_t length;
299

300 301 302 303 304 305
    if (*fileName == '[') {
        /* Parse datastore path and lookup datastore */
        if (esxUtil_ParseDatastorePath(fileName, &datastoreName, NULL,
                                       &directoryAndFileName) < 0) {
            goto cleanup;
        }
306

307 308 309 310 311 312
        if (esxVI_LookupDatastoreByName(data->ctx, datastoreName, NULL, &datastore,
                                        esxVI_Occurrence_RequiredItem) < 0 ||
            esxVI_LookupDatastoreHostMount(data->ctx, datastore->obj,
                                           &hostMount) < 0) {
            goto cleanup;
        }
313

314 315 316 317
        /* Detect separator type */
        if (strchr(hostMount->mountInfo->path, '\\') != NULL) {
            separator = '\\';
        }
318

319 320
        /* Strip trailing separators */
        length = strlen(hostMount->mountInfo->path);
321

322 323 324
        while (length > 0 && hostMount->mountInfo->path[length - 1] == separator) {
            --length;
        }
325

326 327
        /* Format as <mount>[/<directory>]/<file>, convert / to \ when necessary */
        virBufferAdd(&buffer, hostMount->mountInfo->path, length);
328

329 330
        if (separator != '/') {
            tmp = directoryAndFileName;
331

332 333 334 335
            while (*tmp != '\0') {
                if (*tmp == '/') {
                    *tmp = separator;
                }
336

337 338
                ++tmp;
            }
339
        }
340

341 342
        virBufferAddChar(&buffer, separator);
        virBufferAdd(&buffer, directoryAndFileName, -1);
343

344 345 346 347 348 349 350 351 352 353 354 355
        if (virBufferError(&buffer)) {
            virReportOOMError();
            goto cleanup;
        }

        result = virBufferContentAndReset(&buffer);
    } else if (*fileName == '/') {
        /* FIXME: need to deal with Windows paths here too */
        if (esxVI_String_DeepCopyValue(&result, fileName) < 0) {
            goto cleanup;
        }
    } else {
356 357
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not handle file name '%s'"), fileName);
358 359 360 361 362 363 364 365 366
        goto cleanup;
    }

    /* FIXME: Check if referenced path/file really exists */

    success = true;

  cleanup:
    if (! success) {
367
        virBufferFreeAndReset(&buffer);
368
        VIR_FREE(result);
369 370 371
    }

    VIR_FREE(datastoreName);
372
    VIR_FREE(directoryAndFileName);
373 374
    esxVI_ObjectContent_Free(&datastore);
    esxVI_DatastoreHostMount_Free(&hostMount);
375

376
    return result;
377 378 379 380 381 382 383 384 385 386
}



static int
esxAutodetectSCSIControllerModel(virDomainDiskDefPtr def, int *model,
                                 void *opaque)
{
    int result = -1;
    esxVMX_Data *data = opaque;
387
    esxVI_FileInfo *fileInfo = NULL;
388 389 390 391 392 393 394 395 396 397 398 399 400 401
    esxVI_VmDiskFileInfo *vmDiskFileInfo = NULL;

    if (def->device != VIR_DOMAIN_DISK_DEVICE_DISK ||
        def->bus != VIR_DOMAIN_DISK_BUS_SCSI ||
        def->type != VIR_DOMAIN_DISK_TYPE_FILE ||
        def->src == NULL ||
        ! STRPREFIX(def->src, "[")) {
        /*
         * This isn't a file-based SCSI disk device with a datastore related
         * source path => do nothing.
         */
        return 0;
    }

402 403
    if (esxVI_LookupFileInfoByDatastorePath(data->ctx, def->src,
                                            false, &fileInfo,
404
                                            esxVI_Occurrence_RequiredItem) < 0) {
405 406 407
        goto cleanup;
    }

408
    vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo);
409 410

    if (vmDiskFileInfo == NULL || vmDiskFileInfo->controllerType == NULL) {
411 412
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup controller model for '%s'"), def->src);
413 414 415 416 417
        goto cleanup;
    }

    if (STRCASEEQ(vmDiskFileInfo->controllerType,
                  "VirtualBusLogicController")) {
418
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_BUSLOGIC;
419 420
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicController")) {
421
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSILOGIC;
422 423
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "VirtualLsiLogicSASController")) {
424
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_LSISAS1068;
425 426
    } else if (STRCASEEQ(vmDiskFileInfo->controllerType,
                         "ParaVirtualSCSIController")) {
427
        *model = VIR_DOMAIN_CONTROLLER_MODEL_SCSI_VMPVSCSI;
428
    } else {
429 430 431
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Found unexpected controller model '%s' for disk '%s'"),
                       vmDiskFileInfo->controllerType, def->src);
432 433 434 435 436 437
        goto cleanup;
    }

    result = 0;

  cleanup:
438
    esxVI_FileInfo_Free(&fileInfo);
439 440 441 442

    return result;
}

443 444


445
static esxVI_Boolean
446
esxSupportsLongMode(esxPrivate *priv)
447 448 449 450 451 452
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfoList = NULL;
    esxVI_HostCpuIdInfo *hostCpuIdInfo = NULL;
453
    esxVI_ParsedHostCpuIdInfo parsedHostCpuIdInfo;
454 455 456 457 458 459
    char edxLongModeBit = '?';

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

460
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
461
        return esxVI_Boolean_Undefined;
462 463
    }

464
    if (esxVI_String_AppendValueToList(&propertyNameList,
465
                                       "hardware.cpuFeature") < 0 ||
466 467
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
468
        goto cleanup;
469 470 471 472 473 474
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuFeature")) {
            if (esxVI_HostCpuIdInfo_CastListFromAnyType
475
                  (dynamicProperty->val, &hostCpuIdInfoList) < 0) {
M
Matthias Bolte 已提交
476
                goto cleanup;
477 478 479 480 481
            }

            for (hostCpuIdInfo = hostCpuIdInfoList; hostCpuIdInfo != NULL;
                 hostCpuIdInfo = hostCpuIdInfo->_next) {
                if (hostCpuIdInfo->level->value == -2147483647) { /* 0x80000001 */
482 483
                    if (esxVI_ParseHostCpuIdInfo(&parsedHostCpuIdInfo,
                                                 hostCpuIdInfo) < 0) {
M
Matthias Bolte 已提交
484
                        goto cleanup;
485 486
                    }

487
                    edxLongModeBit = parsedHostCpuIdInfo.edx[29];
488 489 490 491 492 493

                    if (edxLongModeBit == '1') {
                        priv->supportsLongMode = esxVI_Boolean_True;
                    } else if (edxLongModeBit == '0') {
                        priv->supportsLongMode = esxVI_Boolean_False;
                    } else {
494 495 496 497 498
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("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 已提交
499
                        goto cleanup;
500 501 502 503 504 505 506 507 508 509 510 511 512
                    }

                    break;
                }
            }

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

  cleanup:
M
Matthias Bolte 已提交
513 514 515 516
    /*
     * 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.
     */
517 518 519 520 521 522 523 524 525
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostCpuIdInfo_Free(&hostCpuIdInfoList);

    return priv->supportsLongMode;
}



526 527 528 529 530 531
static int
esxLookupHostSystemBiosUuid(esxPrivate *priv, unsigned char *uuid)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
532
    char *uuid_string = NULL;
533

534
    if (esxVI_EnsureSession(priv->primary) < 0) {
535 536 537 538 539
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "hardware.systemInfo.uuid") < 0 ||
540
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
541 542 543
                                         &hostSystem) < 0 ||
        esxVI_GetStringValue(hostSystem, "hardware.systemInfo.uuid",
                             &uuid_string, esxVI_Occurrence_RequiredItem) < 0) {
544 545 546
        goto cleanup;
    }

547 548 549
    if (strlen(uuid_string) > 0) {
        if (virUUIDParse(uuid_string, uuid) < 0) {
            VIR_WARN("Could not parse host UUID from string '%s'", uuid_string);
550

551 552
            /* HostSystem has an invalid UUID, ignore it */
            memset(uuid, 0, VIR_UUID_BUFLEN);
553
        }
554 555 556
    } else {
        /* HostSystem has an empty UUID */
        memset(uuid, 0, VIR_UUID_BUFLEN);
557 558 559 560 561 562 563 564 565 566 567 568
    }

    result = 0;

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

    return result;
}


569 570 571 572 573
static int esxDefaultConsoleType(const char *ostype ATTRIBUTE_UNUSED)
{
    return VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL;
}

574

575
static virCapsPtr
576
esxCapsInit(esxPrivate *priv)
577
{
578
    esxVI_Boolean supportsLongMode = esxSupportsLongMode(priv);
579 580 581
    virCapsPtr caps = NULL;
    virCapsGuestPtr guest = NULL;

582 583 584 585 586 587 588 589 590
    if (supportsLongMode == esxVI_Boolean_Undefined) {
        return NULL;
    }

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

    if (caps == NULL) {
593
        virReportOOMError();
594 595 596
        return NULL;
    }

597
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x00, 0x0c, 0x29 });
598
    virCapabilitiesAddHostMigrateTransport(caps, "vpxmigr");
599

600
    caps->hasWideScsiBus = true;
601
    caps->defaultConsoleTargetType = esxDefaultConsoleType;
602

603 604 605 606
    if (esxLookupHostSystemBiosUuid(priv, caps->host.host_uuid) < 0) {
        goto failure;
    }

607 608 609
    /* i686 */
    guest = virCapabilitiesAddGuest(caps, "hvm", "i686", 32, NULL, NULL, 0,
                                    NULL);
610 611 612 613 614 615 616 617 618 619

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

    if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                      NULL) == NULL) {
        goto failure;
    }

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
    /* x86_64 */
    if (supportsLongMode == esxVI_Boolean_True) {
        guest = virCapabilitiesAddGuest(caps, "hvm", "x86_64", 64, NULL, NULL,
                                        0, NULL);

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

        if (virCapabilitiesAddGuestDomain(guest, "vmware", NULL, NULL, 0,
                                          NULL) == NULL) {
            goto failure;
        }
    }

635 636 637 638 639 640 641 642 643 644
    return caps;

  failure:
    virCapabilitiesFree(caps);

    return NULL;
}



645
static int
646 647
esxConnectToHost(virConnectPtr conn,
                 virConnectAuthPtr auth,
648 649 650 651 652
                 char **vCenterIpAddress)
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
653
    char *unescapedPassword = NULL;
654 655 656 657 658
    char *password = NULL;
    char *url = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_Boolean inMaintenanceMode = esxVI_Boolean_Undefined;
659 660 661 662
    esxPrivate *priv = conn->privateData;
    esxVI_ProductVersion expectedProductVersion = STRCASEEQ(conn->uri->scheme, "esx")
        ? esxVI_ProductVersion_ESX
        : esxVI_ProductVersion_GSX;
663 664

    if (vCenterIpAddress == NULL || *vCenterIpAddress != NULL) {
665
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
666 667 668
        return -1;
    }

669
    if (esxUtil_ResolveHostname(conn->uri->server, ipAddress, NI_MAXHOST) < 0) {
670 671 672
        return -1;
    }

673 674
    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);
675 676 677 678 679 680

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
681
        username = virAuthGetUsername(conn, auth, "esx", "root", conn->uri->server);
682 683

        if (username == NULL) {
684
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
685 686 687 688
            goto cleanup;
        }
    }

689
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, conn->uri->server);
690

M
Matthias Bolte 已提交
691
    if (unescapedPassword == NULL) {
692
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
693 694 695
        goto cleanup;
    }

M
Matthias Bolte 已提交
696 697 698 699 700 701
    password = esxUtil_EscapeForXml(unescapedPassword);

    if (password == NULL) {
        goto cleanup;
    }

702
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
703
                    conn->uri->server, conn->uri->port) < 0) {
704 705 706 707 708 709
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->host) < 0 ||
        esxVI_Context_Connect(priv->host, url, ipAddress, username, password,
710
                              priv->parsedUri) < 0 ||
711
        esxVI_Context_LookupManagedObjects(priv->host) < 0) {
712 713 714 715 716
        goto cleanup;
    }

    if (expectedProductVersion == esxVI_ProductVersion_ESX) {
        if (priv->host->productVersion != esxVI_ProductVersion_ESX35 &&
M
Matthias Bolte 已提交
717 718
            priv->host->productVersion != esxVI_ProductVersion_ESX40 &&
            priv->host->productVersion != esxVI_ProductVersion_ESX41 &&
P
Patrice LACHANCE 已提交
719 720
            priv->host->productVersion != esxVI_ProductVersion_ESX4x &&
            priv->host->productVersion != esxVI_ProductVersion_ESX50 &&
M
Martin Kletzander 已提交
721
            priv->host->productVersion != esxVI_ProductVersion_ESX51 &&
P
Patrice LACHANCE 已提交
722
            priv->host->productVersion != esxVI_ProductVersion_ESX5x) {
723 724 725
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s is neither an ESX 3.5, 4.x nor 5.x host"),
                           conn->uri->server);
726 727 728 729
            goto cleanup;
        }
    } else { /* GSX */
        if (priv->host->productVersion != esxVI_ProductVersion_GSX20) {
730 731
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("%s isn't a GSX 2.0 host"), conn->uri->server);
732 733 734 735 736 737 738 739
            goto cleanup;
        }
    }

    /* Query the host for maintenance mode and vCenter IP address */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "runtime.inMaintenanceMode\0"
                                           "summary.managementServerIp\0") < 0 ||
740 741
        esxVI_LookupHostSystemProperties(priv->host, propertyNameList,
                                         &hostSystem) < 0 ||
742 743 744 745 746 747 748 749 750 751 752
        esxVI_GetBoolean(hostSystem, "runtime.inMaintenanceMode",
                         &inMaintenanceMode,
                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetStringValue(hostSystem, "summary.managementServerIp",
                             vCenterIpAddress,
                             esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

    /* Warn if host is in maintenance mode */
    if (inMaintenanceMode == esxVI_Boolean_True) {
753
        VIR_WARN("The server is in maintenance mode");
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    }

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

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

    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
769 770
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
771 772 773 774 775 776 777 778 779 780
    VIR_FREE(url);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



static int
781 782 783
esxConnectToVCenter(virConnectPtr conn,
                    virConnectAuthPtr auth,
                    const char *hostname,
784
                    const char *hostSystemIpAddress)
785 786 787 788
{
    int result = -1;
    char ipAddress[NI_MAXHOST] = "";
    char *username = NULL;
M
Matthias Bolte 已提交
789
    char *unescapedPassword = NULL;
790 791
    char *password = NULL;
    char *url = NULL;
792
    esxPrivate *priv = conn->privateData;
793

794
    if (hostSystemIpAddress == NULL &&
795
        (priv->parsedUri->path == NULL || STREQ(priv->parsedUri->path, "/"))) {
796 797
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Path has to specify the datacenter and compute resource"));
798 799 800
        return -1;
    }

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

805 806
    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);
807 808 809 810 811 812

        if (username == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
813
        username = virAuthGetUsername(conn, auth, "esx", "administrator", hostname);
814 815

        if (username == NULL) {
816
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
817 818 819 820
            goto cleanup;
        }
    }

821
    unescapedPassword = virAuthGetPassword(conn, auth, "esx", username, hostname);
822

M
Matthias Bolte 已提交
823
    if (unescapedPassword == NULL) {
824
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
825 826 827
        goto cleanup;
    }

M
Matthias Bolte 已提交
828 829 830 831 832 833
    password = esxUtil_EscapeForXml(unescapedPassword);

    if (password == NULL) {
        goto cleanup;
    }

834
    if (virAsprintf(&url, "%s://%s:%d/sdk", priv->parsedUri->transport,
835
                    hostname, conn->uri->port) < 0) {
836 837 838 839 840 841
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_Context_Alloc(&priv->vCenter) < 0 ||
        esxVI_Context_Connect(priv->vCenter, url, ipAddress, username,
842
                              password, priv->parsedUri) < 0) {
843 844 845 846
        goto cleanup;
    }

    if (priv->vCenter->productVersion != esxVI_ProductVersion_VPX25 &&
M
Matthias Bolte 已提交
847 848
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX40 &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX41 &&
P
Patrice LACHANCE 已提交
849 850
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX4x &&
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX50 &&
M
Martin Kletzander 已提交
851
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX51 &&
P
Patrice LACHANCE 已提交
852
        priv->vCenter->productVersion != esxVI_ProductVersion_VPX5x) {
853 854 855
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("%s is neither a vCenter 2.5, 4.x nor 5.x server"),
                       hostname);
856 857 858
        goto cleanup;
    }

859
    if (hostSystemIpAddress != NULL) {
860 861
        if (esxVI_Context_LookupManagedObjectsByHostSystemIp
              (priv->vCenter, hostSystemIpAddress) < 0) {
862 863 864
            goto cleanup;
        }
    } else {
865 866
        if (esxVI_Context_LookupManagedObjectsByPath(priv->vCenter,
                                                     priv->parsedUri->path) < 0) {
867 868 869 870
            goto cleanup;
        }
    }

871 872 873 874
    result = 0;

  cleanup:
    VIR_FREE(username);
M
Matthias Bolte 已提交
875 876
    VIR_FREE(unescapedPassword);
    VIR_FREE(password);
877 878 879 880 881 882 883
    VIR_FREE(url);

    return result;
}



884
/*
885 886
 * URI format: {vpx|esx|gsx}://[<username>@]<hostname>[:<port>]/[<path>][?<query parameter>...]
 *             <path> = [<folder>/...]<datacenter>/[<folder>/...]<computeresource>[/<hostsystem>]
887
 *
888 889
 * If no port is specified the default port is set dependent on the scheme and
 * transport parameter:
890 891
 * - vpx+http  80
 * - vpx+https 443
892
 * - esx+http  80
893
 * - esx+https 443
894 895 896
 * - gsx+http  8222
 * - gsx+https 8333
 *
897 898 899
 * For a vpx:// connection <path> references a host managed by the vCenter.
 * In case the host is part of a cluster then <computeresource> is the cluster
 * name. Otherwise <computeresource> and <hostsystem> are equal and the later
900 901
 * can be omitted. As datacenters and computeresources can be organized in
 * folders those have to be included in <path>.
902
 *
903 904
 * Optional query parameters:
 * - transport={http|https}
905
 * - vcenter={<vcenter>|*}             only useful for an esx:// connection
906 907
 * - no_verify={0|1}
 * - auto_answer={0|1}
M
Matthias Bolte 已提交
908
 * - proxy=[{http|socks|socks4|socks4a|socks5}://]<hostname>[:<port>]
909
 *
910 911 912
 * If no transport parameter is specified https is used.
 *
 * The vcenter parameter is only necessary for migration, because the vCenter
913
 * server is in charge to initiate a migration between two ESX hosts. The
914
 * vcenter parameter can be set to an explicitly hostname or to *. If set to *,
915 916
 * 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.
917 918
 *
 * If the no_verify parameter is set to 1, this disables libcurl client checks
919
 * of the server's certificate. The default value it 0.
920 921 922 923
 *
 * If the auto_answer parameter is set to 1, the driver will respond to all
 * virtual machine questions with the default answer, otherwise virtual machine
 * questions will be reported as errors. The default value it 0.
M
Matthias Bolte 已提交
924 925 926 927
 *
 * The proxy parameter allows to specify a proxy for to be used by libcurl.
 * The default for the optional <type> part is http and socks is synonymous for
 * socks5. The optional <port> part allows to override the default port 1080.
928 929
 */
static virDrvOpenStatus
930
esxOpen(virConnectPtr conn, virConnectAuthPtr auth,
E
Eric Blake 已提交
931
        unsigned int flags)
932
{
M
Matthias Bolte 已提交
933
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
934
    char *plus;
935
    esxPrivate *priv = NULL;
936
    char *potentialVCenterIpAddress = NULL;
M
Matthias Bolte 已提交
937
    char vCenterIpAddress[NI_MAXHOST] = "";
938

E
Eric Blake 已提交
939 940
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

941 942
    /* Decline if the URI is NULL or the scheme is NULL */
    if (conn->uri == NULL || conn->uri->scheme == NULL) {
943 944 945
        return VIR_DRV_OPEN_DECLINED;
    }

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    /* Decline if the scheme is not one of {vpx|esx|gsx} */
    plus = strchr(conn->uri->scheme, '+');

    if (plus == NULL) {
        if (STRCASENEQ(conn->uri->scheme, "vpx") &&
            STRCASENEQ(conn->uri->scheme, "esx") &&
            STRCASENEQ(conn->uri->scheme, "gsx")) {
            return VIR_DRV_OPEN_DECLINED;
        }
    } else {
        if (plus - conn->uri->scheme != 3 ||
            (STRCASENEQLEN(conn->uri->scheme, "vpx", 3) &&
             STRCASENEQLEN(conn->uri->scheme, "esx", 3) &&
             STRCASENEQLEN(conn->uri->scheme, "gsx", 3))) {
            return VIR_DRV_OPEN_DECLINED;
        }

963 964 965
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Transport '%s' in URI scheme is not supported, try again "
                         "without the transport part"), plus + 1);
966 967 968
        return VIR_DRV_OPEN_ERROR;
    }

969 970 971 972 973 974
    if (STRCASENEQ(conn->uri->scheme, "vpx") &&
        conn->uri->path != NULL && STRNEQ(conn->uri->path, "/")) {
        VIR_WARN("Ignoring unexpected path '%s' for non-vpx scheme '%s'",
                 conn->uri->path, conn->uri->scheme);
    }

975 976
    /* Require server part */
    if (conn->uri->server == NULL) {
977 978
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("URI is missing the server part"));
979 980 981 982 983
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
    if (auth == NULL || auth->cb == NULL) {
984 985
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing or invalid auth pointer"));
986
        return VIR_DRV_OPEN_ERROR;
987 988 989 990
    }

    /* Allocate per-connection private data */
    if (VIR_ALLOC(priv) < 0) {
991
        virReportOOMError();
M
Matthias Bolte 已提交
992
        goto cleanup;
993 994
    }

995
    if (esxUtil_ParseUri(&priv->parsedUri, conn->uri) < 0) {
996 997 998
        goto cleanup;
    }

M
Matthias Bolte 已提交
999 1000
    priv->maxVcpus = -1;
    priv->supportsVMotion = esxVI_Boolean_Undefined;
1001
    priv->supportsLongMode = esxVI_Boolean_Undefined;
1002 1003
    priv->usedCpuTimeCounterId = -1;

1004 1005
    conn->privateData = priv;

M
Matthias Bolte 已提交
1006 1007 1008 1009 1010 1011 1012
    /*
     * 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) {
1013 1014
        if (STRCASEEQ(conn->uri->scheme, "vpx") ||
            STRCASEEQ(conn->uri->scheme, "esx")) {
1015
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
1016 1017 1018 1019 1020
                conn->uri->port = 443;
            } else {
                conn->uri->port = 80;
            }
        } else { /* GSX */
1021
            if (STRCASEEQ(priv->parsedUri->transport, "https")) {
M
Matthias Bolte 已提交
1022 1023 1024 1025
                conn->uri->port = 8333;
            } else {
                conn->uri->port = 8222;
            }
1026
        }
M
Matthias Bolte 已提交
1027
    }
1028

1029 1030 1031
    if (STRCASEEQ(conn->uri->scheme, "esx") ||
        STRCASEEQ(conn->uri->scheme, "gsx")) {
        /* Connect to host */
1032
        if (esxConnectToHost(conn, auth,
1033
                             &potentialVCenterIpAddress) < 0) {
M
Matthias Bolte 已提交
1034
            goto cleanup;
1035
        }
1036

1037
        /* Connect to vCenter */
1038 1039
        if (priv->parsedUri->vCenter != NULL) {
            if (STREQ(priv->parsedUri->vCenter, "*")) {
1040
                if (potentialVCenterIpAddress == NULL) {
1041 1042
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("This host is not managed by a vCenter"));
M
Matthias Bolte 已提交
1043
                    goto cleanup;
1044 1045
                }

1046 1047
                if (virStrcpyStatic(vCenterIpAddress,
                                    potentialVCenterIpAddress) == NULL) {
1048 1049 1050
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("vCenter IP address %s too big for destination"),
                                   potentialVCenterIpAddress);
1051 1052 1053
                    goto cleanup;
                }
            } else {
1054
                if (esxUtil_ResolveHostname(priv->parsedUri->vCenter,
1055 1056 1057
                                            vCenterIpAddress, NI_MAXHOST) < 0) {
                    goto cleanup;
                }
1058

1059 1060
                if (potentialVCenterIpAddress != NULL &&
                    STRNEQ(vCenterIpAddress, potentialVCenterIpAddress)) {
1061 1062 1063 1064 1065 1066
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("This host is managed by a vCenter with IP "
                                     "address %s, but a mismachting vCenter '%s' "
                                     "(%s) has been specified"),
                                   potentialVCenterIpAddress, priv->parsedUri->vCenter,
                                   vCenterIpAddress);
M
Matthias Bolte 已提交
1067
                    goto cleanup;
1068 1069
                }
            }
1070

1071 1072
            if (esxConnectToVCenter(conn, auth,
                                    vCenterIpAddress,
1073
                                    priv->host->ipAddress) < 0) {
1074 1075
                goto cleanup;
            }
1076 1077
        }

1078 1079 1080
        priv->primary = priv->host;
    } else { /* VPX */
        /* Connect to vCenter */
1081 1082 1083
        if (esxConnectToVCenter(conn, auth,
                                conn->uri->server,
                                NULL) < 0) {
M
Matthias Bolte 已提交
1084
            goto cleanup;
1085 1086
        }

1087
        priv->primary = priv->vCenter;
1088 1089
    }

M
Matthias Bolte 已提交
1090
    /* Setup capabilities */
1091
    priv->caps = esxCapsInit(priv);
1092

M
Matthias Bolte 已提交
1093
    if (priv->caps == NULL) {
M
Matthias Bolte 已提交
1094
        goto cleanup;
1095 1096
    }

M
Matthias Bolte 已提交
1097
    result = VIR_DRV_OPEN_SUCCESS;
1098

M
Matthias Bolte 已提交
1099
  cleanup:
1100 1101
    if (result == VIR_DRV_OPEN_ERROR) {
        esxFreePrivate(&priv);
1102 1103
    }

1104
    VIR_FREE(potentialVCenterIpAddress);
1105

M
Matthias Bolte 已提交
1106
    return result;
1107 1108 1109 1110 1111 1112 1113
}



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

1117 1118 1119 1120 1121 1122
    if (priv->host != NULL) {
        if (esxVI_EnsureSession(priv->host) < 0 ||
            esxVI_Logout(priv->host) < 0) {
            result = -1;
        }
    }
1123

M
Matthias Bolte 已提交
1124
    if (priv->vCenter != NULL) {
E
Eric Blake 已提交
1125 1126 1127 1128
        if (esxVI_EnsureSession(priv->vCenter) < 0 ||
            esxVI_Logout(priv->vCenter) < 0) {
            result = -1;
        }
1129 1130
    }

1131
    esxFreePrivate(&priv);
1132 1133 1134

    conn->privateData = NULL;

E
Eric Blake 已提交
1135
    return result;
1136 1137 1138 1139 1140
}



static esxVI_Boolean
1141
esxSupportsVMotion(esxPrivate *priv)
1142 1143 1144 1145
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

M
Matthias Bolte 已提交
1146 1147
    if (priv->supportsVMotion != esxVI_Boolean_Undefined) {
        return priv->supportsVMotion;
1148 1149
    }

1150
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1151
        return esxVI_Boolean_Undefined;
1152 1153
    }

1154
    if (esxVI_String_AppendValueToList(&propertyNameList,
1155
                                       "capability.vmotionSupported") < 0 ||
1156
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
1157 1158
                                         &hostSystem) < 0 ||
        esxVI_GetBoolean(hostSystem, "capability.vmotionSupported",
1159 1160 1161
                         &priv->supportsVMotion,
                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
1162 1163 1164
    }

  cleanup:
M
Matthias Bolte 已提交
1165 1166 1167 1168
    /*
     * 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.
     */
1169 1170 1171
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

M
Matthias Bolte 已提交
1172
    return priv->supportsVMotion;
1173 1174 1175 1176 1177 1178 1179
}



static int
esxSupportsFeature(virConnectPtr conn, int feature)
{
M
Matthias Bolte 已提交
1180
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1181
    esxVI_Boolean supportsVMotion = esxVI_Boolean_Undefined;
1182 1183 1184

    switch (feature) {
      case VIR_DRV_FEATURE_MIGRATION_V1:
1185
        supportsVMotion = esxSupportsVMotion(priv);
1186

M
Matthias Bolte 已提交
1187
        if (supportsVMotion == esxVI_Boolean_Undefined) {
1188 1189 1190
            return -1;
        }

M
Matthias Bolte 已提交
1191 1192 1193
        /* Migration is only possible via a vCenter and if VMotion is enabled */
        return priv->vCenter != NULL &&
               supportsVMotion == esxVI_Boolean_True ? 1 : 0;
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212

      default:
        return 0;
    }
}



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



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

1215
    if (virParseVersionString(priv->primary->service->about->version,
1216
                              version, false) < 0) {
1217 1218 1219
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse version number from '%s'"),
                       priv->primary->service->about->version);
1220

1221
        return -1;
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    }

    return 0;
}



static char *
esxGetHostname(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1232
    esxPrivate *priv = conn->privateData;
1233 1234 1235 1236 1237 1238 1239
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    const char *hostName = NULL;
    const char *domainName = NULL;
    char *complete = NULL;

1240
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1241
        return NULL;
1242 1243 1244
    }

    if (esxVI_String_AppendValueListToList
1245
          (&propertyNameList,
1246 1247
           "config.network.dnsConfig.hostName\0"
           "config.network.dnsConfig.domainName\0") < 0 ||
1248 1249
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1250
        goto cleanup;
1251 1252 1253 1254 1255 1256
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.network.dnsConfig.hostName")) {
1257
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1258
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1259
                goto cleanup;
1260 1261 1262 1263 1264
            }

            hostName = dynamicProperty->val->string;
        } else if (STREQ(dynamicProperty->name,
                         "config.network.dnsConfig.domainName")) {
1265
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1266
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1267
                goto cleanup;
1268 1269 1270 1271 1272 1273 1274 1275
            }

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

M
Matthias Bolte 已提交
1276
    if (hostName == NULL || strlen(hostName) < 1) {
1277 1278
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing or empty 'hostName' property"));
M
Matthias Bolte 已提交
1279
        goto cleanup;
1280 1281
    }

M
Matthias Bolte 已提交
1282
    if (domainName == NULL || strlen(domainName) < 1) {
1283
        complete = strdup(hostName);
1284

1285
        if (complete == NULL) {
1286
            virReportOOMError();
M
Matthias Bolte 已提交
1287
            goto cleanup;
1288 1289 1290
        }
    } else {
        if (virAsprintf(&complete, "%s.%s", hostName, domainName) < 0) {
1291
            virReportOOMError();
M
Matthias Bolte 已提交
1292
            goto cleanup;
1293
        }
1294 1295 1296
    }

  cleanup:
M
Matthias Bolte 已提交
1297 1298 1299 1300 1301
    /*
     * 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
     */
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return complete;
}



static int
esxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo)
{
M
Matthias Bolte 已提交
1313
    int result = -1;
M
Matthias Bolte 已提交
1314
    esxPrivate *priv = conn->privateData;
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    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;

1326
    memset(nodeinfo, 0, sizeof(*nodeinfo));
1327

1328
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1329
        return -1;
1330 1331
    }

1332
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1333 1334 1335 1336 1337 1338 1339
                                           "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 ||
1340 1341
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
1342
        goto cleanup;
1343 1344 1345 1346 1347
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "hardware.cpuInfo.hz")) {
1348
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1349
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1350
                goto cleanup;
1351 1352 1353 1354 1355
            }

            cpuInfo_hz = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuCores")) {
1356
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1357
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1358
                goto cleanup;
1359 1360 1361 1362 1363
            }

            cpuInfo_numCpuCores = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuPackages")) {
1364
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1365
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1366
                goto cleanup;
1367 1368 1369 1370 1371
            }

            cpuInfo_numCpuPackages = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.cpuInfo.numCpuThreads")) {
1372
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1373
                                         esxVI_Type_Short) < 0) {
M
Matthias Bolte 已提交
1374
                goto cleanup;
1375 1376 1377 1378
            }

            cpuInfo_numCpuThreads = dynamicProperty->val->int16;
        } else if (STREQ(dynamicProperty->name, "hardware.memorySize")) {
1379
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1380
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
1381
                goto cleanup;
1382 1383 1384 1385 1386
            }

            memorySize = dynamicProperty->val->int64;
        } else if (STREQ(dynamicProperty->name,
                         "hardware.numaInfo.numNodes")) {
1387
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1388
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
1389
                goto cleanup;
1390 1391 1392 1393 1394
            }

            numaInfo_numNodes = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "summary.hardware.cpuModel")) {
1395
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1396
                                         esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
1397
                goto cleanup;
1398 1399 1400 1401 1402 1403
            }

            ptr = dynamicProperty->val->string;

            /* Strip the string to fit more relevant information in 32 chars */
            while (*ptr != '\0') {
M
Matthias Bolte 已提交
1404 1405
                if (STRPREFIX(ptr, "  ")) {
                    memmove(ptr, ptr + 1, strlen(ptr + 1) + 1);
1406
                    continue;
1407
                } else if (STRPREFIX(ptr, "(R)") || STRPREFIX(ptr, "(C)")) {
M
Matthias Bolte 已提交
1408
                    memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);
1409
                    continue;
1410 1411 1412
                } else if (STRPREFIX(ptr, "(TM)")) {
                    memmove(ptr, ptr + 4, strlen(ptr + 4) + 1);
                    continue;
1413 1414 1415 1416 1417
                }

                ++ptr;
            }

C
Chris Lalancette 已提交
1418 1419 1420
            if (virStrncpy(nodeinfo->model, dynamicProperty->val->string,
                           sizeof(nodeinfo->model) - 1,
                           sizeof(nodeinfo->model)) == NULL) {
1421 1422 1423
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("CPU Model %s too long for destination"),
                               dynamicProperty->val->string);
M
Matthias Bolte 已提交
1424
                goto cleanup;
C
Chris Lalancette 已提交
1425
            }
1426 1427 1428 1429 1430 1431 1432
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    nodeinfo->memory = memorySize / 1024; /* Scale from bytes to kilobytes */
    nodeinfo->cpus = cpuInfo_numCpuCores;
1433
    nodeinfo->mhz = cpuInfo_hz / (1000 * 1000); /* Scale from hz to mhz */
1434 1435 1436 1437 1438 1439 1440 1441 1442
    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 已提交
1443 1444
    result = 0;

1445 1446 1447 1448 1449 1450 1451 1452 1453
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



1454 1455 1456
static char *
esxGetCapabilities(virConnectPtr conn)
{
M
Matthias Bolte 已提交
1457
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
1458
    char *xml = virCapabilitiesFormatXML(priv->caps);
1459 1460

    if (xml == NULL) {
1461
        virReportOOMError();
1462 1463 1464 1465 1466 1467 1468 1469
        return NULL;
    }

    return xml;
}



1470 1471 1472
static int
esxListDomains(virConnectPtr conn, int *ids, int maxids)
{
M
Matthias Bolte 已提交
1473
    bool success = false;
M
Matthias Bolte 已提交
1474
    esxPrivate *priv = conn->privateData;
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;

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

1485
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1486
        return -1;
1487 1488
    }

1489
    if (esxVI_String_AppendValueToList(&propertyNameList,
1490
                                       "runtime.powerState") < 0 ||
1491 1492
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1493
        goto cleanup;
1494 1495 1496 1497
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1498
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1499
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1500
            goto cleanup;
1501 1502 1503 1504 1505 1506 1507 1508 1509
        }

        if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

        if (esxUtil_ParseVirtualMachineIDString(virtualMachine->obj->value,
                                                &ids[count]) < 0 ||
            ids[count] <= 0) {
1510 1511 1512
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to parse positive integer from '%s'"),
                           virtualMachine->obj->value);
M
Matthias Bolte 已提交
1513
            goto cleanup;
1514 1515 1516 1517 1518 1519 1520 1521 1522
        }

        count++;

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

M
Matthias Bolte 已提交
1523 1524
    success = true;

1525 1526 1527 1528
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1529
    return success ? count : -1;
1530 1531 1532 1533 1534 1535 1536
}



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

1539
    if (esxVI_EnsureSession(priv->primary) < 0) {
1540 1541 1542
        return -1;
    }

1543
    return esxVI_LookupNumberOfDomainsByPowerState
1544
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, false);
1545 1546 1547 1548 1549 1550 1551
}



static virDomainPtr
esxDomainLookupByID(virConnectPtr conn, int id)
{
M
Matthias Bolte 已提交
1552
    esxPrivate *priv = conn->privateData;
1553 1554 1555 1556
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
M
Matthias Bolte 已提交
1557 1558 1559
    int id_candidate = -1;
    char *name_candidate = NULL;
    unsigned char uuid_candidate[VIR_UUID_BUFLEN];
1560 1561
    virDomainPtr domain = NULL;

1562
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1563
        return NULL;
1564 1565
    }

1566
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1567
                                           "configStatus\0"
1568 1569
                                           "name\0"
                                           "runtime.powerState\0"
1570
                                           "config.uuid\0") < 0 ||
1571 1572
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1573
        goto cleanup;
1574 1575 1576 1577
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
1578
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
1579
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
1580
            goto cleanup;
1581 1582 1583 1584 1585 1586 1587
        }

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

M
Matthias Bolte 已提交
1588
        VIR_FREE(name_candidate);
1589

1590
        if (esxVI_GetVirtualMachineIdentity(virtualMachine,
M
Matthias Bolte 已提交
1591 1592
                                            &id_candidate, &name_candidate,
                                            uuid_candidate) < 0) {
M
Matthias Bolte 已提交
1593
            goto cleanup;
1594 1595
        }

M
Matthias Bolte 已提交
1596
        if (id != id_candidate) {
1597 1598 1599
            continue;
        }

M
Matthias Bolte 已提交
1600
        domain = virGetDomain(conn, name_candidate, uuid_candidate);
1601 1602

        if (domain == NULL) {
M
Matthias Bolte 已提交
1603
            goto cleanup;
1604 1605 1606 1607 1608 1609 1610 1611
        }

        domain->id = id;

        break;
    }

    if (domain == NULL) {
1612
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
1613 1614 1615 1616 1617
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
M
Matthias Bolte 已提交
1618
    VIR_FREE(name_candidate);
1619 1620 1621 1622 1623 1624 1625 1626 1627

    return domain;
}



static virDomainPtr
esxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
M
Matthias Bolte 已提交
1628
    esxPrivate *priv = conn->privateData;
1629 1630 1631
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1632 1633
    int id = -1;
    char *name = NULL;
1634 1635
    virDomainPtr domain = NULL;

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

1640
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1641
                                           "name\0"
1642
                                           "runtime.powerState\0") < 0 ||
1643
        esxVI_LookupVirtualMachineByUuid(priv->primary, uuid, propertyNameList,
1644
                                         &virtualMachine,
M
Matthias Bolte 已提交
1645
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1646 1647
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, &name, NULL) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1648
        goto cleanup;
1649 1650
    }

1651
    domain = virGetDomain(conn, name, uuid);
1652 1653

    if (domain == NULL) {
M
Matthias Bolte 已提交
1654
        goto cleanup;
1655
    }
1656

1657 1658 1659 1660 1661
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1662 1663 1664 1665
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1666 1667
    esxVI_ObjectContent_Free(&virtualMachine);
    VIR_FREE(name);
1668 1669 1670 1671 1672 1673 1674 1675 1676

    return domain;
}



static virDomainPtr
esxDomainLookupByName(virConnectPtr conn, const char *name)
{
M
Matthias Bolte 已提交
1677
    esxPrivate *priv = conn->privateData;
1678 1679 1680
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
1681 1682
    int id = -1;
    unsigned char uuid[VIR_UUID_BUFLEN];
1683 1684
    virDomainPtr domain = NULL;

1685
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1686
        return NULL;
1687 1688
    }

1689
    if (esxVI_String_AppendValueListToList(&propertyNameList,
1690
                                           "configStatus\0"
1691
                                           "runtime.powerState\0"
1692
                                           "config.uuid\0") < 0 ||
1693
        esxVI_LookupVirtualMachineByName(priv->primary, name, propertyNameList,
1694 1695
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
1696
        goto cleanup;
1697 1698
    }

1699
    if (virtualMachine == NULL) {
1700
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with name '%s'"), name);
M
Matthias Bolte 已提交
1701
        goto cleanup;
1702
    }
1703

M
Matthias Bolte 已提交
1704 1705 1706
    if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, uuid) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
1707
    }
1708

1709
    domain = virGetDomain(conn, name, uuid);
1710

1711
    if (domain == NULL) {
M
Matthias Bolte 已提交
1712
        goto cleanup;
1713 1714
    }

1715 1716 1717 1718 1719
    /* Only running/suspended virtual machines have an ID != -1 */
    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
        domain->id = id;
    } else {
        domain->id = -1;
1720 1721 1722 1723
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
1724
    esxVI_ObjectContent_Free(&virtualMachine);
1725 1726 1727 1728 1729 1730 1731 1732 1733

    return domain;
}



static int
esxDomainSuspend(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1734
    int result = -1;
M
Matthias Bolte 已提交
1735
    esxPrivate *priv = domain->conn->privateData;
1736 1737 1738 1739 1740
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1741
    char *taskInfoErrorMessage = NULL;
1742

1743
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1744
        return -1;
1745 1746
    }

1747
    if (esxVI_String_AppendValueToList(&propertyNameList,
1748
                                       "runtime.powerState") < 0 ||
1749
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1750
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1751
           priv->parsedUri->autoAnswer) < 0 ||
1752
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1753
        goto cleanup;
1754 1755 1756
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1757 1758
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1759
        goto cleanup;
1760 1761
    }

1762 1763
    if (esxVI_SuspendVM_Task(priv->primary, virtualMachine->obj, &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1764
                                    esxVI_Occurrence_RequiredItem,
1765
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1766
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1767
        goto cleanup;
1768 1769 1770
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1771 1772
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not suspend domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1773
        goto cleanup;
1774 1775
    }

M
Matthias Bolte 已提交
1776 1777
    result = 0;

1778 1779 1780 1781
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1782
    VIR_FREE(taskInfoErrorMessage);
1783 1784 1785 1786 1787 1788 1789 1790 1791

    return result;
}



static int
esxDomainResume(virDomainPtr domain)
{
M
Matthias Bolte 已提交
1792
    int result = -1;
M
Matthias Bolte 已提交
1793
    esxPrivate *priv = domain->conn->privateData;
1794 1795 1796 1797 1798
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1799
    char *taskInfoErrorMessage = NULL;
1800

1801
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1802
        return -1;
1803 1804
    }

1805
    if (esxVI_String_AppendValueToList(&propertyNameList,
1806
                                       "runtime.powerState") < 0 ||
1807
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1808
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
1809
           priv->parsedUri->autoAnswer) < 0 ||
1810
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1811
        goto cleanup;
1812 1813 1814
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended) {
1815
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not suspended"));
M
Matthias Bolte 已提交
1816
        goto cleanup;
1817 1818
    }

1819
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
1820
                             &task) < 0 ||
1821
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
1822
                                    esxVI_Occurrence_RequiredItem,
1823
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1824
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1825
        goto cleanup;
1826 1827 1828
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1829 1830
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not resume domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1831
        goto cleanup;
1832 1833
    }

M
Matthias Bolte 已提交
1834 1835
    result = 0;

1836 1837 1838 1839
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
1840
    VIR_FREE(taskInfoErrorMessage);
1841 1842 1843 1844 1845 1846 1847

    return result;
}



static int
1848
esxDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1849
{
M
Matthias Bolte 已提交
1850
    int result = -1;
M
Matthias Bolte 已提交
1851
    esxPrivate *priv = domain->conn->privateData;
1852 1853 1854 1855
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

1856 1857
    virCheckFlags(0, -1);

1858
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1859
        return -1;
1860 1861
    }

1862
    if (esxVI_String_AppendValueToList(&propertyNameList,
1863
                                       "runtime.powerState") < 0 ||
1864
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1865
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1866
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1867
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1868
        goto cleanup;
1869 1870 1871
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1872 1873
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1874
        goto cleanup;
1875 1876
    }

1877
    if (esxVI_ShutdownGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1878
        goto cleanup;
1879 1880
    }

M
Matthias Bolte 已提交
1881 1882
    result = 0;

1883 1884 1885 1886 1887 1888 1889 1890
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


1891 1892 1893 1894 1895 1896
static int
esxDomainShutdown(virDomainPtr domain)
{
    return esxDomainShutdownFlags(domain, 0);
}

1897 1898

static int
E
Eric Blake 已提交
1899
esxDomainReboot(virDomainPtr domain, unsigned int flags)
1900
{
M
Matthias Bolte 已提交
1901
    int result = -1;
M
Matthias Bolte 已提交
1902
    esxPrivate *priv = domain->conn->privateData;
1903 1904 1905 1906
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

E
Eric Blake 已提交
1907 1908
    virCheckFlags(0, -1);

1909
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
1910
        return -1;
1911 1912
    }

1913
    if (esxVI_String_AppendValueToList(&propertyNameList,
1914
                                       "runtime.powerState") < 0 ||
1915
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
1916
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
1917
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1918
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1919
        goto cleanup;
1920 1921 1922
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1923 1924
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1925
        goto cleanup;
1926 1927
    }

1928
    if (esxVI_RebootGuest(priv->primary, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
1929
        goto cleanup;
1930 1931
    }

M
Matthias Bolte 已提交
1932 1933
    result = 0;

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}



static int
1944 1945
esxDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
1946
{
M
Matthias Bolte 已提交
1947
    int result = -1;
M
Matthias Bolte 已提交
1948
    esxPrivate *priv = domain->conn->privateData;
1949
    esxVI_Context *ctx = NULL;
1950 1951 1952 1953 1954
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
1955
    char *taskInfoErrorMessage = NULL;
1956

1957 1958
    virCheckFlags(0, -1);

1959 1960 1961 1962 1963 1964
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

1965
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
1966
        return -1;
1967 1968
    }

1969
    if (esxVI_String_AppendValueToList(&propertyNameList,
1970
                                       "runtime.powerState") < 0 ||
1971
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1972
          (ctx, domain->uuid, propertyNameList, &virtualMachine,
1973
           priv->parsedUri->autoAnswer) < 0 ||
1974
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
1975
        goto cleanup;
1976 1977 1978
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOn) {
1979 1980
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered on"));
M
Matthias Bolte 已提交
1981
        goto cleanup;
1982 1983
    }

1984
    if (esxVI_PowerOffVM_Task(ctx, virtualMachine->obj, &task) < 0 ||
1985 1986
        esxVI_WaitForTaskCompletion(ctx, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
1987
                                    priv->parsedUri->autoAnswer, &taskInfoState,
1988
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
1989
        goto cleanup;
1990 1991 1992
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
1993 1994
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not destroy domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
1995
        goto cleanup;
1996 1997
    }

1998
    domain->id = -1;
M
Matthias Bolte 已提交
1999 2000
    result = 0;

2001 2002 2003 2004
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
2005
    VIR_FREE(taskInfoErrorMessage);
2006 2007 2008 2009 2010

    return result;
}


2011 2012 2013 2014 2015 2016
static int
esxDomainDestroy(virDomainPtr dom)
{
    return esxDomainDestroyFlags(dom, 0);
}

2017 2018

static char *
2019
esxDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
2020
{
2021 2022 2023
    char *osType = strdup("hvm");

    if (osType == NULL) {
2024
        virReportOOMError();
2025 2026 2027 2028
        return NULL;
    }

    return osType;
2029 2030 2031 2032
}



2033
static unsigned long long
2034 2035
esxDomainGetMaxMemory(virDomainPtr domain)
{
M
Matthias Bolte 已提交
2036
    esxPrivate *priv = domain->conn->privateData;
2037 2038 2039 2040 2041
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    unsigned long memoryMB = 0;

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

2046
    if (esxVI_String_AppendValueToList(&propertyNameList,
2047
                                       "config.hardware.memoryMB") < 0 ||
2048
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2049
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2050
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2051
        goto cleanup;
2052 2053 2054 2055 2056
    }

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

            if (dynamicProperty->val->int32 < 0) {
2063 2064 2065
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Got invalid memory size %d"),
                               dynamicProperty->val->int32);
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
            } 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 已提交
2088
    int result = -1;
M
Matthias Bolte 已提交
2089
    esxPrivate *priv = domain->conn->privateData;
2090
    esxVI_String *propertyNameList = NULL;
2091
    esxVI_ObjectContent *virtualMachine = NULL;
2092
    esxVI_VirtualMachinePowerState powerState;
2093 2094 2095
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2096
    char *taskInfoErrorMessage = NULL;
2097

2098
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2099
        return -1;
2100 2101
    }

2102 2103 2104 2105
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
2106
           priv->parsedUri->autoAnswer) < 0 ||
2107 2108 2109 2110 2111
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
2112 2113
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
2114 2115 2116 2117
        goto cleanup;
    }

    if (esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
2118
        esxVI_Long_Alloc(&spec->memoryMB) < 0) {
M
Matthias Bolte 已提交
2119
        goto cleanup;
2120 2121
    }

2122
    /* max-memory must be a multiple of 4096 kilobyte */
2123
    spec->memoryMB->value =
2124
      VIR_DIV_UP(memory, 4096) * 4; /* Scale from kilobytes to megabytes */
2125

2126
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2127
                              &task) < 0 ||
2128
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2129
                                    esxVI_Occurrence_RequiredItem,
2130
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2131
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2132
        goto cleanup;
2133 2134 2135
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2136 2137 2138
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set max-memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2139
        goto cleanup;
2140 2141
    }

M
Matthias Bolte 已提交
2142 2143
    result = 0;

2144
  cleanup:
2145
    esxVI_String_Free(&propertyNameList);
2146 2147 2148
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2149
    VIR_FREE(taskInfoErrorMessage);
2150 2151 2152 2153 2154 2155 2156 2157 2158

    return result;
}



static int
esxDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
M
Matthias Bolte 已提交
2159
    int result = -1;
M
Matthias Bolte 已提交
2160
    esxPrivate *priv = domain->conn->privateData;
2161 2162 2163 2164
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2165
    char *taskInfoErrorMessage = NULL;
2166

2167
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2168
        return -1;
2169 2170
    }

2171
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2172
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2173
           priv->parsedUri->autoAnswer) < 0 ||
2174 2175 2176
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0 ||
        esxVI_Long_Alloc(&spec->memoryAllocation->limit) < 0) {
M
Matthias Bolte 已提交
2177
        goto cleanup;
2178 2179 2180
    }

    spec->memoryAllocation->limit->value =
2181
      VIR_DIV_UP(memory, 1024); /* Scale from kilobytes to megabytes */
2182

2183
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2184
                              &task) < 0 ||
2185
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2186
                                    esxVI_Occurrence_RequiredItem,
2187
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2188
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2189
        goto cleanup;
2190 2191 2192
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2193 2194 2195
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set memory to %lu kilobytes: %s"), memory,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2196
        goto cleanup;
2197 2198
    }

M
Matthias Bolte 已提交
2199 2200
    result = 0;

2201 2202 2203 2204
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2205
    VIR_FREE(taskInfoErrorMessage);
2206 2207 2208 2209 2210 2211

    return result;
}



2212 2213 2214 2215 2216 2217 2218 2219 2220
/*
 * libvirt exposed virtual CPU usage in absolute time, ESX doesn't provide this
 * information in this format. It exposes it in 20 seconds slots, but it's hard
 * to get a reliable absolute time from this. Therefore, disable the code that
 * queries the performance counters here for now, but keep it as example for how
 * to query a selected performance counter for its values.
 */
#define ESX_QUERY_FOR_USED_CPU_TIME 0

2221 2222 2223
static int
esxDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
M
Matthias Bolte 已提交
2224
    int result = -1;
M
Matthias Bolte 已提交
2225
    esxPrivate *priv = domain->conn->privateData;
2226 2227 2228 2229 2230
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int64_t memory_limit = -1;
2231
#if ESX_QUERY_FOR_USED_CPU_TIME
2232 2233 2234 2235 2236 2237 2238
    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;
2239 2240
    esxVI_PerfEntityMetricBase *perfEntityMetricBase = NULL;
    esxVI_PerfEntityMetricBase *perfEntityMetricBaseList = NULL;
2241 2242 2243
    esxVI_PerfEntityMetric *perfEntityMetric = NULL;
    esxVI_PerfMetricIntSeries *perfMetricIntSeries = NULL;
    esxVI_Long *value = NULL;
2244
#endif
2245

2246
    memset(info, 0, sizeof(*info));
M
Matthias Bolte 已提交
2247

2248
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2249
        return -1;
2250 2251
    }

2252
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2253 2254 2255 2256
                                           "runtime.powerState\0"
                                           "config.hardware.memoryMB\0"
                                           "config.hardware.numCPU\0"
                                           "config.memoryAllocation.limit\0") < 0 ||
2257
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2258
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
2259
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2260
        goto cleanup;
2261 2262 2263 2264 2265 2266 2267 2268
    }

    info->state = VIR_DOMAIN_NOSTATE;

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

2273 2274
            info->state = esxVI_VirtualMachinePowerState_ConvertToLibvirt
                            (powerState);
2275
        } else if (STREQ(dynamicProperty->name, "config.hardware.memoryMB")) {
2276
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2277
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2278
                goto cleanup;
2279 2280 2281 2282
            }

            info->maxMem = dynamicProperty->val->int32 * 1024; /* Scale from megabyte to kilobyte */
        } else if (STREQ(dynamicProperty->name, "config.hardware.numCPU")) {
2283
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2284
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2285
                goto cleanup;
2286 2287 2288 2289 2290
            }

            info->nrVirtCpu = dynamicProperty->val->int32;
        } else if (STREQ(dynamicProperty->name,
                         "config.memoryAllocation.limit")) {
2291
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2292
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
2293
                goto cleanup;
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
            }

            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;

2309
#if ESX_QUERY_FOR_USED_CPU_TIME
2310
    /* Verify the cached 'used CPU time' performance counter ID */
2311 2312 2313 2314 2315 2316
    /* FIXME: Currently no host for a vpx:// connection */
    if (priv->host != NULL) {
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId >= 0) {
            if (esxVI_Int_Alloc(&counterId) < 0) {
                goto cleanup;
            }
2317

2318
            counterId->value = priv->usedCpuTimeCounterId;
2319

2320 2321 2322
            if (esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                goto cleanup;
            }
2323

2324 2325 2326 2327
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfo) < 0) {
                goto cleanup;
            }
2328

2329 2330 2331 2332 2333
            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);
2334

2335 2336 2337 2338 2339
                priv->usedCpuTimeCounterId = -1;
            }

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

2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
        /*
         * Query the PerformanceManager for the 'used CPU time' performance
         * counter ID and cache it, if it's not already cached.
         */
        if (info->state == VIR_DOMAIN_RUNNING && priv->usedCpuTimeCounterId < 0) {
            if (esxVI_QueryAvailablePerfMetric(priv->host, virtualMachine->obj,
                                               NULL, NULL, NULL,
                                               &perfMetricIdList) < 0) {
                goto cleanup;
            }
2352

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

2358
                counterId = NULL;
2359

2360 2361 2362 2363 2364
                if (esxVI_Int_DeepCopy(&counterId, perfMetricId->counterId) < 0 ||
                    esxVI_Int_AppendToList(&counterIdList, counterId) < 0) {
                    goto cleanup;
                }
            }
2365

2366 2367
            if (esxVI_QueryPerfCounter(priv->host, counterIdList,
                                       &perfCounterInfoList) < 0) {
M
Matthias Bolte 已提交
2368
                goto cleanup;
2369 2370
            }

2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
            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;
                }
2388 2389
            }

2390
            if (priv->usedCpuTimeCounterId < 0) {
2391
                VIR_WARN("Could not find 'used CPU time' performance counter");
2392
            }
2393 2394
        }

2395 2396 2397 2398 2399 2400
        /*
         * 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);
2401

2402 2403 2404 2405 2406 2407
            if (esxVI_PerfQuerySpec_Alloc(&querySpec) < 0 ||
                esxVI_Int_Alloc(&querySpec->maxSample) < 0 ||
                esxVI_PerfMetricId_Alloc(&querySpec->metricId) < 0 ||
                esxVI_Int_Alloc(&querySpec->metricId->counterId) < 0) {
                goto cleanup;
            }
2408

2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
            querySpec->entity = virtualMachine->obj;
            querySpec->maxSample->value = 1;
            querySpec->metricId->counterId->value = priv->usedCpuTimeCounterId;
            querySpec->metricId->instance = (char *)"";
            querySpec->format = (char *)"normal";

            if (esxVI_QueryPerf(priv->host, querySpec,
                                &perfEntityMetricBaseList) < 0) {
                goto cleanup;
            }
2419

2420 2421 2422
            for (perfEntityMetricBase = perfEntityMetricBaseList;
                 perfEntityMetricBase != NULL;
                 perfEntityMetricBase = perfEntityMetricBase->_next) {
2423
                VIR_DEBUG("perfEntityMetric ...");
2424

2425 2426
                perfEntityMetric =
                  esxVI_PerfEntityMetric_DynamicCast(perfEntityMetricBase);
2427

2428
                if (perfEntityMetric == NULL) {
2429 2430 2431
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetricBase->_type));
2432
                    goto cleanup;
2433
                }
2434

2435 2436
                perfMetricIntSeries =
                  esxVI_PerfMetricIntSeries_DynamicCast(perfEntityMetric->value);
2437

2438
                if (perfMetricIntSeries == NULL) {
2439 2440 2441
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("QueryPerf returned object with unexpected type '%s'"),
                                   esxVI_Type_ToString(perfEntityMetric->value->_type));
2442
                    goto cleanup;
2443
                }
2444

2445 2446
                for (; perfMetricIntSeries != NULL;
                     perfMetricIntSeries = perfMetricIntSeries->_next) {
2447
                    VIR_DEBUG("perfMetricIntSeries ...");
2448

2449 2450 2451 2452 2453
                    for (value = perfMetricIntSeries->value;
                         value != NULL;
                         value = value->_next) {
                        VIR_DEBUG("value %lld", (long long int)value->value);
                    }
2454 2455 2456
                }
            }

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

2459
            /*
E
Eric Blake 已提交
2460
             * FIXME: Cannot map between relative used-cpu-time and absolute
2461 2462 2463
             *        info->cpuTime
             */
        }
2464
    }
2465
#endif
2466

M
Matthias Bolte 已提交
2467 2468
    result = 0;

2469
  cleanup:
2470
#if ESX_QUERY_FOR_USED_CPU_TIME
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
    /*
     * Remove values owned by data structures to prevent them from being freed
     * by the call to esxVI_PerfQuerySpec_Free().
     */
    if (querySpec != NULL) {
        querySpec->entity = NULL;
        querySpec->format = NULL;

        if (querySpec->metricId != NULL) {
            querySpec->metricId->instance = NULL;
        }
    }
2483
#endif
2484

2485 2486
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2487
#if ESX_QUERY_FOR_USED_CPU_TIME
2488 2489 2490 2491
    esxVI_PerfMetricId_Free(&perfMetricIdList);
    esxVI_Int_Free(&counterIdList);
    esxVI_PerfCounterInfo_Free(&perfCounterInfoList);
    esxVI_PerfQuerySpec_Free(&querySpec);
2492
    esxVI_PerfEntityMetricBase_Free(&perfEntityMetricBaseList);
2493
#endif
2494 2495 2496 2497 2498 2499

    return result;
}



2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542
static int
esxDomainGetState(virDomainPtr domain,
                  int *state,
                  int *reason,
                  unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;

    virCheckFlags(0, -1);

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "runtime.powerState") < 0 ||
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
        goto cleanup;
    }

    *state = esxVI_VirtualMachinePowerState_ConvertToLibvirt(powerState);

    if (reason)
        *reason = 0;

    result = 0;

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

    return result;
}



2543
static int
2544 2545
esxDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
2546
{
M
Matthias Bolte 已提交
2547
    int result = -1;
M
Matthias Bolte 已提交
2548
    esxPrivate *priv = domain->conn->privateData;
M
Matthias Bolte 已提交
2549
    int maxVcpus;
2550 2551 2552 2553
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
2554
    char *taskInfoErrorMessage = NULL;
2555

2556
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2557
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2558 2559 2560
        return -1;
    }

2561
    if (nvcpus < 1) {
2562 2563
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Requested number of virtual CPUs must at least be 1"));
M
Matthias Bolte 已提交
2564
        return -1;
2565 2566
    }

2567
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2568
        return -1;
2569 2570
    }

M
Matthias Bolte 已提交
2571
    maxVcpus = esxDomainGetMaxVcpus(domain);
2572

M
Matthias Bolte 已提交
2573
    if (maxVcpus < 0) {
M
Matthias Bolte 已提交
2574
        return -1;
2575 2576
    }

M
Matthias Bolte 已提交
2577
    if (nvcpus > maxVcpus) {
2578 2579 2580 2581
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Requested number of virtual CPUs is greater than max "
                         "allowable number of virtual CPUs for the domain: %d > %d"),
                       nvcpus, maxVcpus);
M
Matthias Bolte 已提交
2582
        return -1;
2583 2584
    }

2585
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2586
          (priv->primary, domain->uuid, NULL, &virtualMachine,
2587
           priv->parsedUri->autoAnswer) < 0 ||
2588 2589
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_Int_Alloc(&spec->numCPUs) < 0) {
M
Matthias Bolte 已提交
2590
        goto cleanup;
2591 2592 2593 2594
    }

    spec->numCPUs->value = nvcpus;

2595
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
2596
                              &task) < 0 ||
2597
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
2598
                                    esxVI_Occurrence_RequiredItem,
2599
                                    priv->parsedUri->autoAnswer, &taskInfoState,
2600
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
2601
        goto cleanup;
2602 2603 2604
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
2605 2606 2607
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not set number of virtual CPUs to %d: %s"), nvcpus,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
2608
        goto cleanup;
2609 2610
    }

M
Matthias Bolte 已提交
2611 2612
    result = 0;

2613 2614 2615 2616
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
2617
    VIR_FREE(taskInfoErrorMessage);
2618 2619 2620 2621 2622

    return result;
}


M
Matthias Bolte 已提交
2623

2624 2625 2626
static int
esxDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
2627
    return esxDomainSetVcpusFlags(domain, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2628 2629
}

2630

M
Matthias Bolte 已提交
2631

2632
static int
2633
esxDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
2634
{
M
Matthias Bolte 已提交
2635
    esxPrivate *priv = domain->conn->privateData;
2636 2637 2638 2639
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

2640
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2641
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2642 2643 2644
        return -1;
    }

M
Matthias Bolte 已提交
2645 2646
    if (priv->maxVcpus > 0) {
        return priv->maxVcpus;
2647 2648
    }

M
Matthias Bolte 已提交
2649 2650
    priv->maxVcpus = -1;

2651
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2652
        return -1;
2653 2654
    }

2655
    if (esxVI_String_AppendValueToList(&propertyNameList,
2656
                                       "capability.maxSupportedVcpus") < 0 ||
2657 2658
        esxVI_LookupHostSystemProperties(priv->primary, propertyNameList,
                                         &hostSystem) < 0) {
M
Matthias Bolte 已提交
2659
        goto cleanup;
2660 2661 2662 2663 2664
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "capability.maxSupportedVcpus")) {
2665
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2666
                                         esxVI_Type_Int) < 0) {
M
Matthias Bolte 已提交
2667
                goto cleanup;
2668 2669
            }

M
Matthias Bolte 已提交
2670
            priv->maxVcpus = dynamicProperty->val->int32;
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

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

M
Matthias Bolte 已提交
2681
    return priv->maxVcpus;
2682 2683
}

M
Matthias Bolte 已提交
2684 2685


2686 2687 2688
static int
esxDomainGetMaxVcpus(virDomainPtr domain)
{
2689
    return esxDomainGetVcpusFlags(domain, (VIR_DOMAIN_AFFECT_LIVE |
2690 2691
                                           VIR_DOMAIN_VCPU_MAXIMUM));
}
2692

M
Matthias Bolte 已提交
2693 2694


2695
static char *
2696
esxDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2697
{
M
Matthias Bolte 已提交
2698
    esxPrivate *priv = domain->conn->privateData;
2699 2700
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
2701 2702
    esxVI_VirtualMachinePowerState powerState;
    int id;
2703
    char *vmPathName = NULL;
2704
    char *datastoreName = NULL;
M
Matthias Bolte 已提交
2705
    char *directoryName = NULL;
2706
    char *directoryAndFileName = NULL;
2707
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2708 2709
    char *url = NULL;
    char *vmx = NULL;
2710
    virVMXContext ctx;
2711
    esxVMX_Data data;
2712 2713 2714
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2715 2716
    /* Flags checked by virDomainDefFormat */

2717
    memset(&data, 0, sizeof(data));
2718

2719
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2720
        return NULL;
2721 2722
    }

2723 2724 2725
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "config.files.vmPathName\0"
                                           "runtime.powerState\0") < 0 ||
2726
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
2727
                                         propertyNameList, &virtualMachine,
2728
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2729 2730
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0 ||
2731 2732
        esxVI_GetStringValue(virtualMachine, "config.files.vmPathName",
                             &vmPathName, esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2733
        goto cleanup;
2734 2735
    }

2736
    if (esxUtil_ParseDatastorePath(vmPathName, &datastoreName, &directoryName,
2737
                                   &directoryAndFileName) < 0) {
M
Matthias Bolte 已提交
2738
        goto cleanup;
2739 2740
    }

2741
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
2742
                      domain->conn->uri->server, domain->conn->uri->port);
2743
    virBufferURIEncodeString(&buffer, directoryAndFileName);
2744
    virBufferAddLit(&buffer, "?dcPath=");
2745
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
2746 2747 2748 2749
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
2750
        virReportOOMError();
M
Matthias Bolte 已提交
2751
        goto cleanup;
2752 2753
    }

2754 2755
    url = virBufferContentAndReset(&buffer);

2756
    if (esxVI_CURL_Download(priv->primary->curl, url, &vmx, 0, NULL) < 0) {
M
Matthias Bolte 已提交
2757
        goto cleanup;
2758 2759
    }

2760
    data.ctx = priv->primary;
2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774

    if (directoryName == NULL) {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s]",
                        datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    } else {
        if (virAsprintf(&data.datastorePathWithoutFileName, "[%s] %s",
                        datastoreName, directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }
2775 2776 2777 2778 2779 2780

    ctx.opaque = &data;
    ctx.parseFileName = esxParseVMXFileName;
    ctx.formatFileName = NULL;
    ctx.autodetectSCSIControllerModel = NULL;

2781
    def = virVMXParseConfig(&ctx, priv->caps, vmx);
2782 2783

    if (def != NULL) {
2784 2785 2786 2787
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
            def->id = id;
        }

2788
        xml = virDomainDefFormat(def, flags);
2789 2790 2791
    }

  cleanup:
M
Matthias Bolte 已提交
2792 2793 2794 2795
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

2796 2797
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
2798
    VIR_FREE(datastoreName);
M
Matthias Bolte 已提交
2799
    VIR_FREE(directoryName);
2800
    VIR_FREE(directoryAndFileName);
2801
    VIR_FREE(url);
2802
    VIR_FREE(data.datastorePathWithoutFileName);
2803
    VIR_FREE(vmx);
2804
    virDomainDefFree(def);
2805 2806 2807 2808 2809 2810 2811 2812 2813

    return xml;
}



static char *
esxDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat,
                       const char *nativeConfig,
E
Eric Blake 已提交
2814
                       unsigned int flags)
2815
{
M
Matthias Bolte 已提交
2816
    esxPrivate *priv = conn->privateData;
2817
    virVMXContext ctx;
2818
    esxVMX_Data data;
2819 2820 2821
    virDomainDefPtr def = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2822 2823
    virCheckFlags(0, NULL);

2824
    memset(&data, 0, sizeof(data));
2825

2826
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2827 2828
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
2829
        return NULL;
2830 2831
    }

2832
    data.ctx = priv->primary;
2833
    data.datastorePathWithoutFileName = (char *)"[?] ?";
2834 2835 2836 2837 2838 2839

    ctx.opaque = &data;
    ctx.parseFileName = esxParseVMXFileName;
    ctx.formatFileName = NULL;
    ctx.autodetectSCSIControllerModel = NULL;

2840
    def = virVMXParseConfig(&ctx, priv->caps, nativeConfig);
2841 2842

    if (def != NULL) {
2843
        xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
2844 2845 2846 2847 2848 2849 2850 2851 2852
    }

    virDomainDefFree(def);

    return xml;
}



M
Matthias Bolte 已提交
2853 2854 2855
static char *
esxDomainXMLToNative(virConnectPtr conn, const char *nativeFormat,
                     const char *domainXml,
E
Eric Blake 已提交
2856
                     unsigned int flags)
M
Matthias Bolte 已提交
2857
{
M
Matthias Bolte 已提交
2858
    esxPrivate *priv = conn->privateData;
2859 2860
    int virtualHW_version;
    virVMXContext ctx;
2861
    esxVMX_Data data;
M
Matthias Bolte 已提交
2862 2863 2864
    virDomainDefPtr def = NULL;
    char *vmx = NULL;

E
Eric Blake 已提交
2865 2866
    virCheckFlags(0, NULL);

2867
    memset(&data, 0, sizeof(data));
2868

M
Matthias Bolte 已提交
2869
    if (STRNEQ(nativeFormat, "vmware-vmx")) {
2870 2871
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Unsupported config format '%s'"), nativeFormat);
M
Matthias Bolte 已提交
2872 2873 2874
        return NULL;
    }

2875 2876 2877 2878 2879 2880 2881
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        return NULL;
    }

M
Matthias Bolte 已提交
2882 2883
    def = virDomainDefParseString(priv->caps, domainXml,
                                  1 << VIR_DOMAIN_VIRT_VMWARE, 0);
M
Matthias Bolte 已提交
2884 2885 2886 2887 2888

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

2889
    data.ctx = priv->primary;
2890
    data.datastorePathWithoutFileName = NULL;
2891 2892 2893 2894 2895 2896

    ctx.opaque = &data;
    ctx.parseFileName = NULL;
    ctx.formatFileName = esxFormatVMXFileName;
    ctx.autodetectSCSIControllerModel = esxAutodetectSCSIControllerModel;

2897
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
2898 2899 2900 2901 2902 2903 2904 2905

    virDomainDefFree(def);

    return vmx;
}



2906 2907 2908
static int
esxListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
{
M
Matthias Bolte 已提交
2909
    bool success = false;
M
Matthias Bolte 已提交
2910
    esxPrivate *priv = conn->privateData;
2911 2912 2913 2914 2915
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachinePowerState powerState;
    int count = 0;
2916
    int i;
2917 2918 2919 2920 2921

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

2922
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
2923
        return -1;
2924 2925
    }

2926
    if (esxVI_String_AppendValueListToList(&propertyNameList,
2927 2928
                                           "name\0"
                                           "runtime.powerState\0") < 0 ||
2929 2930
        esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2931
        goto cleanup;
2932 2933 2934 2935
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
2936
        if (esxVI_GetVirtualMachinePowerState(virtualMachine,
2937
                                              &powerState) < 0) {
M
Matthias Bolte 已提交
2938
            goto cleanup;
2939 2940 2941 2942 2943 2944
        }

        if (powerState == esxVI_VirtualMachinePowerState_PoweredOn) {
            continue;
        }

2945
        names[count] = NULL;
2946

2947 2948 2949
        if (esxVI_GetVirtualMachineIdentity(virtualMachine, NULL, &names[count],
                                            NULL) < 0) {
            goto cleanup;
2950 2951
        }

2952 2953
        ++count;

2954 2955 2956 2957 2958
        if (count >= maxnames) {
            break;
        }
    }

M
Matthias Bolte 已提交
2959
    success = true;
2960

M
Matthias Bolte 已提交
2961 2962 2963 2964 2965
  cleanup:
    if (! success) {
        for (i = 0; i < count; ++i) {
            VIR_FREE(names[i]);
        }
2966

M
Matthias Bolte 已提交
2967
        count = -1;
2968 2969
    }

M
Matthias Bolte 已提交
2970 2971
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
2972

M
Matthias Bolte 已提交
2973
    return count;
2974 2975 2976 2977 2978 2979 2980
}



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

2983
    if (esxVI_EnsureSession(priv->primary) < 0) {
2984 2985 2986
        return -1;
    }

2987
    return esxVI_LookupNumberOfDomainsByPowerState
2988
             (priv->primary, esxVI_VirtualMachinePowerState_PoweredOn, true);
2989 2990 2991 2992 2993
}



static int
2994
esxDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
2995
{
M
Matthias Bolte 已提交
2996
    int result = -1;
M
Matthias Bolte 已提交
2997
    esxPrivate *priv = domain->conn->privateData;
2998 2999 3000
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;
3001
    int id = -1;
3002 3003
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3004
    char *taskInfoErrorMessage = NULL;
3005

3006 3007
    virCheckFlags(0, -1);

3008
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3009
        return -1;
3010 3011
    }

3012
    if (esxVI_String_AppendValueToList(&propertyNameList,
3013
                                       "runtime.powerState") < 0 ||
3014
        esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3015
          (priv->primary, domain->uuid, propertyNameList, &virtualMachine,
3016
           priv->parsedUri->autoAnswer) < 0 ||
3017 3018
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0 ||
        esxVI_GetVirtualMachineIdentity(virtualMachine, &id, NULL, NULL) < 0) {
M
Matthias Bolte 已提交
3019
        goto cleanup;
3020 3021 3022
    }

    if (powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3023 3024
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not powered off"));
M
Matthias Bolte 已提交
3025
        goto cleanup;
3026 3027
    }

3028
    if (esxVI_PowerOnVM_Task(priv->primary, virtualMachine->obj, NULL,
3029
                             &task) < 0 ||
3030
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3031
                                    esxVI_Occurrence_RequiredItem,
3032
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3033
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3034
        goto cleanup;
3035 3036 3037
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3038 3039
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not start domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3040
        goto cleanup;
3041 3042
    }

3043
    domain->id = id;
M
Matthias Bolte 已提交
3044 3045
    result = 0;

3046 3047 3048 3049
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&task);
3050
    VIR_FREE(taskInfoErrorMessage);
3051 3052 3053 3054

    return result;
}

3055 3056


3057 3058 3059 3060 3061
static int
esxDomainCreate(virDomainPtr domain)
{
    return esxDomainCreateWithFlags(domain, 0);
}
3062

3063 3064


M
Matthias Bolte 已提交
3065
static virDomainPtr
3066
esxDomainDefineXML(virConnectPtr conn, const char *xml)
M
Matthias Bolte 已提交
3067
{
M
Matthias Bolte 已提交
3068
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
3069 3070
    virDomainDefPtr def = NULL;
    char *vmx = NULL;
3071 3072
    int i;
    virDomainDiskDefPtr disk = NULL;
M
Matthias Bolte 已提交
3073
    esxVI_ObjectContent *virtualMachine = NULL;
3074 3075
    int virtualHW_version;
    virVMXContext ctx;
3076
    esxVMX_Data data;
M
Matthias Bolte 已提交
3077 3078
    char *datastoreName = NULL;
    char *directoryName = NULL;
3079
    char *escapedName = NULL;
M
Matthias Bolte 已提交
3080 3081 3082 3083 3084 3085 3086 3087
    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;
3088
    char *taskInfoErrorMessage = NULL;
M
Matthias Bolte 已提交
3089 3090
    virDomainPtr domain = NULL;

3091
    memset(&data, 0, sizeof(data));
3092

3093
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3094
        return NULL;
M
Matthias Bolte 已提交
3095 3096 3097
    }

    /* Parse domain XML */
M
Matthias Bolte 已提交
3098
    def = virDomainDefParseString(priv->caps, xml, 1 << VIR_DOMAIN_VIRT_VMWARE,
M
Matthias Bolte 已提交
3099 3100 3101
                                  VIR_DOMAIN_XML_INACTIVE);

    if (def == NULL) {
M
Matthias Bolte 已提交
3102
        return NULL;
M
Matthias Bolte 已提交
3103 3104 3105
    }

    /* Check if an existing domain should be edited */
3106
    if (esxVI_LookupVirtualMachineByUuid(priv->primary, def->uuid, NULL,
M
Matthias Bolte 已提交
3107
                                         &virtualMachine,
M
Matthias Bolte 已提交
3108
                                         esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
3109
        goto cleanup;
M
Matthias Bolte 已提交
3110 3111
    }

3112 3113 3114 3115 3116 3117 3118
    if (virtualMachine == NULL &&
        esxVI_LookupVirtualMachineByName(priv->primary, def->name, NULL,
                                         &virtualMachine,
                                         esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
    }

M
Matthias Bolte 已提交
3119 3120
    if (virtualMachine != NULL) {
        /* FIXME */
3121 3122 3123
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain already exists, editing existing domains is not "
                         "supported yet"));
M
Matthias Bolte 已提交
3124
        goto cleanup;
M
Matthias Bolte 已提交
3125 3126 3127
    }

    /* Build VMX from domain XML */
3128 3129 3130 3131 3132 3133 3134
    virtualHW_version = esxVI_ProductVersionToDefaultVirtualHWVersion
                          (priv->primary->productVersion);

    if (virtualHW_version < 0) {
        goto cleanup;
    }

3135
    data.ctx = priv->primary;
3136
    data.datastorePathWithoutFileName = NULL;
3137 3138 3139 3140 3141 3142

    ctx.opaque = &data;
    ctx.parseFileName = NULL;
    ctx.formatFileName = esxFormatVMXFileName;
    ctx.autodetectSCSIControllerModel = esxAutodetectSCSIControllerModel;

3143
    vmx = virVMXFormatConfig(&ctx, priv->caps, def, virtualHW_version);
M
Matthias Bolte 已提交
3144 3145

    if (vmx == NULL) {
M
Matthias Bolte 已提交
3146
        goto cleanup;
M
Matthias Bolte 已提交
3147 3148
    }

3149 3150 3151 3152 3153 3154 3155
    /*
     * 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 已提交
3156
    if (def->ndisks < 1) {
3157 3158 3159
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Domain XML doesn't contain any disks, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3160
        goto cleanup;
3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
    }

    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) {
3172 3173 3174
        virReportError(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 已提交
3175
        goto cleanup;
M
Matthias Bolte 已提交
3176 3177
    }

3178
    if (disk->src == NULL) {
3179 3180 3181
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("First file-based harddisk has no source, cannot deduce "
                         "datastore and path for VMX file"));
M
Matthias Bolte 已提交
3182
        goto cleanup;
M
Matthias Bolte 已提交
3183 3184
    }

3185
    if (esxUtil_ParseDatastorePath(disk->src, &datastoreName, &directoryName,
3186
                                   NULL) < 0) {
M
Matthias Bolte 已提交
3187
        goto cleanup;
M
Matthias Bolte 已提交
3188 3189
    }

3190
    if (! virFileHasSuffix(disk->src, ".vmdk")) {
3191 3192 3193
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting source '%s' of first file-based harddisk to "
                         "be a VMDK image"), disk->src);
M
Matthias Bolte 已提交
3194
        goto cleanup;
M
Matthias Bolte 已提交
3195 3196
    }

3197
    virBufferAsprintf(&buffer, "%s://%s:%d/folder/", priv->parsedUri->transport,
M
Matthias Bolte 已提交
3198 3199 3200 3201 3202 3203 3204
                      conn->uri->server, conn->uri->port);

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

3205 3206 3207 3208 3209 3210 3211
    escapedName = esxUtil_EscapeDatastoreItem(def->name);

    if (escapedName == NULL) {
        goto cleanup;
    }

    virBufferURIEncodeString(&buffer, escapedName);
M
Matthias Bolte 已提交
3212
    virBufferAddLit(&buffer, ".vmx?dcPath=");
3213
    virBufferURIEncodeString(&buffer, priv->primary->datacenterPath);
M
Matthias Bolte 已提交
3214 3215 3216 3217
    virBufferAddLit(&buffer, "&dsName=");
    virBufferURIEncodeString(&buffer, datastoreName);

    if (virBufferError(&buffer)) {
3218
        virReportOOMError();
M
Matthias Bolte 已提交
3219
        goto cleanup;
M
Matthias Bolte 已提交
3220 3221 3222 3223
    }

    url = virBufferContentAndReset(&buffer);

3224 3225 3226 3227 3228 3229
    /* Check, if VMX file already exists */
    /* FIXME */

    /* Upload VMX file */
    VIR_DEBUG("Uploading .vmx config, url='%s' vmx='%s'", url, vmx);

3230
    if (esxVI_CURL_Upload(priv->primary->curl, url, vmx) < 0) {
3231 3232 3233 3234
        goto cleanup;
    }

    /* Register the domain */
M
Matthias Bolte 已提交
3235 3236
    if (directoryName != NULL) {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s/%s.vmx", datastoreName,
3237
                        directoryName, escapedName) < 0) {
3238
            virReportOOMError();
M
Matthias Bolte 已提交
3239
            goto cleanup;
M
Matthias Bolte 已提交
3240 3241 3242
        }
    } else {
        if (virAsprintf(&datastoreRelatedPath, "[%s] %s.vmx", datastoreName,
3243
                        escapedName) < 0) {
3244
            virReportOOMError();
M
Matthias Bolte 已提交
3245
            goto cleanup;
M
Matthias Bolte 已提交
3246 3247 3248
        }
    }

3249
    if (esxVI_RegisterVM_Task(priv->primary, priv->primary->datacenter->vmFolder,
M
Matthias Bolte 已提交
3250
                              datastoreRelatedPath, NULL, esxVI_Boolean_False,
3251 3252 3253 3254
                              priv->primary->computeResource->resourcePool,
                              priv->primary->hostSystem->_reference,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, def->uuid,
3255
                                    esxVI_Occurrence_OptionalItem,
3256
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3257
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3258
        goto cleanup;
M
Matthias Bolte 已提交
3259 3260 3261
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3262 3263
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not define domain: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3264
        goto cleanup;
M
Matthias Bolte 已提交
3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
    }

    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 已提交
3276 3277 3278 3279
    if (url == NULL) {
        virBufferFreeAndReset(&buffer);
    }

M
Matthias Bolte 已提交
3280 3281 3282 3283
    virDomainDefFree(def);
    VIR_FREE(vmx);
    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3284
    VIR_FREE(escapedName);
M
Matthias Bolte 已提交
3285 3286 3287 3288 3289 3290 3291
    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);
3292
    VIR_FREE(taskInfoErrorMessage);
M
Matthias Bolte 已提交
3293 3294 3295 3296 3297 3298

    return domain;
}



3299
static int
3300 3301
esxDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
3302
{
M
Matthias Bolte 已提交
3303
    int result = -1;
M
Matthias Bolte 已提交
3304
    esxPrivate *priv = domain->conn->privateData;
3305
    esxVI_Context *ctx = NULL;
3306 3307 3308 3309
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

3310 3311 3312 3313
    /* No managed save, so we explicitly reject
     * VIR_DOMAIN_UNDEFINE_MANAGED_SAVE.  No snapshot metadata for
     * ESX, so we can trivially ignore that flag.  */
    virCheckFlags(VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
3314

3315 3316 3317 3318 3319 3320
    if (priv->vCenter != NULL) {
        ctx = priv->vCenter;
    } else {
        ctx = priv->host;
    }

3321
    if (esxVI_EnsureSession(ctx) < 0) {
M
Matthias Bolte 已提交
3322
        return -1;
3323 3324
    }

3325
    if (esxVI_String_AppendValueToList(&propertyNameList,
3326
                                       "runtime.powerState") < 0 ||
3327 3328
        esxVI_LookupVirtualMachineByUuid(ctx, domain->uuid, propertyNameList,
                                         &virtualMachine,
M
Matthias Bolte 已提交
3329
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3330
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
3331
        goto cleanup;
3332 3333 3334 3335
    }

    if (powerState != esxVI_VirtualMachinePowerState_Suspended &&
        powerState != esxVI_VirtualMachinePowerState_PoweredOff) {
3336 3337
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not suspended or powered off"));
M
Matthias Bolte 已提交
3338
        goto cleanup;
3339 3340
    }

3341
    if (esxVI_UnregisterVM(ctx, virtualMachine->obj) < 0) {
M
Matthias Bolte 已提交
3342
        goto cleanup;
3343 3344
    }

M
Matthias Bolte 已提交
3345 3346
    result = 0;

3347 3348 3349 3350 3351 3352 3353 3354
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);

    return result;
}


3355 3356 3357 3358 3359
static int
esxDomainUndefine(virDomainPtr domain)
{
    return esxDomainUndefineFlags(domain, 0);
}
3360

3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
static int
esxDomainGetAutostart(virDomainPtr domain, int *autostart)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_AutoStartDefaults *defaults = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;

    *autostart = 0;

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

    /* Check general autostart config */
    if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
        goto cleanup;
    }

    if (defaults->enabled != esxVI_Boolean_True) {
        /* Autostart is disabled in general, exit early here */
        result = 0;
        goto cleanup;
    }

    /* Check specific autostart config */
    if (esxVI_LookupAutoStartPowerInfoList(priv->primary, &powerInfoList) < 0) {
        goto cleanup;
    }

    if (powerInfoList == NULL) {
        /* powerInfo list is empty, exit early here */
        result = 0;
        goto cleanup;
    }

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    for (powerInfo = powerInfoList; powerInfo != NULL;
         powerInfo = powerInfo->_next) {
        if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
            if (STRCASEEQ(powerInfo->startAction, "powerOn")) {
                *autostart = 1;
            }

            break;
        }
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_AutoStartDefaults_Free(&defaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



static int
esxDomainSetAutostart(virDomainPtr domain, int autostart)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_HostAutoStartManagerConfig *spec = NULL;
    esxVI_AutoStartDefaults *defaults = NULL;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_AutoStartPowerInfo *newPowerInfo = NULL;
3441
    bool newPowerInfo_isAppended = false;
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479

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

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_HostAutoStartManagerConfig_Alloc(&spec) < 0) {
        goto cleanup;
    }

    if (autostart) {
        /*
         * There is a general autostart option that affects the autostart
         * behavior of all domains. If it's disabled then no domain does
         * autostart. If it's enabled then the autostart behavior depends on
         * the per-domain autostart config.
         */
        if (esxVI_LookupAutoStartDefaults(priv->primary, &defaults) < 0) {
            goto cleanup;
        }

        if (defaults->enabled != esxVI_Boolean_True) {
            /*
             * Autostart is disabled in general. Check if no other domain is
             * in the list of autostarted domains, so it's safe to enable the
             * general autostart option without affecting the autostart
             * behavior of other domains.
             */
            if (esxVI_LookupAutoStartPowerInfoList(priv->primary,
                                                   &powerInfoList) < 0) {
                goto cleanup;
            }

            for (powerInfo = powerInfoList; powerInfo != NULL;
                 powerInfo = powerInfo->_next) {
                if (STRNEQ(powerInfo->key->value, virtualMachine->obj->value)) {
3480 3481 3482
                    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                   _("Cannot enable general autostart option "
                                     "without affecting other domains"));
3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
                    goto cleanup;
                }
            }

            /* Enable autostart in general */
            if (esxVI_AutoStartDefaults_Alloc(&spec->defaults) < 0) {
                goto cleanup;
            }

            spec->defaults->enabled = esxVI_Boolean_True;
        }
    }

    if (esxVI_AutoStartPowerInfo_Alloc(&newPowerInfo) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startOrder) < 0 ||
        esxVI_Int_Alloc(&newPowerInfo->startDelay) < 0 ||
3499
        esxVI_Int_Alloc(&newPowerInfo->stopDelay) < 0) {
3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
        goto cleanup;
    }

    newPowerInfo->key = virtualMachine->obj;
    newPowerInfo->startOrder->value = -1; /* no specific start order */
    newPowerInfo->startDelay->value = -1; /* use system default */
    newPowerInfo->waitForHeartbeat = esxVI_AutoStartWaitHeartbeatSetting_SystemDefault;
    newPowerInfo->startAction = autostart ? (char *)"powerOn" : (char *)"none";
    newPowerInfo->stopDelay->value = -1; /* use system default */
    newPowerInfo->stopAction = (char *)"none";

3511 3512 3513 3514 3515 3516 3517
    if (esxVI_AutoStartPowerInfo_AppendToList(&spec->powerInfo,
                                              newPowerInfo) < 0) {
        goto cleanup;
    }

    newPowerInfo_isAppended = true;

3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
    if (esxVI_ReconfigureAutostart
          (priv->primary,
           priv->primary->hostSystem->configManager->autoStartManager,
           spec) < 0) {
        goto cleanup;
    }

    result = 0;

  cleanup:
    if (newPowerInfo != NULL) {
        newPowerInfo->key = NULL;
        newPowerInfo->startAction = NULL;
        newPowerInfo->stopAction = NULL;
    }

    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_HostAutoStartManagerConfig_Free(&spec);
    esxVI_AutoStartDefaults_Free(&defaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);

3539 3540 3541 3542
    if (!newPowerInfo_isAppended) {
        esxVI_AutoStartPowerInfo_Free(&newPowerInfo);
    }

3543 3544 3545 3546 3547
    return result;
}



3548 3549 3550 3551 3552 3553 3554 3555 3556 3557
/*
 * 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:
 *
3558
 * - reservation (VIR_TYPED_PARAM_LLONG >= 0, in megaherz)
3559
 *
3560
 *   The amount of CPU resource that is guaranteed to be available to the domain.
3561 3562
 *
 *
3563
 * - limit (VIR_TYPED_PARAM_LLONG >= 0, or -1, in megaherz)
3564
 *
3565 3566
 *   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
3567 3568 3569 3570
 *   utilization of the domain is unlimited. If the limit is not set to -1, it
 *   must be greater than or equal to the reservation.
 *
 *
3571
 * - shares (VIR_TYPED_PARAM_INT >= 0, or in {-1, -2, -3}, no unit)
3572 3573 3574 3575 3576 3577
 *
 *   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'.
 */
3578
static char *
3579
esxDomainGetSchedulerType(virDomainPtr domain ATTRIBUTE_UNUSED, int *nparams)
3580 3581 3582 3583
{
    char *type = strdup("allocation");

    if (type == NULL) {
3584
        virReportOOMError();
3585
        return NULL;
3586 3587
    }

3588 3589 3590
    if (nparams != NULL) {
        *nparams = 3; /* reservation, limit, shares */
    }
3591 3592 3593 3594 3595 3596 3597

    return type;
}



static int
3598 3599 3600
esxDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
3601
{
M
Matthias Bolte 已提交
3602
    int result = -1;
M
Matthias Bolte 已提交
3603
    esxPrivate *priv = domain->conn->privateData;
3604 3605 3606 3607 3608 3609 3610
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    unsigned int mask = 0;
    int i = 0;

3611 3612
    virCheckFlags(0, -1);

3613
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3614
        return -1;
3615 3616
    }

3617
    if (esxVI_String_AppendValueListToList(&propertyNameList,
3618 3619 3620
                                           "config.cpuAllocation.reservation\0"
                                           "config.cpuAllocation.limit\0"
                                           "config.cpuAllocation.shares\0") < 0 ||
3621
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
3622
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
3623
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3624
        goto cleanup;
3625 3626 3627
    }

    for (dynamicProperty = virtualMachine->propSet;
3628
         dynamicProperty != NULL && mask != 7 && i < 3 && i < *nparams;
3629 3630
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.cpuAllocation.reservation") &&
M
Matthias Bolte 已提交
3631
            ! (mask & (1 << 0))) {
3632
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3633
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3634
                goto cleanup;
3635
            }
3636 3637 3638 3639 3640
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_RESERVATION,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3641 3642 3643 3644
            mask |= 1 << 0;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.limit") &&
M
Matthias Bolte 已提交
3645
                   ! (mask & (1 << 1))) {
3646
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
3647
                                         esxVI_Type_Long) < 0) {
M
Matthias Bolte 已提交
3648
                goto cleanup;
3649
            }
3650 3651 3652 3653 3654
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_LIMIT,
                                        VIR_TYPED_PARAM_LLONG,
                                        dynamicProperty->val->int64) < 0)
                goto cleanup;
3655 3656 3657 3658
            mask |= 1 << 1;
            ++i;
        } else if (STREQ(dynamicProperty->name,
                         "config.cpuAllocation.shares") &&
M
Matthias Bolte 已提交
3659
                   ! (mask & (1 << 2))) {
3660 3661 3662 3663
            if (virTypedParameterAssign(&params[i],
                                        VIR_DOMAIN_SCHEDULER_SHARES,
                                        VIR_TYPED_PARAM_INT, 0) < 0)
                goto cleanup;
3664
            if (esxVI_SharesInfo_CastFromAnyType(dynamicProperty->val,
3665
                                                 &sharesInfo) < 0) {
M
Matthias Bolte 已提交
3666
                goto cleanup;
3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
            }

            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:
3687 3688 3689
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Shares level has unknown value %d"),
                               (int)sharesInfo->level);
M
Matthias Bolte 已提交
3690
                goto cleanup;
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
            }

            esxVI_SharesInfo_Free(&sharesInfo);

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

    *nparams = i;
M
Matthias Bolte 已提交
3703
    result = 0;
3704 3705 3706 3707 3708 3709 3710 3711

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

    return result;
}

3712 3713 3714 3715 3716 3717
static int
esxDomainGetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int *nparams)
{
    return esxDomainGetSchedulerParametersFlags(domain, params, nparams, 0);
}
3718 3719 3720


static int
3721 3722 3723
esxDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int nparams,
                                     unsigned int flags)
3724
{
M
Matthias Bolte 已提交
3725
    int result = -1;
M
Matthias Bolte 已提交
3726
    esxPrivate *priv = domain->conn->privateData;
3727 3728 3729 3730 3731
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_SharesInfo *sharesInfo = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3732
    char *taskInfoErrorMessage = NULL;
3733 3734
    int i;

3735
    virCheckFlags(0, -1);
3736 3737 3738 3739 3740 3741 3742 3743 3744
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_SCHEDULER_RESERVATION,
                                       VIR_TYPED_PARAM_LLONG,
                                       VIR_DOMAIN_SCHEDULER_LIMIT,
                                       VIR_TYPED_PARAM_LLONG,
                                       VIR_DOMAIN_SCHEDULER_SHARES,
                                       VIR_TYPED_PARAM_INT,
                                       NULL) < 0)
        return -1;
3745

3746
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
3747
        return -1;
3748 3749
    }

3750
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
3751
          (priv->primary, domain->uuid, NULL, &virtualMachine,
3752
           priv->parsedUri->autoAnswer) < 0 ||
3753 3754
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->cpuAllocation) < 0) {
M
Matthias Bolte 已提交
3755
        goto cleanup;
3756 3757 3758
    }

    for (i = 0; i < nparams; ++i) {
3759
        if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_RESERVATION)) {
3760
            if (esxVI_Long_Alloc(&spec->cpuAllocation->reservation) < 0) {
M
Matthias Bolte 已提交
3761
                goto cleanup;
3762 3763 3764
            }

            if (params[i].value.l < 0) {
3765 3766 3767
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set reservation to %lld MHz, expecting "
                                 "positive value"), params[i].value.l);
M
Matthias Bolte 已提交
3768
                goto cleanup;
3769 3770 3771
            }

            spec->cpuAllocation->reservation->value = params[i].value.l;
3772
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_LIMIT)) {
3773
            if (esxVI_Long_Alloc(&spec->cpuAllocation->limit) < 0) {
M
Matthias Bolte 已提交
3774
                goto cleanup;
3775 3776 3777
            }

            if (params[i].value.l < -1) {
3778 3779 3780 3781
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Could not set limit to %lld MHz, expecting "
                                 "positive value or -1 (unlimited)"),
                               params[i].value.l);
M
Matthias Bolte 已提交
3782
                goto cleanup;
3783 3784 3785
            }

            spec->cpuAllocation->limit->value = params[i].value.l;
3786
        } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_SHARES)) {
3787 3788
            if (esxVI_SharesInfo_Alloc(&sharesInfo) < 0 ||
                esxVI_Int_Alloc(&sharesInfo->shares) < 0) {
M
Matthias Bolte 已提交
3789
                goto cleanup;
3790 3791 3792 3793
            }

            spec->cpuAllocation->shares = sharesInfo;

3794
            if (params[i].value.i >= 0) {
3795
                spec->cpuAllocation->shares->level = esxVI_SharesLevel_Custom;
3796
                spec->cpuAllocation->shares->shares->value = params[i].value.i;
3797
            } else {
3798
                switch (params[i].value.i) {
3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
                  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:
3817 3818 3819 3820
                    virReportError(VIR_ERR_INVALID_ARG,
                                   _("Could not set shares to %d, expecting positive "
                                     "value or -1 (low), -2 (normal) or -3 (high)"),
                                   params[i].value.i);
M
Matthias Bolte 已提交
3821
                    goto cleanup;
3822 3823 3824 3825 3826
                }
            }
        }
    }

3827
    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
3828
                              &task) < 0 ||
3829
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
3830
                                    esxVI_Occurrence_RequiredItem,
3831
                                    priv->parsedUri->autoAnswer, &taskInfoState,
3832
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
3833
        goto cleanup;
3834 3835 3836
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3837 3838 3839
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change scheduler parameters: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
3840
        goto cleanup;
3841 3842
    }

M
Matthias Bolte 已提交
3843 3844
    result = 0;

3845 3846 3847 3848
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
3849
    VIR_FREE(taskInfoErrorMessage);
3850 3851 3852 3853

    return result;
}

3854 3855 3856 3857 3858 3859
static int
esxDomainSetSchedulerParameters(virDomainPtr domain,
                                virTypedParameterPtr params, int nparams)
{
    return esxDomainSetSchedulerParametersFlags(domain, params, nparams, 0);
}
3860

E
Eric Blake 已提交
3861 3862 3863 3864 3865 3866
/* The subset of migration flags we are able to support.  */
#define ESX_MIGRATION_FLAGS                     \
    (VIR_MIGRATE_PERSIST_DEST |                 \
     VIR_MIGRATE_UNDEFINE_SOURCE |              \
     VIR_MIGRATE_LIVE |                         \
     VIR_MIGRATE_PAUSED)
3867 3868 3869 3870 3871

static int
esxDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie ATTRIBUTE_UNUSED,
                        int *cookielen ATTRIBUTE_UNUSED,
3872 3873
                        const char *uri_in ATTRIBUTE_UNUSED,
                        char **uri_out,
E
Eric Blake 已提交
3874
                        unsigned long flags,
3875 3876 3877
                        const char *dname ATTRIBUTE_UNUSED,
                        unsigned long resource ATTRIBUTE_UNUSED)
{
3878
    esxPrivate *priv = dconn->privateData;
3879

E
Eric Blake 已提交
3880 3881
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

3882
    if (uri_in == NULL) {
3883 3884 3885 3886
        if (virAsprintf(uri_out, "vpxmigr://%s/%s/%s",
                        priv->vCenter->ipAddress,
                        priv->vCenter->computeResource->resourcePool->value,
                        priv->vCenter->hostSystem->_reference->value) < 0) {
3887
            virReportOOMError();
3888
            return -1;
3889 3890 3891
        }
    }

3892
    return 0;
3893 3894 3895 3896 3897 3898 3899 3900 3901
}



static int
esxDomainMigratePerform(virDomainPtr domain,
                        const char *cookie ATTRIBUTE_UNUSED,
                        int cookielen ATTRIBUTE_UNUSED,
                        const char *uri,
E
Eric Blake 已提交
3902
                        unsigned long flags,
3903 3904 3905
                        const char *dname,
                        unsigned long bandwidth ATTRIBUTE_UNUSED)
{
M
Matthias Bolte 已提交
3906
    int result = -1;
M
Matthias Bolte 已提交
3907
    esxPrivate *priv = domain->conn->privateData;
M
Martin Kletzander 已提交
3908
    virURIPtr parsedUri = NULL;
3909 3910 3911
    char *saveptr;
    char *path_resourcePool;
    char *path_hostSystem;
3912
    esxVI_ObjectContent *virtualMachine = NULL;
3913 3914
    esxVI_ManagedObjectReference resourcePool;
    esxVI_ManagedObjectReference hostSystem;
3915 3916 3917
    esxVI_Event *eventList = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3918
    char *taskInfoErrorMessage = NULL;
3919

E
Eric Blake 已提交
3920 3921
    virCheckFlags(ESX_MIGRATION_FLAGS, -1);

M
Matthias Bolte 已提交
3922
    if (priv->vCenter == NULL) {
3923 3924
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration not possible without a vCenter"));
M
Matthias Bolte 已提交
3925
        return -1;
3926 3927 3928
    }

    if (dname != NULL) {
3929 3930
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Renaming domains on migration not supported"));
M
Matthias Bolte 已提交
3931
        return -1;
3932 3933
    }

3934
    if (esxVI_EnsureSession(priv->vCenter) < 0) {
M
Matthias Bolte 已提交
3935
        return -1;
3936 3937
    }

3938
    /* Parse migration URI */
3939
    if (!(parsedUri = virURIParse(uri)))
M
Matthias Bolte 已提交
3940
        return -1;
3941

3942
    if (parsedUri->scheme == NULL || STRCASENEQ(parsedUri->scheme, "vpxmigr")) {
3943 3944
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Only vpxmigr:// migration URIs are supported"));
M
Matthias Bolte 已提交
3945
        goto cleanup;
3946 3947
    }

3948
    if (STRCASENEQ(priv->vCenter->ipAddress, parsedUri->server)) {
3949 3950 3951
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration source and destination have to refer to "
                         "the same vCenter"));
3952 3953 3954 3955 3956 3957 3958
        goto cleanup;
    }

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

    if (path_resourcePool == NULL || path_hostSystem == NULL) {
3959 3960
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Migration URI has to specify resource pool and host system"));
M
Matthias Bolte 已提交
3961
        goto cleanup;
3962 3963
    }

3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976
    resourcePool._next = NULL;
    resourcePool._type = esxVI_Type_ManagedObjectReference;
    resourcePool.type = (char *)"ResourcePool";
    resourcePool.value = path_resourcePool;

    hostSystem._next = NULL;
    hostSystem._type = esxVI_Type_ManagedObjectReference;
    hostSystem.type = (char *)"HostSystem";
    hostSystem.value = path_hostSystem;

    /* Lookup VirtualMachine */
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->vCenter, domain->uuid, NULL, &virtualMachine,
3977
           priv->parsedUri->autoAnswer) < 0) {
M
Matthias Bolte 已提交
3978
        goto cleanup;
3979 3980 3981
    }

    /* Validate the purposed migration */
3982
    if (esxVI_ValidateMigration(priv->vCenter, virtualMachine->obj,
3983 3984
                                esxVI_VirtualMachinePowerState_Undefined, NULL,
                                &resourcePool, &hostSystem, &eventList) < 0) {
M
Matthias Bolte 已提交
3985
        goto cleanup;
3986 3987 3988 3989 3990 3991 3992 3993
    }

    if (eventList != NULL) {
        /*
         * FIXME: Need to report the complete list of events. Limit reporting
         *        to the first event for now.
         */
        if (eventList->fullFormattedMessage != NULL) {
3994 3995 3996
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not migrate domain, validation reported a "
                             "problem: %s"), eventList->fullFormattedMessage);
3997
        } else {
3998 3999 4000
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not migrate domain, validation reported a "
                             "problem"));
4001 4002
        }

M
Matthias Bolte 已提交
4003
        goto cleanup;
4004 4005 4006
    }

    /* Perform the purposed migration */
4007 4008
    if (esxVI_MigrateVM_Task(priv->vCenter, virtualMachine->obj,
                             &resourcePool, &hostSystem,
4009 4010 4011
                             esxVI_VirtualMachineMovePriority_DefaultPriority,
                             esxVI_VirtualMachinePowerState_Undefined,
                             &task) < 0 ||
4012
        esxVI_WaitForTaskCompletion(priv->vCenter, task, domain->uuid,
4013
                                    esxVI_Occurrence_RequiredItem,
4014
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4015
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4016
        goto cleanup;
4017 4018 4019
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4020 4021 4022 4023
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not migrate domain, migration task finished with "
                         "an error: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4024
        goto cleanup;
4025 4026
    }

M
Matthias Bolte 已提交
4027 4028
    result = 0;

4029
  cleanup:
4030
    virURIFree(parsedUri);
4031 4032 4033
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_Event_Free(&eventList);
    esxVI_ManagedObjectReference_Free(&task);
4034
    VIR_FREE(taskInfoErrorMessage);
4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045

    return result;
}



static virDomainPtr
esxDomainMigrateFinish(virConnectPtr dconn, const char *dname,
                       const char *cookie ATTRIBUTE_UNUSED,
                       int cookielen ATTRIBUTE_UNUSED,
                       const char *uri ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
4046
                       unsigned long flags)
4047
{
E
Eric Blake 已提交
4048 4049
    virCheckFlags(ESX_MIGRATION_FLAGS, NULL);

4050 4051 4052 4053 4054
    return esxDomainLookupByName(dconn, dname);
}



M
Matthias Bolte 已提交
4055 4056 4057 4058
static unsigned long long
esxNodeGetFreeMemory(virConnectPtr conn)
{
    unsigned long long result = 0;
M
Matthias Bolte 已提交
4059
    esxPrivate *priv = conn->privateData;
M
Matthias Bolte 已提交
4060 4061 4062 4063 4064
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *resourcePool = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ResourcePoolResourceUsage *resourcePoolResourceUsage = NULL;

4065
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4066
        return 0;
M
Matthias Bolte 已提交
4067 4068 4069
    }

    /* Get memory usage of resource pool */
4070
    if (esxVI_String_AppendValueToList(&propertyNameList,
M
Matthias Bolte 已提交
4071
                                       "runtime.memory") < 0 ||
4072 4073
        esxVI_LookupObjectContentByType(priv->primary,
                                        priv->primary->computeResource->resourcePool,
4074
                                        "ResourcePool", propertyNameList,
4075 4076
                                        &resourcePool,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4077
        goto cleanup;
M
Matthias Bolte 已提交
4078 4079 4080 4081 4082 4083
    }

    for (dynamicProperty = resourcePool->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.memory")) {
            if (esxVI_ResourcePoolResourceUsage_CastFromAnyType
4084
                  (dynamicProperty->val, &resourcePoolResourceUsage) < 0) {
M
Matthias Bolte 已提交
4085
                goto cleanup;
M
Matthias Bolte 已提交
4086 4087 4088 4089 4090 4091 4092 4093 4094
            }

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

    if (resourcePoolResourceUsage == NULL) {
4095 4096
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve memory usage of resource pool"));
M
Matthias Bolte 已提交
4097
        goto cleanup;
M
Matthias Bolte 已提交
4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
    }

    result = resourcePoolResourceUsage->unreservedForVm->value;

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

    return result;
}



4112 4113 4114
static int
esxIsEncrypted(virConnectPtr conn)
{
M
Matthias Bolte 已提交
4115
    esxPrivate *priv = conn->privateData;
4116

4117
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128
        return 1;
    } else {
        return 0;
    }
}



static int
esxIsSecure(virConnectPtr conn)
{
M
Matthias Bolte 已提交
4129
    esxPrivate *priv = conn->privateData;
4130

4131
    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
4132 4133 4134 4135 4136 4137 4138 4139
        return 1;
    } else {
        return 0;
    }
}



4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
static int
esxIsAlive(virConnectPtr conn)
{
    esxPrivate *priv = conn->privateData;

    /* XXX we should be able to do something better than this but this is
     * simple, safe, and good enough for now. In worst case, the function will
     * return true even though the connection is not alive.
     */
    if (priv->primary)
        return 1;
    else
        return 0;
}



4157 4158 4159
static int
esxDomainIsActive(virDomainPtr domain)
{
M
Matthias Bolte 已提交
4160
    int result = -1;
M
Matthias Bolte 已提交
4161
    esxPrivate *priv = domain->conn->privateData;
4162 4163 4164 4165
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachinePowerState powerState;

4166
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4167
        return -1;
4168 4169
    }

4170
    if (esxVI_String_AppendValueToList(&propertyNameList,
4171
                                       "runtime.powerState") < 0 ||
4172
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
4173
                                         propertyNameList, &virtualMachine,
M
Matthias Bolte 已提交
4174
                                         esxVI_Occurrence_RequiredItem) < 0 ||
4175
        esxVI_GetVirtualMachinePowerState(virtualMachine, &powerState) < 0) {
M
Matthias Bolte 已提交
4176
        goto cleanup;
4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194
    }

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

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

    return result;
}



static int
4195
esxDomainIsPersistent(virDomainPtr domain)
4196
{
4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216
    /* ESX has no concept of transient domains, so all of them are
     * persistent.  However, we do want to check for existence. */
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;

    if (esxVI_EnsureSession(priv->primary) < 0)
        return -1;

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0)
        goto cleanup;

    result = 1;

cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4217 4218
}

M
Matthias Bolte 已提交
4219 4220


4221 4222 4223
static int
esxDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
{
4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243
    /* ESX domains never have a persistent state that differs from
     * current state.  However, we do want to check for existence.  */
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;

    if (esxVI_EnsureSession(priv->primary) < 0)
        return -1;

    if (esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         NULL, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0)
        goto cleanup;

    result = 0;

cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
4244
}
4245

M
Matthias Bolte 已提交
4246 4247


4248 4249
static virDomainSnapshotPtr
esxDomainSnapshotCreateXML(virDomainPtr domain, const char *xmlDesc,
4250
                           unsigned int flags)
4251 4252 4253 4254 4255 4256 4257 4258
{
    esxPrivate *priv = domain->conn->privateData;
    virDomainSnapshotDefPtr def = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4259
    char *taskInfoErrorMessage = NULL;
4260 4261
    virDomainSnapshotPtr snapshot = NULL;

4262 4263
    /* ESX has no snapshot metadata, so this flag is trivial.  */
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA, NULL);
4264

4265
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4266
        return NULL;
4267 4268
    }

4269
    def = virDomainSnapshotDefParseString(xmlDesc, NULL, 0, 0);
4270 4271

    if (def == NULL) {
M
Matthias Bolte 已提交
4272
        return NULL;
4273 4274
    }

4275
    if (def->ndisks) {
4276 4277
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("disk snapshots not supported yet"));
4278 4279 4280
        return NULL;
    }

4281
    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
4282
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4283
           priv->parsedUri->autoAnswer) < 0 ||
4284
        esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4285 4286
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, def->name,
4287
                                    &snapshotTree, NULL,
4288
                                    esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4289
        goto cleanup;
4290 4291 4292
    }

    if (snapshotTree != NULL) {
4293 4294
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Snapshot '%s' already exists"), def->name);
M
Matthias Bolte 已提交
4295
        goto cleanup;
4296 4297
    }

4298
    if (esxVI_CreateSnapshot_Task(priv->primary, virtualMachine->obj,
4299 4300 4301
                                  def->name, def->description,
                                  esxVI_Boolean_True,
                                  esxVI_Boolean_False, &task) < 0 ||
4302
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
4303
                                    esxVI_Occurrence_RequiredItem,
4304
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4305
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4306
        goto cleanup;
4307 4308 4309
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4310 4311
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create snapshot: %s"),
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4312
        goto cleanup;
4313 4314 4315 4316 4317 4318 4319 4320 4321
    }

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

  cleanup:
    virDomainSnapshotDefFree(def);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4322
    VIR_FREE(taskInfoErrorMessage);
4323 4324 4325 4326 4327 4328 4329

    return snapshot;
}



static char *
4330 4331
esxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
4332 4333 4334 4335 4336 4337 4338 4339 4340
{
    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;

4341 4342
    virCheckFlags(0, NULL);

4343
    memset(&def, 0, sizeof(def));
4344

4345
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4346
        return NULL;
4347 4348
    }

4349
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4350 4351 4352 4353
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, &snapshotTreeParent,
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4354
        goto cleanup;
4355 4356 4357 4358 4359 4360 4361 4362
    }

    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 已提交
4363
        goto cleanup;
4364 4365 4366 4367 4368 4369 4370
    }

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

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

4371
    xml = virDomainSnapshotDefFormat(uuid_string, &def, flags, 0);
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381

  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return xml;
}



static int
4382
esxDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
4383
{
M
Matthias Bolte 已提交
4384
    int count;
4385 4386
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4387
    bool recurse;
4388
    bool leaves;
4389

4390
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4391 4392
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4393 4394

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4395
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4396

4397
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4398
        return -1;
4399 4400
    }

4401 4402 4403 4404
    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        return 0;

4405
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4406
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4407
        return -1;
4408 4409
    }

4410 4411
    count = esxVI_GetNumberOfSnapshotTrees(rootSnapshotTreeList, recurse,
                                           leaves);
4412 4413 4414

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

M
Matthias Bolte 已提交
4415
    return count;
4416 4417 4418 4419 4420 4421
}



static int
esxDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
4422
                           unsigned int flags)
4423
{
M
Matthias Bolte 已提交
4424
    int result;
4425 4426
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
4427
    bool recurse;
4428
    bool leaves;
4429 4430

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
4431 4432
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4433

4434
    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) == 0;
4435
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4436

4437
    if (names == NULL || nameslen < 0) {
4438
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4439 4440 4441
        return -1;
    }

4442
    if (nameslen == 0 || (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)) {
4443 4444 4445
        return 0;
    }

4446
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4447
        return -1;
4448 4449
    }

4450
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4451
                                         &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
4452
        return -1;
4453 4454
    }

4455
    result = esxVI_GetSnapshotTreeNames(rootSnapshotTreeList, names, nameslen,
4456
                                        recurse, leaves);
4457 4458 4459 4460 4461 4462 4463 4464

    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4465 4466 4467 4468 4469 4470 4471 4472
static int
esxDomainSnapshotNumChildren(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    int count = -1;
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    bool recurse;
4473
    bool leaves;
4474 4475

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4476 4477
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4478 4479

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4480
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500

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

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

    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        count = 0;
        goto cleanup;
    }

    count = esxVI_GetNumberOfSnapshotTrees(snapshotTree->childSnapshotList,
4501
                                           recurse, leaves);
4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return count;
}



static int
esxDomainSnapshotListChildrenNames(virDomainSnapshotPtr snapshot,
                                   char **names, int nameslen,
                                   unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    bool recurse;
4521
    bool leaves;
4522 4523

    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS |
4524 4525
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA |
                  VIR_DOMAIN_SNAPSHOT_LIST_LEAVES, -1);
4526 4527

    recurse = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) != 0;
4528
    leaves = (flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) != 0;
4529 4530

    if (names == NULL || nameslen < 0) {
4531
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument"));
4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557
        return -1;
    }

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

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

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

    /* ESX snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        result = 0;
        goto cleanup;
    }

    result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
4558
                                        names, nameslen, recurse, leaves);
4559 4560 4561 4562 4563 4564 4565 4566 4567

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



4568 4569
static virDomainSnapshotPtr
esxDomainSnapshotLookupByName(virDomainPtr domain, const char *name,
4570
                              unsigned int flags)
4571 4572 4573 4574 4575 4576
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    virDomainSnapshotPtr snapshot = NULL;

4577 4578
    virCheckFlags(0, NULL);

4579
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4580
        return NULL;
4581 4582
    }

4583
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, domain->uuid,
4584 4585
                                         &rootSnapshotTreeList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotTreeList, name, &snapshotTree,
4586
                                    NULL,
4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606
                                    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;

4607
    virCheckFlags(0, -1);
4608

4609
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4610
        return -1;
4611 4612
    }

4613
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4614 4615
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_OptionalItem) < 0) {
M
Matthias Bolte 已提交
4616
        return -1;
4617 4618 4619
    }

    if (currentSnapshotTree != NULL) {
M
Matthias Bolte 已提交
4620 4621
        esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
        return 1;
4622 4623
    }

M
Matthias Bolte 已提交
4624
    return 0;
4625 4626 4627 4628
}



E
Eric Blake 已提交
4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652
static virDomainSnapshotPtr
esxDomainSnapshotGetParent(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTreeParent = NULL;
    virDomainSnapshotPtr parent = NULL;

    virCheckFlags(0, NULL);

    if (esxVI_EnsureSession(priv->primary) < 0) {
        return NULL;
    }

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

    if (!snapshotTreeParent) {
4653 4654 4655
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshotTree->name);
E
Eric Blake 已提交
4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668
        goto cleanup;
    }

    parent = virGetDomainSnapshot(snapshot->domain, snapshotTreeParent->name);

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);

    return parent;
}



4669 4670 4671 4672 4673
static virDomainSnapshotPtr
esxDomainSnapshotCurrent(virDomainPtr domain, unsigned int flags)
{
    esxPrivate *priv = domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
M
Matthias Bolte 已提交
4674
    virDomainSnapshotPtr snapshot = NULL;
4675

4676
    virCheckFlags(0, NULL);
4677

4678
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4679
        return NULL;
4680 4681
    }

4682
    if (esxVI_LookupCurrentSnapshotTree(priv->primary, domain->uuid,
4683 4684
                                        &currentSnapshotTree,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4685
        return NULL;
4686 4687 4688 4689 4690 4691 4692 4693 4694 4695
    }

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

    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);

    return snapshot;
}


4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764
static int
esxDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *currentSnapshotTree = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

    /* Check that snapshot exists.  */
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

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

    ret = STREQ(snapshot->name, currentSnapshotTree->name);

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&currentSnapshotTree);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}


static int
esxDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

    /* Check that snapshot exists.  If so, there is no metadata.  */
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
                                    &snapshotTree, NULL,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    ret = 0;

cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    return ret;
}

4765 4766 4767 4768

static int
esxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4769
    int result = -1;
4770 4771 4772 4773 4774
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4775
    char *taskInfoErrorMessage = NULL;
4776

4777
    virCheckFlags(0, -1);
4778

4779
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4780
        return -1;
4781 4782
    }

4783
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4784 4785
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4786
                                    &snapshotTree, NULL,
4787
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4788
        goto cleanup;
4789 4790
    }

4791
    if (esxVI_RevertToSnapshot_Task(priv->primary, snapshotTree->snapshot, NULL,
4792
                                    &task) < 0 ||
4793
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4794
                                    esxVI_Occurrence_RequiredItem,
4795
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4796
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4797
        goto cleanup;
4798 4799 4800
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4801 4802 4803
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not revert to snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4804
        goto cleanup;
4805 4806
    }

M
Matthias Bolte 已提交
4807 4808
    result = 0;

4809 4810 4811
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4812
    VIR_FREE(taskInfoErrorMessage);
4813 4814 4815 4816 4817 4818 4819 4820 4821

    return result;
}



static int
esxDomainSnapshotDelete(virDomainSnapshotPtr snapshot, unsigned int flags)
{
M
Matthias Bolte 已提交
4822
    int result = -1;
4823 4824 4825 4826 4827 4828
    esxPrivate *priv = snapshot->domain->conn->privateData;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;
    esxVI_Boolean removeChildren = esxVI_Boolean_False;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4829
    char *taskInfoErrorMessage = NULL;
4830

4831 4832
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
4833

4834
    if (esxVI_EnsureSession(priv->primary) < 0) {
M
Matthias Bolte 已提交
4835
        return -1;
4836 4837 4838 4839 4840 4841
    }

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

4842
    if (esxVI_LookupRootSnapshotTreeList(priv->primary, snapshot->domain->uuid,
4843 4844
                                         &rootSnapshotList) < 0 ||
        esxVI_GetSnapshotTreeByName(rootSnapshotList, snapshot->name,
4845
                                    &snapshotTree, NULL,
4846
                                    esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
4847
        goto cleanup;
4848 4849
    }

4850 4851 4852 4853 4854 4855 4856
    /* ESX snapshots do not require any libvirt metadata, making this
     * flag trivial once we know we have a valid snapshot.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY) {
        result = 0;
        goto cleanup;
    }

4857
    if (esxVI_RemoveSnapshot_Task(priv->primary, snapshotTree->snapshot,
4858
                                  removeChildren, &task) < 0 ||
4859
        esxVI_WaitForTaskCompletion(priv->primary, task, snapshot->domain->uuid,
4860
                                    esxVI_Occurrence_RequiredItem,
4861
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4862
                                    &taskInfoErrorMessage) < 0) {
M
Matthias Bolte 已提交
4863
        goto cleanup;
4864 4865 4866
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4867 4868 4869
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not delete snapshot '%s': %s"), snapshot->name,
                       taskInfoErrorMessage);
M
Matthias Bolte 已提交
4870
        goto cleanup;
4871 4872
    }

M
Matthias Bolte 已提交
4873 4874
    result = 0;

4875 4876 4877
  cleanup:
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotList);
    esxVI_ManagedObjectReference_Free(&task);
4878
    VIR_FREE(taskInfoErrorMessage);
4879 4880 4881 4882 4883 4884

    return result;
}



4885
static int
4886
esxDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4887 4888 4889 4890 4891 4892 4893 4894
                             int nparams, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_VirtualMachineConfigSpec *spec = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
4895
    char *taskInfoErrorMessage = NULL;
4896 4897 4898
    int i;

    virCheckFlags(0, -1);
4899 4900 4901 4902 4903
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                       VIR_TYPED_PARAM_ULLONG,
                                       NULL) < 0)
        return -1;
4904 4905 4906 4907 4908 4909 4910

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

    if (esxVI_LookupVirtualMachineByUuidAndPrepareForTask
          (priv->primary, domain->uuid, NULL, &virtualMachine,
4911
           priv->parsedUri->autoAnswer) < 0 ||
4912 4913 4914 4915 4916 4917
        esxVI_VirtualMachineConfigSpec_Alloc(&spec) < 0 ||
        esxVI_ResourceAllocationInfo_Alloc(&spec->memoryAllocation) < 0) {
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
4918
        if (STREQ(params[i].field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
4919 4920 4921 4922 4923
            if (esxVI_Long_Alloc(&spec->memoryAllocation->reservation) < 0) {
                goto cleanup;
            }

            spec->memoryAllocation->reservation->value =
4924
              VIR_DIV_UP(params[i].value.ul, 1024); /* Scale from kilobytes to megabytes */
4925 4926 4927 4928 4929 4930 4931
        }
    }

    if (esxVI_ReconfigVM_Task(priv->primary, virtualMachine->obj, spec,
                              &task) < 0 ||
        esxVI_WaitForTaskCompletion(priv->primary, task, domain->uuid,
                                    esxVI_Occurrence_RequiredItem,
4932
                                    priv->parsedUri->autoAnswer, &taskInfoState,
4933
                                    &taskInfoErrorMessage) < 0) {
4934 4935 4936 4937
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
4938 4939 4940
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not change memory parameters: %s"),
                       taskInfoErrorMessage);
4941 4942 4943 4944 4945 4946 4947 4948 4949
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_VirtualMachineConfigSpec_Free(&spec);
    esxVI_ManagedObjectReference_Free(&task);
4950
    VIR_FREE(taskInfoErrorMessage);
4951 4952 4953 4954 4955 4956 4957

    return result;
}



static int
4958
esxDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params,
4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
                             int *nparams, unsigned int flags)
{
    int result = -1;
    esxPrivate *priv = domain->conn->privateData;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_Long *reservation = NULL;

    virCheckFlags(0, -1);

    if (*nparams == 0) {
        *nparams = 1; /* min_guarantee */
        return 0;
    }

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

    if (esxVI_String_AppendValueToList
          (&propertyNameList, "config.memoryAllocation.reservation") < 0 ||
        esxVI_LookupVirtualMachineByUuid(priv->primary, domain->uuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetLong(virtualMachine, "config.memoryAllocation.reservation",
                      &reservation, esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

4988 4989 4990 4991
    /* Scale from megabytes to kilobytes */
    if (virTypedParameterAssign(params, VIR_DOMAIN_MEMORY_MIN_GUARANTEE,
                                VIR_TYPED_PARAM_ULLONG,
                                reservation->value * 1024) < 0)
4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004
        goto cleanup;

    *nparams = 1;
    result = 0;

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

    return result;
}

5005 5006 5007 5008 5009 5010 5011 5012
#define MATCH(FLAG) (flags & (FLAG))
static int
esxListAllDomains(virConnectPtr conn,
                  virDomainPtr **domains,
                  unsigned int flags)
{
    int ret = -1;
    esxPrivate *priv = conn->privateData;
5013 5014
    bool needIdentity;
    bool needPowerState;
5015 5016 5017
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    size_t ndoms = 0;
5018
    esxVI_String *propertyNameList = NULL;
5019 5020
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
5021
    esxVI_AutoStartDefaults *autoStartDefaults = NULL;
5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038
    esxVI_VirtualMachinePowerState powerState;
    esxVI_AutoStartPowerInfo *powerInfoList = NULL;
    esxVI_AutoStartPowerInfo *powerInfo = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    char *name = NULL;
    int id;
    unsigned char uuid[VIR_UUID_BUFLEN];
    int count = 0;
    bool autostart;
    int state;

    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);

    /* check for flags that would produce empty output lists:
     * - persistence: all esx machines are persistent
     * - managed save: esx doesn't support managed save
     */
5039
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
         !MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE))) {
        if (domains &&
            VIR_ALLOC_N(*domains, 1) < 0)
            goto no_memory;

        ret = 0;
        goto cleanup;
    }

5051
    if (esxVI_EnsureSession(priv->primary) < 0)
5052 5053 5054 5055 5056
        return -1;

    /* check system default autostart value */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
        if (esxVI_LookupAutoStartDefaults(priv->primary,
5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077
                                          &autoStartDefaults) < 0) {
            goto cleanup;
        }

        if (autoStartDefaults->enabled == esxVI_Boolean_True) {
            if (esxVI_LookupAutoStartPowerInfoList(priv->primary,
                                                   &powerInfoList) < 0) {
                goto cleanup;
            }
        }
    }

    needIdentity = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT) ||
                   domains != NULL;

    if (needIdentity) {
        /* Request required data for esxVI_GetVirtualMachineIdentity */
        if (esxVI_String_AppendValueListToList(&propertyNameList,
                                               "configStatus\0"
                                               "name\0"
                                               "config.uuid\0") < 0) {
5078
            goto cleanup;
5079 5080 5081 5082 5083 5084
        }
    }

    needPowerState = MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) ||
                     MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) ||
                     domains != NULL;
5085

5086 5087 5088
    if (needPowerState) {
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "runtime.powerState") < 0) {
5089
            goto cleanup;
5090
        }
5091 5092
    }

5093
    if (esxVI_LookupVirtualMachineList(priv->primary, propertyNameList,
5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104
                                       &virtualMachineList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
            goto no_memory;
        ndoms = 1;
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
5105 5106
        if (needIdentity) {
            VIR_FREE(name);
5107

5108 5109 5110 5111 5112
            if (esxVI_GetVirtualMachineIdentity(virtualMachine, &id,
                                                &name, uuid) < 0) {
                goto cleanup;
            }
        }
5113

5114 5115 5116 5117 5118 5119
        if (needPowerState) {
            if (esxVI_GetVirtualMachinePowerState(virtualMachine,
                                                  &powerState) < 0) {
                goto cleanup;
            }
        }
5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130

        /* filter by active state */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) &&
            !((MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) &&
               powerState != esxVI_VirtualMachinePowerState_PoweredOff) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE) &&
               powerState == esxVI_VirtualMachinePowerState_PoweredOff)))
            continue;

        /* filter by snapshot existence */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
5131 5132
            esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5133 5134 5135 5136 5137 5138
            if (esxVI_LookupRootSnapshotTreeList(priv->primary, uuid,
                                                 &rootSnapshotTreeList) < 0) {
                goto cleanup;
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
5139
                   rootSnapshotTreeList != NULL) ||
5140
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
5141
                   rootSnapshotTreeList == NULL)))
5142 5143 5144 5145 5146 5147 5148
                continue;
        }

        /* filter by autostart */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART)) {
            autostart = false;

5149 5150 5151 5152 5153 5154
            if (autoStartDefaults->enabled == esxVI_Boolean_True) {
                for (powerInfo = powerInfoList; powerInfo != NULL;
                     powerInfo = powerInfo->_next) {
                    if (STREQ(powerInfo->key->value, virtualMachine->obj->value)) {
                        if (STRCASEEQ(powerInfo->startAction, "powerOn"))
                            autostart = true;
5155

5156 5157
                        break;
                    }
5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170
                }
            }

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) &&
                   autostart) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART) &&
                   !autostart)))
                continue;
        }

        /* filter by domain state */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE)) {
            state = esxVI_VirtualMachinePowerState_ConvertToLibvirt(powerState);
5171

5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190
            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
                   state == VIR_DOMAIN_RUNNING) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
                   state == VIR_DOMAIN_PAUSED) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
                   state == VIR_DOMAIN_SHUTOFF) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
                   (state != VIR_DOMAIN_RUNNING &&
                    state != VIR_DOMAIN_PAUSED &&
                    state != VIR_DOMAIN_SHUTOFF))))
                continue;
        }

        /* just count the machines */
        if (!doms) {
            count++;
            continue;
        }

5191
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
5192 5193
            goto no_memory;

5194 5195 5196
        if (!(dom = virGetDomain(conn, name, uuid)))
            goto cleanup;

5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213
        /* Only running/suspended virtual machines have an ID != -1 */
        if (powerState != esxVI_VirtualMachinePowerState_PoweredOff)
            dom->id = id;
        else
            dom->id = -1;

        doms[count++] = dom;
    }

    if (doms)
        *domains = doms;
    doms = NULL;
    ret = count;

cleanup:
    if (doms) {
        for (id = 0; id < count; id++) {
5214
            virDomainFree(doms[id]);
5215
        }
5216 5217

        VIR_FREE(doms);
5218
    }
5219

5220
    VIR_FREE(name);
5221 5222
    esxVI_AutoStartDefaults_Free(&autoStartDefaults);
    esxVI_AutoStartPowerInfo_Free(&powerInfoList);
5223 5224
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
5225 5226
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

5227 5228 5229 5230 5231 5232 5233
    return ret;

no_memory:
    virReportOOMError();
    goto cleanup;
}
#undef MATCH
5234 5235


5236
static virDriver esxDriver = {
5237 5238
    .no = VIR_DRV_ESX,
    .name = "ESX",
5239 5240 5241 5242 5243 5244 5245 5246 5247 5248
    .open = esxOpen, /* 0.7.0 */
    .close = esxClose, /* 0.7.0 */
    .supports_feature = esxSupportsFeature, /* 0.7.0 */
    .type = esxGetType, /* 0.7.0 */
    .version = esxGetVersion, /* 0.7.0 */
    .getHostname = esxGetHostname, /* 0.7.0 */
    .nodeGetInfo = esxNodeGetInfo, /* 0.7.0 */
    .getCapabilities = esxGetCapabilities, /* 0.7.1 */
    .listDomains = esxListDomains, /* 0.7.0 */
    .numOfDomains = esxNumberOfDomains, /* 0.7.0 */
5249
    .listAllDomains = esxListAllDomains, /* 0.10.2 */
5250 5251 5252 5253 5254 5255
    .domainLookupByID = esxDomainLookupByID, /* 0.7.0 */
    .domainLookupByUUID = esxDomainLookupByUUID, /* 0.7.0 */
    .domainLookupByName = esxDomainLookupByName, /* 0.7.0 */
    .domainSuspend = esxDomainSuspend, /* 0.7.0 */
    .domainResume = esxDomainResume, /* 0.7.0 */
    .domainShutdown = esxDomainShutdown, /* 0.7.0 */
5256
    .domainShutdownFlags = esxDomainShutdownFlags, /* 0.9.10 */
5257 5258
    .domainReboot = esxDomainReboot, /* 0.7.0 */
    .domainDestroy = esxDomainDestroy, /* 0.7.0 */
5259
    .domainDestroyFlags = esxDomainDestroyFlags, /* 0.9.4 */
5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280
    .domainGetOSType = esxDomainGetOSType, /* 0.7.0 */
    .domainGetMaxMemory = esxDomainGetMaxMemory, /* 0.7.0 */
    .domainSetMaxMemory = esxDomainSetMaxMemory, /* 0.7.0 */
    .domainSetMemory = esxDomainSetMemory, /* 0.7.0 */
    .domainSetMemoryParameters = esxDomainSetMemoryParameters, /* 0.8.6 */
    .domainGetMemoryParameters = esxDomainGetMemoryParameters, /* 0.8.6 */
    .domainGetInfo = esxDomainGetInfo, /* 0.7.0 */
    .domainGetState = esxDomainGetState, /* 0.9.2 */
    .domainSetVcpus = esxDomainSetVcpus, /* 0.7.0 */
    .domainSetVcpusFlags = esxDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = esxDomainGetVcpusFlags, /* 0.8.5 */
    .domainGetMaxVcpus = esxDomainGetMaxVcpus, /* 0.7.0 */
    .domainGetXMLDesc = esxDomainGetXMLDesc, /* 0.7.0 */
    .domainXMLFromNative = esxDomainXMLFromNative, /* 0.7.0 */
    .domainXMLToNative = esxDomainXMLToNative, /* 0.7.2 */
    .listDefinedDomains = esxListDefinedDomains, /* 0.7.0 */
    .numOfDefinedDomains = esxNumberOfDefinedDomains, /* 0.7.0 */
    .domainCreate = esxDomainCreate, /* 0.7.0 */
    .domainCreateWithFlags = esxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = esxDomainDefineXML, /* 0.7.2 */
    .domainUndefine = esxDomainUndefine, /* 0.7.1 */
5281
    .domainUndefineFlags = esxDomainUndefineFlags, /* 0.9.4 */
5282 5283 5284 5285
    .domainGetAutostart = esxDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = esxDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = esxDomainGetSchedulerType, /* 0.7.0 */
    .domainGetSchedulerParameters = esxDomainGetSchedulerParameters, /* 0.7.0 */
5286
    .domainGetSchedulerParametersFlags = esxDomainGetSchedulerParametersFlags, /* 0.9.2 */
5287
    .domainSetSchedulerParameters = esxDomainSetSchedulerParameters, /* 0.7.0 */
5288
    .domainSetSchedulerParametersFlags = esxDomainSetSchedulerParametersFlags, /* 0.9.2 */
5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301
    .domainMigratePrepare = esxDomainMigratePrepare, /* 0.7.0 */
    .domainMigratePerform = esxDomainMigratePerform, /* 0.7.0 */
    .domainMigrateFinish = esxDomainMigrateFinish, /* 0.7.0 */
    .nodeGetFreeMemory = esxNodeGetFreeMemory, /* 0.7.2 */
    .isEncrypted = esxIsEncrypted, /* 0.7.3 */
    .isSecure = esxIsSecure, /* 0.7.3 */
    .domainIsActive = esxDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = esxDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = esxDomainIsUpdated, /* 0.8.6 */
    .domainSnapshotCreateXML = esxDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = esxDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = esxDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = esxDomainSnapshotListNames, /* 0.8.0 */
5302 5303
    .domainSnapshotNumChildren = esxDomainSnapshotNumChildren, /* 0.9.7 */
    .domainSnapshotListChildrenNames = esxDomainSnapshotListChildrenNames, /* 0.9.7 */
5304 5305
    .domainSnapshotLookupByName = esxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = esxDomainHasCurrentSnapshot, /* 0.8.0 */
E
Eric Blake 已提交
5306
    .domainSnapshotGetParent = esxDomainSnapshotGetParent, /* 0.9.7 */
5307 5308
    .domainSnapshotCurrent = esxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = esxDomainRevertToSnapshot, /* 0.8.0 */
5309 5310
    .domainSnapshotIsCurrent = esxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = esxDomainSnapshotHasMetadata, /* 0.9.13 */
5311
    .domainSnapshotDelete = esxDomainSnapshotDelete, /* 0.8.0 */
5312
    .isAlive = esxIsAlive, /* 0.9.8 */
5313 5314 5315 5316 5317 5318 5319
};



int
esxRegister(void)
{
5320 5321 5322 5323 5324
    if (virRegisterDriver(&esxDriver) < 0 ||
        esxInterfaceRegister() < 0 ||
        esxNetworkRegister() < 0 ||
        esxStorageRegister() < 0 ||
        esxDeviceRegister() < 0 ||
M
Matthias Bolte 已提交
5325 5326
        esxSecretRegister() < 0 ||
        esxNWFilterRegister() < 0) {
5327 5328
        return -1;
    }
5329 5330 5331

    return 0;
}