esx_vi.c 124.0 KB
Newer Older
1 2 3 4

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

#include <config.h>

#include <libxml/parser.h>
#include <libxml/xpathInternals.h>

#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "util.h"
#include "uuid.h"
34
#include "vmx.h"
35
#include "xml.h"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"

#define VIR_FROM_THIS VIR_FROM_ESX



#define ESX_VI__SOAP__RESPONSE_XPATH(_type)                                   \
    ((char *)"/soapenv:Envelope/soapenv:Body/"                                \
               "vim:"_type"Response/vim:returnval")



#define ESX_VI__TEMPLATE__ALLOC(_type)                                        \
    int                                                                       \
52
    esxVI_##_type##_Alloc(esxVI_##_type **ptrptr)                             \
53
    {                                                                         \
54
        return esxVI_Alloc((void **)ptrptr, sizeof(esxVI_##_type));           \
55 56
    }

57 58


59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
#define ESX_VI__TEMPLATE__FREE(_type, _body)                                  \
    void                                                                      \
    esxVI_##_type##_Free(esxVI_##_type **ptrptr)                              \
    {                                                                         \
        esxVI_##_type *item = NULL;                                           \
                                                                              \
        if (ptrptr == NULL || *ptrptr == NULL) {                              \
            return;                                                           \
        }                                                                     \
                                                                              \
        item = *ptrptr;                                                       \
                                                                              \
        _body                                                                 \
                                                                              \
        VIR_FREE(*ptrptr);                                                    \
    }



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Context
 */

/* esxVI_Context_Alloc */
ESX_VI__TEMPLATE__ALLOC(Context);

/* esxVI_Context_Free */
ESX_VI__TEMPLATE__FREE(Context,
{
    VIR_FREE(item->url);
M
Matthias Bolte 已提交
89
    VIR_FREE(item->ipAddress);
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

    if (item->curl_handle != NULL) {
        curl_easy_cleanup(item->curl_handle);
    }

    if (item->curl_headers != NULL) {
        curl_slist_free_all(item->curl_headers);
    }

    virMutexDestroy(&item->curl_lock);

    VIR_FREE(item->username);
    VIR_FREE(item->password);
    esxVI_ServiceContent_Free(&item->service);
    esxVI_UserSession_Free(&item->session);
105 106 107
    esxVI_Datacenter_Free(&item->datacenter);
    esxVI_ComputeResource_Free(&item->computeResource);
    esxVI_HostSystem_Free(&item->hostSystem);
108 109 110 111 112 113
    esxVI_SelectionSpec_Free(&item->selectSet_folderToChildEntity);
    esxVI_SelectionSpec_Free(&item->selectSet_hostSystemToParent);
    esxVI_SelectionSpec_Free(&item->selectSet_hostSystemToVm);
    esxVI_SelectionSpec_Free(&item->selectSet_hostSystemToDatastore);
    esxVI_SelectionSpec_Free(&item->selectSet_computeResourceToHost);
    esxVI_SelectionSpec_Free(&item->selectSet_computeResourceToParentToParent);
114 115 116
});

static size_t
M
Matthias Bolte 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
esxVI_CURL_ReadString(char *data, size_t size, size_t nmemb, void *ptrptr)
{
    const char *content = *(const char **)ptrptr;
    size_t available = 0;
    size_t requested = size * nmemb;

    if (content == NULL) {
        return 0;
    }

    available = strlen(content);

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

    if (requested > available) {
        requested = available;
    }

    memcpy(data, content, requested);

    *(const char **)ptrptr = content + requested;

    return requested;
}

static size_t
esxVI_CURL_WriteBuffer(char *data, size_t size, size_t nmemb, void *buffer)
146 147 148 149 150 151 152 153 154 155 156 157 158 159
{
    if (buffer != NULL) {
        virBufferAdd((virBufferPtr) buffer, data, size * nmemb);

        return size * nmemb;
    }

    return 0;
}

#define ESX_VI__CURL__ENABLE_DEBUG_OUTPUT 0

#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
static int
M
Matthias Bolte 已提交
160 161
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
                 char *info, size_t size, void *data ATTRIBUTE_UNUSED)
162
{
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    char *buffer = NULL;

    /*
     * The libcurl documentation says:
     *
     *    The data pointed to by the char * passed to this function WILL NOT
     *    be zero terminated, but will be exactly of the size as told by the
     *    size_t argument.
     *
     * To handle this properly in order to pass the info string to VIR_DEBUG
     * a zero terminated copy of the info string has to be allocated.
     */
    if (VIR_ALLOC_N(buffer, size + 1) < 0) {
        return 0;
    }

    if (virStrncpy(buffer, info, size, size + 1) == NULL) {
        VIR_FREE(buffer);
        return 0;
    }

184 185
    switch (type) {
      case CURLINFO_TEXT:
186 187 188 189 190
        if (size > 0 && buffer[size - 1] == '\n') {
            buffer[size - 1] = '\0';
        }

        VIR_DEBUG("CURLINFO_TEXT [[[[%s]]]]", buffer);
191 192 193
        break;

      case CURLINFO_HEADER_IN:
194
        VIR_DEBUG("CURLINFO_HEADER_IN [[[[%s]]]]", buffer);
195 196 197
        break;

      case CURLINFO_HEADER_OUT:
198
        VIR_DEBUG("CURLINFO_HEADER_OUT [[[[%s]]]]", buffer);
199 200 201
        break;

      case CURLINFO_DATA_IN:
202
        VIR_DEBUG("CURLINFO_DATA_IN [[[[%s]]]]", buffer);
203 204 205
        break;

      case CURLINFO_DATA_OUT:
206
        VIR_DEBUG("CURLINFO_DATA_OUT [[[[%s]]]]", buffer);
207 208 209 210 211 212 213
        break;

      default:
        VIR_DEBUG0("unknown");
        break;
    }

214 215
    VIR_FREE(buffer);

216 217 218 219
    return 0;
}
#endif

220
static int
221
esxVI_CURL_Perform(esxVI_Context *ctx, const char *url)
222 223 224 225 226 227 228 229 230 231
{
    CURLcode errorCode;
    long responseCode = 0;
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
    const char *redirectUrl = NULL;
#endif

    errorCode = curl_easy_perform(ctx->curl_handle);

    if (errorCode != CURLE_OK) {
232
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
233
                     _("curl_easy_perform() returned an error: %s (%d) : %s"),
234
                     curl_easy_strerror(errorCode), errorCode, ctx->curl_error);
235 236 237 238 239 240 241
        return -1;
    }

    errorCode = curl_easy_getinfo(ctx->curl_handle, CURLINFO_RESPONSE_CODE,
                                  &responseCode);

    if (errorCode != CURLE_OK) {
242
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
243 244
                     _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned an "
                       "error: %s (%d) : %s"), curl_easy_strerror(errorCode),
245
                     errorCode, ctx->curl_error);
246 247 248 249
        return -1;
    }

    if (responseCode < 0) {
250 251 252
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned a "
                       "negative response code"));
253 254 255 256 257 258 259 260 261
        return -1;
    }

    if (responseCode == 301) {
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
        errorCode = curl_easy_getinfo(ctx->curl_handle, CURLINFO_REDIRECT_URL,
                                      &redirectUrl);

        if (errorCode != CURLE_OK) {
262
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
263 264 265
                         _("curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
                           "an error: %s (%d) : %s"),
                         curl_easy_strerror(errorCode),
266
                         errorCode, ctx->curl_error);
267
        } else {
268
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
269
                         _("The server redirects from '%s' to '%s'"), url,
270 271 272
                         redirectUrl);
        }
#else
273
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
274
                     _("The server redirects from '%s'"), url);
275 276 277 278 279 280 281 282
#endif

        return -1;
    }

    return responseCode;
}

283
int
284
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
M
Matthias Bolte 已提交
285
                      const char *ipAddress, const char *username,
M
Matthias Bolte 已提交
286
                      const char *password, esxUtil_ParsedUri *parsedUri)
287
{
M
Matthias Bolte 已提交
288 289 290
    if (ctx == NULL || url == NULL || ipAddress == NULL || username == NULL ||
        password == NULL || ctx->url != NULL || ctx->service != NULL ||
        ctx->curl_handle != NULL || ctx->curl_headers != NULL) {
291
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
292
        return -1;
293 294
    }

295 296
    if (esxVI_String_DeepCopyValue(&ctx->url, url) < 0 ||
        esxVI_String_DeepCopyValue(&ctx->ipAddress, ipAddress) < 0) {
297
        return -1;
298 299 300 301 302
    }

    ctx->curl_handle = curl_easy_init();

    if (ctx->curl_handle == NULL) {
303 304
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL"));
305
        return -1;
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    }

    ctx->curl_headers = curl_slist_append(ctx->curl_headers, "Content-Type: "
                                          "text/xml; charset=UTF-8");

    /*
     * Add a dummy expect header to stop CURL from waiting for a response code
     * 100 (Continue) from the server before continuing the POST operation.
     * Waiting for this response would slowdown each communication with the
     * server by approx. 2 sec, because the server doesn't send the expected
     * 100 (Continue) response and the wait times out resulting in wasting
     * approx. 2 sec per POST operation.
     */
    ctx->curl_headers = curl_slist_append(ctx->curl_headers,
                                          "Expect: nothing");

    if (ctx->curl_headers == NULL) {
323 324
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not build CURL header list"));
325
        return -1;
326 327 328 329 330
    }

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, ctx->url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_USERAGENT, "libvirt-esx");
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HEADER, 0);
331
    curl_easy_setopt(ctx->curl_handle, CURLOPT_FOLLOWLOCATION, 0);
M
Matthias Bolte 已提交
332
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYPEER,
M
Matthias Bolte 已提交
333
                     parsedUri->noVerify ? 0 : 1);
M
Matthias Bolte 已提交
334
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYHOST,
M
Matthias Bolte 已提交
335
                     parsedUri->noVerify ? 0 : 2);
336 337
    curl_easy_setopt(ctx->curl_handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPHEADER, ctx->curl_headers);
M
Matthias Bolte 已提交
338 339
    curl_easy_setopt(ctx->curl_handle, CURLOPT_READFUNCTION,
                     esxVI_CURL_ReadString);
340
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
341
                     esxVI_CURL_WriteBuffer);
342 343
    curl_easy_setopt(ctx->curl_handle, CURLOPT_ERRORBUFFER,
                     ctx->curl_error);
344
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
345 346
    curl_easy_setopt(ctx->curl_handle, CURLOPT_DEBUGFUNCTION, esxVI_CURL_Debug);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 1);
347 348
#endif

M
Matthias Bolte 已提交
349
    if (parsedUri->proxy) {
M
Matthias Bolte 已提交
350
        curl_easy_setopt(ctx->curl_handle, CURLOPT_PROXY,
M
Matthias Bolte 已提交
351
                         parsedUri->proxy_hostname);
M
Matthias Bolte 已提交
352
        curl_easy_setopt(ctx->curl_handle, CURLOPT_PROXYTYPE,
M
Matthias Bolte 已提交
353
                         parsedUri->proxy_type);
M
Matthias Bolte 已提交
354
        curl_easy_setopt(ctx->curl_handle, CURLOPT_PROXYPORT,
M
Matthias Bolte 已提交
355
                         parsedUri->proxy_port);
M
Matthias Bolte 已提交
356 357
    }

358
    if (virMutexInit(&ctx->curl_lock) < 0) {
359 360
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL mutex"));
361
        return -1;
362 363 364 365 366 367
    }

    ctx->username = strdup(username);
    ctx->password = strdup(password);

    if (ctx->username == NULL || ctx->password == NULL) {
368
        virReportOOMError();
369
        return -1;
370 371
    }

372
    if (esxVI_RetrieveServiceContent(ctx, &ctx->service) < 0) {
373
        return -1;
374 375
    }

376 377 378
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
379
            ctx->apiVersion = esxVI_APIVersion_25;
380
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
381
            ctx->apiVersion = esxVI_APIVersion_40;
M
Matthias Bolte 已提交
382 383 384 385 386 387 388
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.1")) {
            ctx->apiVersion = esxVI_APIVersion_41;
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.")) {
            ctx->apiVersion = esxVI_APIVersion_4x;

            VIR_WARN("Found untested VI API major/minor version '%s'",
                     ctx->service->about->apiVersion);
389
        } else {
390
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
391
                         _("Expecting VI API major/minor version '2.5' or '4.x' "
392
                           "but found '%s'"), ctx->service->about->apiVersion);
393
            return -1;
394
        }
395

396 397 398 399
        if (STREQ(ctx->service->about->productLineId, "gsx")) {
            if (STRPREFIX(ctx->service->about->version, "2.0")) {
                ctx->productVersion = esxVI_ProductVersion_GSX20;
            } else {
400
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
401 402
                             _("Expecting GSX major/minor version '2.0' but "
                               "found '%s'"), ctx->service->about->version);
403
                return -1;
404 405 406 407 408 409 410
            }
        } else if (STREQ(ctx->service->about->productLineId, "esx") ||
                   STREQ(ctx->service->about->productLineId, "embeddedEsx")) {
            if (STRPREFIX(ctx->service->about->version, "3.5")) {
                ctx->productVersion = esxVI_ProductVersion_ESX35;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_ESX40;
M
Matthias Bolte 已提交
411 412 413 414 415 416 417
            } else if (STRPREFIX(ctx->service->about->version, "4.1")) {
                ctx->productVersion = esxVI_ProductVersion_ESX41;
            } else if (STRPREFIX(ctx->service->about->version, "4.")) {
                ctx->productVersion = esxVI_ProductVersion_ESX4x;

                VIR_WARN("Found untested ESX major/minor version '%s'",
                         ctx->service->about->version);
418
            } else {
419
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
420
                             _("Expecting ESX major/minor version '3.5' or "
M
Matthias Bolte 已提交
421
                               "'4.x' but found '%s'"),
422
                             ctx->service->about->version);
423
                return -1;
424 425 426 427 428 429
            }
        } else if (STREQ(ctx->service->about->productLineId, "vpx")) {
            if (STRPREFIX(ctx->service->about->version, "2.5")) {
                ctx->productVersion = esxVI_ProductVersion_VPX25;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_VPX40;
M
Matthias Bolte 已提交
430 431 432 433 434 435 436
            } else if (STRPREFIX(ctx->service->about->version, "4.1")) {
                ctx->productVersion = esxVI_ProductVersion_VPX41;
            } else if (STRPREFIX(ctx->service->about->version, "4.")) {
                ctx->productVersion = esxVI_ProductVersion_VPX4x;

                VIR_WARN("Found untested VPX major/minor version '%s'",
                         ctx->service->about->version);
437
            } else {
438
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
439
                             _("Expecting VPX major/minor version '2.5' or '4.x' "
440
                               "but found '%s'"), ctx->service->about->version);
441
                return -1;
442
            }
443
        } else {
444
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
445 446
                         _("Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                           "or 'vpx' but found '%s'"),
447
                         ctx->service->about->productLineId);
448
            return -1;
449 450
        }
    } else {
451
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
452 453
                     _("Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                       "but found '%s'"), ctx->service->about->apiType);
454
        return -1;
455 456
    }

457 458 459 460 461 462 463 464 465 466 467
    if (ctx->productVersion & esxVI_ProductVersion_ESX) {
        /*
         * FIXME: Actually this should be detected by really calling
         * QueryVirtualDiskUuid and checking if a NotImplemented fault is
         * returned. But currently we don't deserialized the details of a
         * possbile fault and therefore we don't know if the fault was a
         * NotImplemented fault or not.
         */
        ctx->hasQueryVirtualDiskUuid = true;
    }

468 469 470 471
    if (ctx->productVersion & esxVI_ProductVersion_VPX) {
        ctx->hasSessionIsActive = true;
    }

472
    if (esxVI_Login(ctx, username, password, NULL, &ctx->session) < 0 ||
473
        esxVI_BuildSelectSetCollection(ctx) < 0) {
474
        return -1;
475 476
    }

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    return 0;
}

int
esxVI_Context_LookupObjectsByPath(esxVI_Context *ctx,
                                  esxUtil_ParsedUri *parsedUri)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    char *name = NULL;
    esxVI_ObjectContent *datacenterList = NULL;
    esxVI_ObjectContent *datacenter = NULL;
    esxVI_ObjectContent *computeResourceList = NULL;
    esxVI_ObjectContent *computeResource = NULL;
    char *hostSystemName = NULL;
    esxVI_ObjectContent *hostSystemList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;

    /* Lookup Datacenter */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "name\0"
                                           "vmFolder\0"
                                           "hostFolder\0") < 0 ||
        esxVI_LookupObjectContentByType(ctx, ctx->service->rootFolder,
501
                                        "Datacenter", propertyNameList,
502 503
                                        &datacenterList,
                                        esxVI_Occurrence_RequiredList) < 0) {
M
Matthias Bolte 已提交
504
        goto cleanup;
505 506
    }

507 508 509 510
    if (parsedUri->path_datacenter != NULL) {
        for (datacenter = datacenterList; datacenter != NULL;
             datacenter = datacenter->_next) {
            name = NULL;
511

512 513
            if (esxVI_GetStringValue(datacenter, "name", &name,
                                     esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
514
                goto cleanup;
515
            }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

            if (STREQ(name, parsedUri->path_datacenter)) {
                break;
            }
        }

        if (datacenter == NULL) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Could not find datacenter '%s'"),
                         parsedUri->path_datacenter);
            goto cleanup;
        }
    } else {
        datacenter = datacenterList;
    }

    if (esxVI_Datacenter_CastFromObjectContent(datacenter,
                                               &ctx->datacenter) < 0) {
        goto cleanup;
    }

537
    /* Lookup (Cluster)ComputeResource */
538 539 540 541 542 543 544 545
    esxVI_String_Free(&propertyNameList);

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "name\0"
                                           "host\0"
                                           "resourcePool\0") < 0 ||
        esxVI_LookupObjectContentByType(ctx, ctx->datacenter->hostFolder,
                                        "ComputeResource", propertyNameList,
546 547
                                        &computeResourceList,
                                        esxVI_Occurrence_RequiredList) < 0) {
548 549 550 551 552 553 554 555 556 557
        goto cleanup;
    }

    if (parsedUri->path_computeResource != NULL) {
        for (computeResource = computeResourceList; computeResource != NULL;
             computeResource = computeResource->_next) {
            name = NULL;

            if (esxVI_GetStringValue(computeResource, "name", &name,
                                     esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
558
                goto cleanup;
559
            }
560 561 562 563

            if (STREQ(name, parsedUri->path_computeResource)) {
                break;
            }
564
        }
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

        if (computeResource == NULL) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Could not find compute resource '%s'"),
                         parsedUri->path_computeResource);
            goto cleanup;
        }
    } else {
        computeResource = computeResourceList;
    }

    if (esxVI_ComputeResource_CastFromObjectContent(computeResource,
                                                    &ctx->computeResource) < 0) {
        goto cleanup;
    }

    if (ctx->computeResource->resourcePool == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve resource pool"));
        goto cleanup;
    }

    /* Lookup HostSystem */
    if (parsedUri->path_hostSystem == NULL &&
        STREQ(ctx->computeResource->_reference->type,
              "ClusterComputeResource")) {
        ESX_VI_ERROR(VIR_ERR_INVALID_ARG, "%s",
                     _("Path has to specify the host system"));
        goto cleanup;
594 595
    }

596 597 598
    esxVI_String_Free(&propertyNameList);

    if (esxVI_String_AppendValueListToList(&propertyNameList,
599 600
                                           "name\0"
                                           "configManager\0") < 0 ||
601 602
        esxVI_LookupObjectContentByType(ctx, ctx->computeResource->_reference,
                                        "HostSystem", propertyNameList,
603 604
                                        &hostSystemList,
                                        esxVI_Occurrence_RequiredList) < 0) {
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
        goto cleanup;
    }

    if (parsedUri->path_hostSystem != NULL ||
        (parsedUri->path_computeResource != NULL &&
         parsedUri->path_hostSystem == NULL)) {
        if (parsedUri->path_hostSystem != NULL) {
            hostSystemName = parsedUri->path_hostSystem;
        } else {
            hostSystemName = parsedUri->path_computeResource;
        }

        for (hostSystem = hostSystemList; hostSystem != NULL;
             hostSystem = hostSystem->_next) {
            name = NULL;

            if (esxVI_GetStringValue(hostSystem, "name", &name,
                                     esxVI_Occurrence_RequiredItem) < 0) {
                goto cleanup;
            }

            if (STREQ(name, hostSystemName)) {
                break;
            }
        }

        if (hostSystem == NULL) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Could not find host system '%s'"), hostSystemName);
            goto cleanup;
        }
    } else {
        hostSystem = hostSystemList;
    }

    if (esxVI_HostSystem_CastFromObjectContent(hostSystem,
                                               &ctx->hostSystem) < 0) {
M
Matthias Bolte 已提交
642
        goto cleanup;
643 644
    }

M
Matthias Bolte 已提交
645 646
    result = 0;

647 648 649
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datacenterList);
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
    esxVI_ObjectContent_Free(&computeResourceList);
    esxVI_ObjectContent_Free(&hostSystemList);

    return result;
}

int
esxVI_Context_LookupObjectsByHostSystemIp(esxVI_Context *ctx,
                                          const char *hostSystemIpAddress)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_ObjectContent *computeResource = NULL;
    esxVI_ObjectContent *datacenter = NULL;

    /* Lookup HostSystem */
    if (esxVI_String_AppendValueListToList(&propertyNameList,
669 670
                                           "name\0"
                                           "configManager\0") < 0 ||
671 672 673 674
        esxVI_FindByIp(ctx, NULL, hostSystemIpAddress, esxVI_Boolean_False,
                       &managedObjectReference) < 0 ||
        esxVI_LookupObjectContentByType(ctx, managedObjectReference,
                                        "HostSystem", propertyNameList,
675 676 677
                                        &hostSystem,
                                        esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_HostSystem_CastFromObjectContent(hostSystem,
678 679 680 681
                                               &ctx->hostSystem) < 0) {
        goto cleanup;
    }

682
    /* Lookup (Cluster)ComputeResource */
683 684 685 686 687 688 689 690
    esxVI_String_Free(&propertyNameList);

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "name\0"
                                           "host\0"
                                           "resourcePool\0") < 0 ||
        esxVI_LookupObjectContentByType(ctx, hostSystem->obj,
                                        "ComputeResource", propertyNameList,
691 692 693
                                        &computeResource,
                                        esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_ComputeResource_CastFromObjectContent(computeResource,
694 695 696 697 698 699 700 701 702 703 704 705 706
                                                    &ctx->computeResource) < 0) {
        goto cleanup;
    }

    /* Lookup Datacenter */
    esxVI_String_Free(&propertyNameList);

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "name\0"
                                           "vmFolder\0"
                                           "hostFolder\0") < 0 ||
        esxVI_LookupObjectContentByType(ctx, computeResource->obj,
                                        "Datacenter", propertyNameList,
707 708 709
                                        &datacenter,
                                        esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_Datacenter_CastFromObjectContent(datacenter,
710 711 712 713 714 715 716 717 718 719 720 721
                                               &ctx->datacenter) < 0) {
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_ObjectContent_Free(&computeResource);
    esxVI_ObjectContent_Free(&datacenter);
722 723 724 725 726

    return result;
}

int
727
esxVI_Context_DownloadFile(esxVI_Context *ctx, const char *url, char **content)
728 729
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
730
    int responseCode = 0;
731 732

    if (content == NULL || *content != NULL) {
733
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
734
        return -1;
735 736 737 738 739 740
    }

    virMutexLock(&ctx->curl_lock);

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEDATA, &buffer);
M
Matthias Bolte 已提交
741
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
742 743
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPGET, 1);

744
    responseCode = esxVI_CURL_Perform(ctx, url);
745

746
    virMutexUnlock(&ctx->curl_lock);
747

748
    if (responseCode < 0) {
M
Matthias Bolte 已提交
749
        goto cleanup;
750
    } else if (responseCode != 200) {
751
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
752
                     _("HTTP response code %d for download from '%s'"),
753
                     responseCode, url);
M
Matthias Bolte 已提交
754
        goto cleanup;
755 756 757
    }

    if (virBufferError(&buffer)) {
758
        virReportOOMError();
M
Matthias Bolte 已提交
759
        goto cleanup;
760 761 762 763
    }

    *content = virBufferContentAndReset(&buffer);

M
Matthias Bolte 已提交
764 765 766 767 768
  cleanup:
    if (*content == NULL) {
        virBufferFreeAndReset(&buffer);
        return -1;
    }
769

M
Matthias Bolte 已提交
770
    return 0;
771 772
}

M
Matthias Bolte 已提交
773
int
774 775
esxVI_Context_UploadFile(esxVI_Context *ctx, const char *url,
                         const char *content)
M
Matthias Bolte 已提交
776
{
777
    int responseCode = 0;
M
Matthias Bolte 已提交
778 779

    if (content == NULL) {
780
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
781 782 783 784 785 786 787 788 789 790
        return -1;
    }

    virMutexLock(&ctx->curl_lock);

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_READDATA, &content);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 1);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_INFILESIZE, strlen(content));

791
    responseCode = esxVI_CURL_Perform(ctx, url);
M
Matthias Bolte 已提交
792 793 794

    virMutexUnlock(&ctx->curl_lock);

795 796 797
    if (responseCode < 0) {
        return -1;
    } else if (responseCode != 200 && responseCode != 201) {
798
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
799
                     _("HTTP response code %d for upload to '%s'"),
800
                     responseCode, url);
M
Matthias Bolte 已提交
801 802 803 804 805 806
        return -1;
    }

    return 0;
}

807
int
808 809 810
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
811
{
M
Matthias Bolte 已提交
812
    int result = -1;
813 814
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
815 816 817
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
818

819
    if (request == NULL || response == NULL || *response != NULL) {
820
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
821
        return -1;
822 823
    }

824
    if (esxVI_Response_Alloc(response) < 0) {
M
Matthias Bolte 已提交
825
        return -1;
826 827 828 829 830 831
    }

    virMutexLock(&ctx->curl_lock);

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, ctx->url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEDATA, &buffer);
M
Matthias Bolte 已提交
832
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
833 834
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDSIZE, strlen(request));
835

836
    (*response)->responseCode = esxVI_CURL_Perform(ctx, ctx->url);
837

838
    virMutexUnlock(&ctx->curl_lock);
839

840
    if ((*response)->responseCode < 0) {
M
Matthias Bolte 已提交
841
        goto cleanup;
842 843 844
    }

    if (virBufferError(&buffer)) {
845
        virReportOOMError();
M
Matthias Bolte 已提交
846
        goto cleanup;
847 848
    }

849
    (*response)->content = virBufferContentAndReset(&buffer);
850

851
    if ((*response)->responseCode == 500 || (*response)->responseCode == 200) {
852 853
        (*response)->document = xmlReadDoc(BAD_CAST (*response)->content, "",
                                           NULL, XML_PARSE_NONET);
854

855
        if ((*response)->document == NULL) {
856
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
857
                         _("Response for call to '%s' could not be parsed"),
858
                         methodName);
M
Matthias Bolte 已提交
859
            goto cleanup;
860 861
        }

862
        if (xmlDocGetRootElement((*response)->document) == NULL) {
863
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
864
                         _("Response for call to '%s' is an empty XML document"),
865
                         methodName);
M
Matthias Bolte 已提交
866
            goto cleanup;
867 868
        }

869
        xpathContext = xmlXPathNewContext((*response)->document);
870

871
        if (xpathContext == NULL) {
872 873
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not create XPath context"));
M
Matthias Bolte 已提交
874
            goto cleanup;
875 876
        }

877
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
878
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
879
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
880

881 882
        if ((*response)->responseCode == 500) {
            (*response)->node =
883
              virXPathNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault",
884
                           xpathContext);
885

886
            if ((*response)->node == NULL) {
887
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
888 889
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, XPath evaluation failed"),
890
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
891
                goto cleanup;
892 893
            }

894 895
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
896 897
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, deserialization failed"),
898
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
899
                goto cleanup;
900 901
            }

902
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
903 904
                         _("HTTP response code %d for call to '%s'. "
                           "Fault: %s - %s"), (*response)->responseCode,
905
                         methodName, fault->faultcode, fault->faultstring);
906 907 908 909 910 911

            /* FIXME: Dump raw response until detail part gets deserialized */
            VIR_DEBUG("HTTP response code %d for call to '%s' [[[[%s]]]]",
                      (*response)->responseCode, methodName,
                      (*response)->content);

M
Matthias Bolte 已提交
912
            goto cleanup;
913 914 915 916
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
                            methodName) < 0) {
917
                virReportOOMError();
M
Matthias Bolte 已提交
918
                goto cleanup;
919
            }
920

921
            responseNode = virXPathNode(xpathExpression, xpathContext);
922

923
            if (responseNode == NULL) {
924
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
925 926
                             _("XPath evaluation of response for call to '%s' "
                               "failed"), methodName);
M
Matthias Bolte 已提交
927
                goto cleanup;
928 929
            }

930
            xpathContext->node = responseNode;
931
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
932

933 934
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
935 936
                if ((*response)->node == NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
937 938
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
939
                    goto cleanup;
940 941
                } else if ((*response)->node->next != NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
942 943
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
944
                    goto cleanup;
945 946 947 948 949
                }

                break;

              case esxVI_Occurrence_RequiredList:
950
                if ((*response)->node == NULL) {
951
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
952 953
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
954
                    goto cleanup;
955 956 957 958 959 960 961
                }

                break;

              case esxVI_Occurrence_OptionalItem:
                if ((*response)->node != NULL &&
                    (*response)->node->next != NULL) {
962
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
963 964
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
965
                    goto cleanup;
966 967 968 969
                }

                break;

970
              case esxVI_Occurrence_OptionalList:
971 972 973 974 975
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
                if ((*response)->node != NULL) {
976
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
977 978
                                 _("Call to '%s' returned something, expecting "
                                   "an empty result"), methodName);
M
Matthias Bolte 已提交
979
                    goto cleanup;
980 981 982 983 984
                }

                break;

              default:
985 986
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Invalid argument (occurrence)"));
M
Matthias Bolte 已提交
987
                goto cleanup;
988
            }
989
        }
990
    } else {
991
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
992
                     _("HTTP response code %d for call to '%s'"),
993
                     (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
994
        goto cleanup;
995 996
    }

M
Matthias Bolte 已提交
997 998
    result = 0;

999
  cleanup:
M
Matthias Bolte 已提交
1000 1001 1002 1003 1004 1005
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
        esxVI_Response_Free(response);
        esxVI_Fault_Free(&fault);
    }

1006 1007 1008 1009
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
1010 1011 1012 1013 1014
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1015
 * Response
1016 1017
 */

1018 1019
/* esxVI_Response_Alloc */
ESX_VI__TEMPLATE__ALLOC(Response);
1020

1021 1022
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
1023
{
1024
    VIR_FREE(item->content);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

    if (item->document != NULL) {
        xmlFreeDoc(item->document);
    }
});



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Enumeration
 */

int
1038
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
1039 1040 1041 1042 1043
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
1044
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1045 1046 1047 1048 1049
        return -1;
    }

    *value = 0; /* undefined */

1050
    if (anyType->type != enumeration->type) {
1051
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1052
                     _("Expecting type '%s' but found '%s'"),
1053 1054
                     esxVI_Type_ToString(enumeration->type),
                     esxVI_Type_ToString(anyType->type));
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        return -1;
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(anyType->value, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
            return 0;
        }
    }

1065
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1066
                 _("Unknown value '%s' for %s"), anyType->value,
1067
                 esxVI_Type_ToString(enumeration->type));
1068 1069 1070 1071 1072

    return -1;
}

int
1073
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
1074
                            int value, const char *element, virBufferPtr output)
1075 1076 1077 1078 1079
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
1080
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1081 1082 1083 1084
        return -1;
    }

    if (value == 0) { /* undefined */
1085
        return 0;
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (value == enumeration->values[i].value) {
            name = enumeration->values[i].name;
            break;
        }
    }

    if (name == NULL) {
1096
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1097 1098 1099
        return -1;
    }

1100 1101
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
1102 1103 1104 1105 1106 1107 1108 1109 1110

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
1111
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
1112 1113 1114
                              xmlNodePtr node, int *value)
{
    int i;
M
Matthias Bolte 已提交
1115
    int result = -1;
1116 1117 1118
    char *name = NULL;

    if (value == NULL) {
1119
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1120
        return -1;
1121 1122 1123 1124
    }

    *value = 0; /* undefined */

1125
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
M
Matthias Bolte 已提交
1126
        return -1;
1127 1128 1129 1130 1131
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(name, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
M
Matthias Bolte 已提交
1132 1133
            result = 0;
            break;
1134 1135 1136
        }
    }

M
Matthias Bolte 已提交
1137 1138 1139 1140
    if (result < 0) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, _("Unknown value '%s' for %s"),
                     name, esxVI_Type_ToString(enumeration->type));
    }
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

    VIR_FREE(name);

    return result;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * List
 */

int
1154
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
1155 1156 1157 1158
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
1159
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        return -1;
    }

    if (*list == NULL) {
        *list = item;
        return 0;
    }

    next = *list;

    while (next->_next != NULL) {
        next = next->_next;
    }

    next->_next = item;

    return 0;
}

int
1180
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
1181 1182 1183 1184 1185 1186 1187
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
1188
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1189
        return -1;
1190 1191 1192
    }

    for (src = srcList; src != NULL; src = src->_next) {
1193 1194
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
            goto failure;
        }

        dest = NULL;
    }

    return 0;

  failure:
    freeFunc(&dest);
    freeFunc(destList);

    return -1;
}

1210
int
1211
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
1212 1213 1214
                           esxVI_List_CastFromAnyTypeFunc castFromAnyTypeFunc,
                           esxVI_List_FreeFunc freeFunc)
{
M
Matthias Bolte 已提交
1215
    int result = -1;
1216 1217 1218 1219 1220 1221
    xmlNodePtr childNode = NULL;
    esxVI_AnyType *childAnyType = NULL;
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        castFromAnyTypeFunc == NULL || freeFunc == NULL) {
1222
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1223
        return -1;
1224 1225 1226 1227 1228 1229 1230
    }

    if (anyType == NULL) {
        return 0;
    }

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
1231
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1232
                     _("Expecting type to begin with 'ArrayOf' but found '%s'"),
1233
                     anyType->other);
1234
        return -1;
1235 1236
    }

1237
    for (childNode = anyType->node->children; childNode != NULL;
1238 1239
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1240
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1241
                         _("Wrong XML element type %d"), childNode->type);
M
Matthias Bolte 已提交
1242
            goto cleanup;
1243 1244 1245 1246
        }

        esxVI_AnyType_Free(&childAnyType);

1247 1248 1249
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
M
Matthias Bolte 已提交
1250
            goto cleanup;
1251 1252 1253 1254 1255
        }

        item = NULL;
    }

M
Matthias Bolte 已提交
1256 1257
    result = 0;

1258
  cleanup:
M
Matthias Bolte 已提交
1259 1260 1261 1262 1263
    if (result < 0) {
        freeFunc(&item);
        freeFunc(list);
    }

1264 1265 1266 1267 1268
    esxVI_AnyType_Free(&childAnyType);

    return result;
}

1269
int
1270
esxVI_List_Serialize(esxVI_List *list, const char *element,
1271
                     virBufferPtr output,
1272 1273 1274 1275 1276
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
1277
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1278 1279 1280 1281
        return -1;
    }

    if (list == NULL) {
1282
        return 0;
1283 1284 1285
    }

    for (item = list; item != NULL; item = item->_next) {
1286
        if (serializeFunc(item, element, output) < 0) {
1287 1288 1289 1290 1291 1292 1293 1294
            return -1;
        }
    }

    return 0;
}

int
1295
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1296 1297 1298 1299 1300 1301 1302
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
1303
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1304 1305 1306 1307 1308 1309 1310 1311 1312
        return -1;
    }

    if (node == NULL) {
        return 0;
    }

    for (; node != NULL; node = node->next) {
        if (node->type != XML_ELEMENT_NODE) {
1313
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1314
                         _("Wrong XML element type %d"), node->type);
1315 1316 1317
            goto failure;
        }

1318 1319
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1320 1321 1322
            goto failure;
        }

1323
        item = NULL;
1324 1325 1326 1327 1328
    }

    return 0;

  failure:
1329
    freeFunc(&item);
1330 1331 1332 1333 1334 1335 1336 1337 1338
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1339 1340 1341 1342
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1343 1344 1345
 */

int
1346
esxVI_Alloc(void **ptrptr, size_t size)
1347 1348
{
    if (ptrptr == NULL || *ptrptr != NULL) {
1349
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1350 1351 1352 1353
        return -1;
    }

    if (virAllocN(ptrptr, size, 1) < 0) {
1354
        virReportOOMError();
1355 1356 1357 1358 1359 1360
        return -1;
    }

    return 0;
}

1361 1362


1363
int
1364 1365 1366
esxVI_BuildSelectSet(esxVI_SelectionSpec **selectSet,
                     const char *name, const char *type,
                     const char *path, const char *selectSetNames)
1367 1368 1369 1370 1371
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

1372 1373 1374 1375 1376
    if (selectSet == NULL) {
        /*
         * Don't check for *selectSet != NULL here because selectSet is a list
         * and might contain items already. This function appends to selectSet.
         */
1377
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1378 1379 1380
        return -1;
    }

1381
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1382
        esxVI_String_DeepCopyValue(&traversalSpec->name, name) < 0 ||
1383 1384
        esxVI_String_DeepCopyValue(&traversalSpec->type, type) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->path, path) < 0) {
1385 1386 1387 1388 1389 1390 1391 1392 1393
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

    if (selectSetNames != NULL) {
        currentSelectSetName = selectSetNames;

        while (currentSelectSetName != NULL && *currentSelectSetName != '\0') {
1394 1395
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
                esxVI_String_DeepCopyValue(&selectionSpec->name,
1396
                                           currentSelectSetName) < 0 ||
1397
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1398 1399 1400 1401
                                                 selectionSpec) < 0) {
                goto failure;
            }

1402
            selectionSpec = NULL;
1403 1404 1405 1406
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1407
    if (esxVI_SelectionSpec_AppendToList(selectSet,
1408 1409
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1410 1411 1412 1413 1414 1415 1416
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);
1417
    esxVI_SelectionSpec_Free(&selectionSpec);
1418 1419 1420 1421 1422

    return -1;
}


1423

1424
int
1425
esxVI_BuildSelectSetCollection(esxVI_Context *ctx)
1426
{
1427
    /* Folder -> childEntity (ManagedEntity) */
1428 1429 1430 1431 1432
    if (esxVI_BuildSelectSet(&ctx->selectSet_folderToChildEntity,
                             "folderToChildEntity",
                             "Folder", "childEntity",
                             "folderToChildEntity\0") < 0) {
        return -1;
1433 1434
    }

1435
    /* ComputeResource -> host (HostSystem) */
1436 1437 1438 1439
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToHost,
                             "computeResourceToHost",
                             "ComputeResource", "host", NULL) < 0) {
        return -1;
1440 1441
    }

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
    /* ComputeResource -> datastore (Datastore) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToDatastore,
                             "computeResourceToDatastore",
                             "ComputeResource", "datastore", NULL) < 0) {
        return -1;
    }*/

    /* ResourcePool -> resourcePool (ResourcePool) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_resourcePoolToVm,
                             "resourcePoolToResourcePool",
                             "ResourcePool", "resourcePool",
                             "resourcePoolToResourcePool\0"
                             "resourcePoolToVm\0") < 0) {
        return -1;
    }*/
1457

1458 1459 1460 1461 1462 1463
    /* ResourcePool -> vm (VirtualMachine) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_resourcePoolToVm,
                             "resourcePoolToVm",
                             "ResourcePool", "vm", NULL) < 0) {
        return -1;
    }*/
1464

1465
    /* HostSystem -> parent (ComputeResource) */
1466 1467 1468 1469
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToParent,
                             "hostSystemToParent",
                             "HostSystem", "parent", NULL) < 0) {
        return -1;
1470 1471
    }

1472
    /* HostSystem -> vm (VirtualMachine) */
1473 1474 1475 1476
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToVm,
                             "hostSystemToVm",
                             "HostSystem", "vm", NULL) < 0) {
        return -1;
1477 1478
    }

1479
    /* HostSystem -> datastore (Datastore) */
1480 1481 1482 1483
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToDatastore,
                             "hostSystemToDatastore",
                             "HostSystem", "datastore", NULL) < 0) {
        return -1;
1484 1485
    }

1486 1487 1488 1489 1490 1491
    /* Folder -> parent (Folder, Datacenter) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "managedEntityToParent",
                             "ManagedEntity", "parent", NULL) < 0) {
        return -1;
    }
1492

1493 1494 1495 1496 1497 1498 1499
    /* ComputeResource -> parent (Folder) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "computeResourceToParent",
                             "ComputeResource", "parent",
                             "managedEntityToParent\0") < 0) {
        return -1;
    }
1500

1501
    return 0;
1502 1503 1504 1505 1506
}



int
1507
esxVI_EnsureSession(esxVI_Context *ctx)
1508
{
M
Matthias Bolte 已提交
1509
    int result = -1;
1510
    esxVI_Boolean active = esxVI_Boolean_Undefined;
1511 1512 1513 1514 1515 1516
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;

    if (ctx->session == NULL) {
1517
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
1518 1519 1520
        return -1;
    }

1521 1522 1523 1524 1525 1526 1527
    if (ctx->hasSessionIsActive) {
        /*
         * Use SessionIsActive to check if there is an active session for this
         * connection an re-login in there isn't.
         */
        if (esxVI_SessionIsActive(ctx, ctx->session->key,
                                  ctx->session->userName, &active) < 0) {
1528 1529
            return -1;
        }
1530

1531 1532
        if (active != esxVI_Boolean_True) {
            esxVI_UserSession_Free(&ctx->session);
1533

1534 1535 1536
            if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                            &ctx->session) < 0) {
                return -1;
1537
            }
1538
        }
1539

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
        return 0;
    } else {
        /*
         * Query the session manager for the current session of this connection
         * and re-login if there is no current session for this connection.
         */
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "currentSession") < 0 ||
            esxVI_LookupObjectContentByType(ctx, ctx->service->sessionManager,
                                            "SessionManager", propertyNameList,
1550 1551
                                            &sessionManager,
                                            esxVI_Occurrence_RequiredItem) < 0) {
1552
            goto cleanup;
1553 1554
        }

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
        for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "currentSession")) {
                if (esxVI_UserSession_CastFromAnyType(dynamicProperty->val,
                                                      &currentSession) < 0) {
                    goto cleanup;
                }

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

1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
        if (currentSession == NULL) {
            esxVI_UserSession_Free(&ctx->session);

            if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                            &ctx->session) < 0) {
                goto cleanup;
            }
        } else if (STRNEQ(ctx->session->key, currentSession->key)) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Key of the current session differs from the key at "
                           "last login"));
M
Matthias Bolte 已提交
1580
            goto cleanup;
1581 1582
        }

1583
        result = 0;
M
Matthias Bolte 已提交
1584

1585
  cleanup:
1586 1587 1588
        esxVI_String_Free(&propertyNameList);
        esxVI_ObjectContent_Free(&sessionManager);
        esxVI_UserSession_Free(&currentSession);
1589

1590 1591
        return result;
    }
1592 1593 1594 1595 1596
}



int
1597
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
1598 1599 1600
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
1601 1602
                                esxVI_ObjectContent **objectContentList,
                                esxVI_Occurrence occurrence)
1603
{
M
Matthias Bolte 已提交
1604
    int result = -1;
1605 1606 1607 1608
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

1609 1610 1611 1612 1613
    if (objectContentList == NULL || *objectContentList != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

1614
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
1615
        return -1;
1616 1617 1618 1619 1620
    }

    objectSpec->obj = root;
    objectSpec->skip = esxVI_Boolean_False;

1621 1622
    if (STRNEQ(root->type, type)) {
        if (STREQ(root->type, "Folder")) {
1623 1624
            if (STREQ(type, "Datacenter") || STREQ(type, "ComputeResource") ||
                STREQ(type, "ClusterComputeResource")) {
1625 1626 1627 1628 1629 1630 1631
                objectSpec->selectSet = ctx->selectSet_folderToChildEntity;
            } else {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("Invalid lookup of '%s' from '%s'"),
                             type, root->type);
                goto cleanup;
            }
1632 1633
        } else if (STREQ(root->type, "ComputeResource") ||
                   STREQ(root->type, "ClusterComputeResource")) {
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
            if (STREQ(type, "HostSystem")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToHost;
            } else if (STREQ(type, "Datacenter")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToParentToParent;
            } else {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("Invalid lookup of '%s' from '%s'"),
                             type, root->type);
                goto cleanup;
            }
        } else if (STREQ(root->type, "HostSystem")) {
1645 1646
            if (STREQ(type, "ComputeResource") ||
                STREQ(type, "ClusterComputeResource")) {
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                objectSpec->selectSet = ctx->selectSet_hostSystemToParent;
            } else if (STREQ(type, "VirtualMachine")) {
                objectSpec->selectSet = ctx->selectSet_hostSystemToVm;
            } else if (STREQ(type, "Datastore")) {
                objectSpec->selectSet = ctx->selectSet_hostSystemToDatastore;
            } else {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("Invalid lookup of '%s' from '%s'"),
                             type, root->type);
                goto cleanup;
            }
        } else {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Invalid lookup from '%s'"), root->type);
            goto cleanup;
        }
1663 1664
    }

1665
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
1666
        goto cleanup;
1667 1668 1669 1670 1671
    }

    propertySpec->type = (char *)type;
    propertySpec->pathSet = propertyNameList;

1672 1673
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
1674
                                        propertySpec) < 0 ||
1675
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
                                      objectSpec) < 0 ||
        esxVI_RetrieveProperties(ctx, propertyFilterSpec,
                                 objectContentList) < 0) {
        goto cleanup;
    }

    if (objectContentList == NULL) {
        switch (occurrence) {
          case esxVI_Occurrence_OptionalItem:
          case esxVI_Occurrence_OptionalList:
            result = 0;
            break;

          case esxVI_Occurrence_RequiredItem:
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Could not lookup '%s' from '%s'"),
                         type, root->type);
            break;

          case esxVI_Occurrence_RequiredList:
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Could not lookup '%s' list from '%s'"),
                         type, root->type);
            break;

          default:
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Invalid occurrence value"));
            break;
        }

M
Matthias Bolte 已提交
1707
        goto cleanup;
1708 1709
    }

1710
    result = 0;
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733

  cleanup:
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
     */
    if (objectSpec != NULL) {
        objectSpec->obj = NULL;
        objectSpec->selectSet = NULL;
    }

    if (propertySpec != NULL) {
        propertySpec->type = NULL;
        propertySpec->pathSet = NULL;
    }

    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);

    return result;
}



1734
int
1735
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
1736 1737 1738 1739 1740 1741 1742 1743 1744
                             const char *propertyName,
                             esxVI_ManagedEntityStatus *managedEntityStatus)
{
    esxVI_DynamicProperty *dynamicProperty;

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            return esxVI_ManagedEntityStatus_CastFromAnyType
1745
                     (dynamicProperty->val, managedEntityStatus);
1746 1747 1748
        }
    }

1749
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1750 1751
                 _("Missing '%s' property while looking for "
                   "ManagedEntityStatus"), propertyName);
1752 1753 1754 1755 1756 1757

    return -1;
}



1758
int
1759
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
1760 1761 1762 1763 1764 1765 1766 1767
                                  esxVI_VirtualMachinePowerState *powerState)
{
    esxVI_DynamicProperty *dynamicProperty;

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            return esxVI_VirtualMachinePowerState_CastFromAnyType
1768
                     (dynamicProperty->val, powerState);
1769 1770 1771
        }
    }

1772 1773
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("Missing 'runtime.powerState' property"));
1774 1775 1776 1777 1778 1779

    return -1;
}



1780 1781
int
esxVI_GetVirtualMachineQuestionInfo
1782
  (esxVI_ObjectContent *virtualMachine,
1783 1784 1785 1786 1787
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (questionInfo == NULL || *questionInfo != NULL) {
1788
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1789 1790 1791 1792 1793 1794 1795
        return -1;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
1796
                  (dynamicProperty->val, questionInfo) < 0) {
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
                return -1;
            }
        }
    }

    return 0;
}



1807 1808
int
esxVI_GetBoolean(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
1809
                 esxVI_Boolean *value, esxVI_Occurrence occurrence)
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != esxVI_Boolean_Undefined) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
                                         esxVI_Type_Boolean) < 0) {
                return -1;
            }

            *value = dynamicProperty->val->boolean;
            break;
        }
    }

    if (*value == esxVI_Boolean_Undefined &&
M
Matthias Bolte 已提交
1832
        occurrence == esxVI_Occurrence_RequiredItem) {
1833 1834 1835 1836 1837 1838 1839 1840
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}

M
Matthias Bolte 已提交
1841 1842


1843 1844
int
esxVI_GetLong(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
1845
              esxVI_Long **value, esxVI_Occurrence occurrence)
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_Long_CastFromAnyType(dynamicProperty->val, value) < 0) {
                return -1;
            }

            break;
        }
    }

M
Matthias Bolte 已提交
1865
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
1866 1867 1868 1869 1870 1871 1872 1873
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}

1874 1875 1876 1877 1878


int
esxVI_GetStringValue(esxVI_ObjectContent *objectContent,
                     const char *propertyName,
M
Matthias Bolte 已提交
1879
                     char **value, esxVI_Occurrence occurrence)
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
                                         esxVI_Type_String) < 0) {
                return -1;
            }

            *value = dynamicProperty->val->string;
            break;
        }
    }

M
Matthias Bolte 已提交
1901
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



int
esxVI_GetManagedObjectReference(esxVI_ObjectContent *objectContent,
                                const char *propertyName,
                                esxVI_ManagedObjectReference **value,
M
Matthias Bolte 已提交
1916
                                esxVI_Occurrence occurrence)
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, value) < 0) {
                return -1;
            }

            break;
        }
    }

M
Matthias Bolte 已提交
1937
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



1948
int
1949
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
1950 1951
                                        esxVI_VirtualMachinePowerState powerState,
                                        esxVI_Boolean inverse)
1952
{
M
Matthias Bolte 已提交
1953
    bool success = false;
1954 1955 1956 1957 1958
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
M
Matthias Bolte 已提交
1959
    int count = 0;
1960

1961
    if (esxVI_String_AppendValueToList(&propertyNameList,
1962
                                       "runtime.powerState") < 0 ||
1963 1964
        esxVI_LookupVirtualMachineList(ctx, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1965
        goto cleanup;
1966 1967 1968 1969 1970 1971 1972 1973 1974
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "runtime.powerState")) {
                if (esxVI_VirtualMachinePowerState_CastFromAnyType
1975
                      (dynamicProperty->val, &powerState_) < 0) {
M
Matthias Bolte 已提交
1976
                    goto cleanup;
1977 1978 1979 1980 1981 1982
                }

                if ((inverse != esxVI_Boolean_True &&
                     powerState_ == powerState) ||
                    (inverse == esxVI_Boolean_True &&
                     powerState_ != powerState)) {
M
Matthias Bolte 已提交
1983
                    count++;
1984 1985 1986 1987 1988 1989 1990
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

M
Matthias Bolte 已提交
1991 1992
    success = true;

1993 1994 1995 1996
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1997
    return success ? count : -1;
1998 1999 2000 2001 2002
}



int
2003
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
2004 2005 2006 2007
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
2008
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
2009 2010

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
2011 2012
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("ObjectContent does not reference a virtual machine"));
2013 2014 2015 2016 2017 2018
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
2019
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2020
                         _("Could not parse positive integer from '%s'"),
2021 2022 2023 2024 2025 2026 2027
                         virtualMachine->obj->value);
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
2028
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2029 2030 2031 2032 2033 2034 2035
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2036
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2037 2038 2039 2040 2041 2042 2043
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                *name = strdup(dynamicProperty->val->string);

                if (*name == NULL) {
2044
                    virReportOOMError();
2045 2046 2047
                    goto failure;
                }

2048
                if (virVMXUnescapeHexPercent(*name) < 0) {
2049 2050 2051 2052 2053
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                                 _("Domain name contains invalid escape sequence"));
                    goto failure;
                }

2054 2055 2056 2057 2058
                break;
            }
        }

        if (*name == NULL) {
2059 2060
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not get name of virtual machine"));
2061 2062 2063 2064 2065
            goto failure;
        }
    }

    if (uuid != NULL) {
2066
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
2067 2068 2069 2070 2071 2072 2073 2074 2075
                                         &configStatus) < 0) {
            goto failure;
        }

        if (configStatus == esxVI_ManagedEntityStatus_Green) {
            for (dynamicProperty = virtualMachine->propSet;
                 dynamicProperty != NULL;
                 dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "config.uuid")) {
2076
                    if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2077 2078 2079 2080 2081 2082
                                                 esxVI_Type_String) < 0) {
                        goto failure;
                    }

                    uuid_string = dynamicProperty->val->string;
                    break;
2083
                }
2084
            }
2085

2086
            if (uuid_string == NULL) {
2087 2088
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Could not get UUID of virtual machine"));
2089
                goto failure;
2090 2091
            }

2092
            if (virUUIDParse(uuid_string, uuid) < 0) {
2093
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2094
                             _("Could not parse UUID from string '%s'"),
2095 2096 2097 2098 2099
                             uuid_string);
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
2100

2101 2102
            VIR_WARN0("Cannot access UUID, because 'configStatus' property "
                      "indicates a config problem");
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
        }
    }

    return 0;

  failure:
    if (name != NULL) {
        VIR_FREE(*name);
    }

    return -1;
}



2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
int
esxVI_GetNumberOfSnapshotTrees
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList)
{
    int count = 0;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList; snapshotTree != NULL;
         snapshotTree = snapshotTree->_next) {
        count += 1 + esxVI_GetNumberOfSnapshotTrees
                       (snapshotTree->childSnapshotList);
    }

    return count;
}



int
esxVI_GetSnapshotTreeNames(esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
                           char **names, int nameslen)
{
    int count = 0;
    int result;
    int i;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList;
         snapshotTree != NULL && count < nameslen;
         snapshotTree = snapshotTree->_next) {
        names[count] = strdup(snapshotTree->name);

        if (names[count] == NULL) {
            virReportOOMError();
            goto failure;
        }

        count++;

        if (count >= nameslen) {
            break;
        }

        result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
                                            names + count, nameslen - count);

        if (result < 0) {
            goto failure;
        }

        count += result;
    }

    return count;

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

    return -1;
}



int
esxVI_GetSnapshotTreeByName
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList, const char *name,
   esxVI_VirtualMachineSnapshotTree **snapshotTree,
   esxVI_VirtualMachineSnapshotTree **snapshotTreeParent,
   esxVI_Occurrence occurrence)
{
    esxVI_VirtualMachineSnapshotTree *candidate;

    if (snapshotTree == NULL || *snapshotTree != NULL ||
        snapshotTreeParent == NULL || *snapshotTreeParent != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (candidate = snapshotTreeList; candidate != NULL;
         candidate = candidate->_next) {
        if (STREQ(candidate->name, name)) {
            *snapshotTree = candidate;
            *snapshotTreeParent = NULL;
            return 1;
        }

        if (esxVI_GetSnapshotTreeByName(candidate->childSnapshotList, name,
                                        snapshotTree, snapshotTreeParent,
                                        occurrence) > 0) {
            if (*snapshotTreeParent == NULL) {
                *snapshotTreeParent = candidate;
            }

            return 1;
        }
    }

    if (occurrence == esxVI_Occurrence_OptionalItem) {
        return 0;
    } else {
        ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                     _("Could not find snapshot with name '%s'"), name);

        return -1;
    }
}



int
esxVI_GetSnapshotTreeBySnapshot
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
   esxVI_ManagedObjectReference *snapshot,
   esxVI_VirtualMachineSnapshotTree **snapshotTree)
{
    esxVI_VirtualMachineSnapshotTree *candidate;

    if (snapshotTree == NULL || *snapshotTree != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (candidate = snapshotTreeList; candidate != NULL;
         candidate = candidate->_next) {
        if (STREQ(candidate->snapshot->value, snapshot->value)) {
            *snapshotTree = candidate;
            return 0;
        }

        if (esxVI_GetSnapshotTreeBySnapshot(candidate->childSnapshotList,
                                            snapshot, snapshotTree) >= 0) {
            return 0;
        }
    }

    ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                 _("Could not find domain snapshot with internal name '%s'"),
                 snapshot->value);

    return -1;
}



M
Matthias Bolte 已提交
2264 2265 2266 2267
int
esxVI_LookupHostSystemProperties(esxVI_Context *ctx,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **hostSystem)
M
Matthias Bolte 已提交
2268
{
2269 2270
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "HostSystem", propertyNameList,
2271 2272
                                           hostSystem,
                                           esxVI_Occurrence_RequiredItem);
M
Matthias Bolte 已提交
2273 2274 2275 2276
}



2277
int
2278 2279 2280
esxVI_LookupVirtualMachineList(esxVI_Context *ctx,
                               esxVI_String *propertyNameList,
                               esxVI_ObjectContent **virtualMachineList)
2281
{
2282 2283 2284 2285
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource->resourcePool
     *        for cluster support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "VirtualMachine", propertyNameList,
2286 2287
                                           virtualMachineList,
                                           esxVI_Occurrence_OptionalList);
2288 2289 2290 2291 2292
}



int
2293
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
2294
                                 esxVI_String *propertyNameList,
2295
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
2296
                                 esxVI_Occurrence occurrence)
2297
{
M
Matthias Bolte 已提交
2298
    int result = -1;
2299
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
2300
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
2301 2302

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2303
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2304 2305 2306
        return -1;
    }

2307 2308
    virUUIDFormat(uuid, uuid_string);

2309 2310
    if (esxVI_FindByUuid(ctx, ctx->datacenter->_reference, uuid_string,
                         esxVI_Boolean_True, &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2311
        return -1;
2312 2313
    }

2314
    if (managedObjectReference == NULL) {
M
Matthias Bolte 已提交
2315
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2316 2317 2318
            result = 0;

            goto cleanup;
2319
        } else {
2320
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2321 2322
                         _("Could not find domain with UUID '%s'"),
                         uuid_string);
M
Matthias Bolte 已提交
2323
            goto cleanup;
2324 2325 2326
        }
    }

2327
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2328
                                        "VirtualMachine", propertyNameList,
2329 2330
                                        virtualMachine,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2331
        goto cleanup;
2332 2333
    }

M
Matthias Bolte 已提交
2334 2335
    result = 0;

2336 2337 2338 2339
  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
M
Matthias Bolte 已提交
2340 2341 2342 2343
}



2344 2345 2346 2347 2348 2349
int
esxVI_LookupVirtualMachineByName(esxVI_Context *ctx, const char *name,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2350
    int result = -1;
2351 2352 2353 2354 2355 2356
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate = NULL;

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2357
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2358 2359 2360 2361 2362 2363
        return -1;
    }

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
2364 2365
        esxVI_LookupVirtualMachineList(ctx, completePropertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2366
        goto cleanup;
2367 2368 2369 2370 2371 2372 2373 2374
    }

    for (candidate = virtualMachineList; candidate != NULL;
         candidate = candidate->_next) {
        VIR_FREE(name_candidate);

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
M
Matthias Bolte 已提交
2375
            goto cleanup;
2376 2377 2378 2379 2380 2381 2382
        }

        if (STRNEQ(name, name_candidate)) {
            continue;
        }

        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0) {
M
Matthias Bolte 已提交
2383
            goto cleanup;
2384 2385 2386 2387 2388 2389 2390
        }

        break;
    }

    if (*virtualMachine == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2391 2392 2393
            result = 0;

            goto cleanup;
2394 2395
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2396
                         _("Could not find domain with name '%s'"), name);
M
Matthias Bolte 已提交
2397
            goto cleanup;
2398 2399 2400
        }
    }

M
Matthias Bolte 已提交
2401 2402
    result = 0;

2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;
}



2413 2414
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2415
  (esxVI_Context *ctx, const unsigned char *uuid,
2416 2417 2418
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
   esxVI_Boolean autoAnswer)
{
M
Matthias Bolte 已提交
2419
    int result = -1;
2420 2421 2422
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;
2423
    esxVI_Boolean blocked = esxVI_Boolean_Undefined;
2424

2425
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2426
                                  propertyNameList) < 0 ||
2427
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2428 2429
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2430
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2431
                                         virtualMachine,
M
Matthias Bolte 已提交
2432
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2433
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
2434 2435
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
2436
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
M
Matthias Bolte 已提交
2437
        goto cleanup;
2438 2439 2440
    }

    if (questionInfo != NULL &&
2441
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
2442 2443
                                           questionInfo, autoAnswer,
                                           &blocked) < 0) {
M
Matthias Bolte 已提交
2444
        goto cleanup;
2445 2446 2447
    }

    if (pendingTaskInfoList != NULL) {
2448 2449
        ESX_VI_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                     _("Other tasks are pending for this domain"));
M
Matthias Bolte 已提交
2450
        goto cleanup;
2451 2452
    }

M
Matthias Bolte 已提交
2453 2454
    result = 0;

2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;
}



2465 2466 2467 2468 2469 2470 2471 2472
int
esxVI_LookupDatastoreList(esxVI_Context *ctx, esxVI_String *propertyNameList,
                          esxVI_ObjectContent **datastoreList)
{
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource for cluster
     *        support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "Datastore", propertyNameList,
2473 2474
                                           datastoreList,
                                           esxVI_Occurrence_OptionalList);
2475 2476 2477 2478
}



M
Matthias Bolte 已提交
2479
int
2480 2481
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
2482
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
2483
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
2484
{
M
Matthias Bolte 已提交
2485
    int result = -1;
M
Matthias Bolte 已提交
2486 2487 2488
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
2489
    char *name_candidate;
M
Matthias Bolte 已提交
2490 2491

    if (datastore == NULL || *datastore != NULL) {
2492
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
2493 2494 2495 2496
        return -1;
    }

    /* Get all datastores */
2497
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
2498
                                  propertyNameList) < 0 ||
2499 2500
        esxVI_String_AppendValueToList(&completePropertyNameList,
                                       "summary.name") < 0 ||
2501 2502
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
M
Matthias Bolte 已提交
2503
        goto cleanup;
M
Matthias Bolte 已提交
2504 2505
    }

2506 2507 2508 2509 2510 2511 2512
    /* Search for a matching datastore */
    for (candidate = datastoreList; candidate != NULL;
         candidate = candidate->_next) {
        name_candidate = NULL;

        if (esxVI_GetStringValue(candidate, "summary.name", &name_candidate,
                                 esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2513
            goto cleanup;
M
Matthias Bolte 已提交
2514
        }
2515 2516 2517 2518 2519 2520

        if (STREQ(name_candidate, name)) {
            if (esxVI_ObjectContent_DeepCopy(datastore, candidate) < 0) {
                goto cleanup;
            }

2521 2522 2523 2524
            /* Found datastore with matching name */
            result = 0;

            goto cleanup;
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
        }
    }

    if (*datastore == NULL && occurrence != esxVI_Occurrence_OptionalItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find datastore with name '%s'"), name);
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);

    return result;
}


int
esxVI_LookupDatastoreByAbsolutePath(esxVI_Context *ctx,
                                    const char *absolutePath,
                                    esxVI_String *propertyNameList,
                                    esxVI_ObjectContent **datastore,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_DatastoreHostMount *datastoreHostMountList = NULL;
    esxVI_DatastoreHostMount *datastoreHostMount = NULL;

    if (datastore == NULL || *datastore != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    /* Get all datastores */
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "host") < 0 ||
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
        goto cleanup;
M
Matthias Bolte 已提交
2571 2572 2573 2574 2575
    }

    /* Search for a matching datastore */
    for (candidate = datastoreList; candidate != NULL;
         candidate = candidate->_next) {
2576
        esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
2577

M
Matthias Bolte 已提交
2578 2579
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
2580 2581 2582
            if (STREQ(dynamicProperty->name, "host")) {
                if (esxVI_DatastoreHostMount_CastListFromAnyType
                      (dynamicProperty->val, &datastoreHostMountList) < 0) {
M
Matthias Bolte 已提交
2583
                    goto cleanup;
2584 2585 2586 2587 2588 2589
                }

                break;
            }
        }

2590 2591
        if (datastoreHostMountList == NULL) {
            continue;
2592 2593
        }

2594 2595 2596 2597 2598 2599 2600
        for (datastoreHostMount = datastoreHostMountList;
             datastoreHostMount != NULL;
             datastoreHostMount = datastoreHostMount->_next) {
            if (STRNEQ(ctx->hostSystem->_reference->value,
                       datastoreHostMount->key->value)) {
                continue;
            }
2601

2602 2603
            if (STRPREFIX(absolutePath, datastoreHostMount->mountInfo->path)) {
                if (esxVI_ObjectContent_DeepCopy(datastore, candidate) < 0) {
M
Matthias Bolte 已提交
2604
                    goto cleanup;
M
Matthias Bolte 已提交
2605 2606
                }

2607
                /* Found datastore with matching mount path */
2608 2609 2610
                result = 0;

                goto cleanup;
M
Matthias Bolte 已提交
2611 2612 2613 2614
            }
        }
    }

2615 2616 2617 2618
    if (*datastore == NULL && occurrence != esxVI_Occurrence_OptionalItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find datastore containing absolute path '%s'"),
                     absolutePath);
M
Matthias Bolte 已提交
2619
        goto cleanup;
M
Matthias Bolte 已提交
2620 2621
    }

M
Matthias Bolte 已提交
2622 2623
    result = 0;

M
Matthias Bolte 已提交
2624 2625 2626
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
2627
    esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
M
Matthias Bolte 已提交
2628 2629

    return result;
2630 2631 2632 2633
}



2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
int
esxVI_LookupDatastoreHostMount(esxVI_Context *ctx,
                               esxVI_ManagedObjectReference *datastore,
                               esxVI_DatastoreHostMount **hostMount)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_DatastoreHostMount *hostMountList = NULL;
    esxVI_DatastoreHostMount *candidate = NULL;

    if (hostMount == NULL || *hostMount != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList, "host") < 0 ||
        esxVI_LookupObjectContentByType(ctx, datastore, "Datastore",
2653 2654
                                        propertyNameList, &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
        goto cleanup;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "host")) {
            if (esxVI_DatastoreHostMount_CastListFromAnyType
                  (dynamicProperty->val, &hostMountList) < 0) {
                goto cleanup;
            }

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

    for (candidate = hostMountList; candidate != NULL;
         candidate = candidate->_next) {
        if (STRNEQ(ctx->hostSystem->_reference->value, candidate->key->value)) {
            continue;
        }

        if (esxVI_DatastoreHostMount_DeepCopy(hostMount, candidate) < 0) {
            goto cleanup;
        }

        break;
    }

    if (*hostMount == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not lookup datastore host mount"));
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);
    esxVI_DatastoreHostMount_Free(&hostMountList);

    return result;
}


2702 2703 2704 2705
int
esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
                           esxVI_ManagedObjectReference *task,
                           esxVI_TaskInfo **taskInfo)
2706
{
M
Matthias Bolte 已提交
2707
    int result = -1;
2708 2709 2710 2711 2712
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (taskInfo == NULL || *taskInfo != NULL) {
2713
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2714 2715 2716
        return -1;
    }

2717 2718
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
2719 2720
                                        &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2721
        goto cleanup;
2722 2723 2724 2725 2726
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
2727
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
2728
                                               taskInfo) < 0) {
M
Matthias Bolte 已提交
2729
                goto cleanup;
2730 2731 2732 2733 2734 2735 2736 2737
            }

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

M
Matthias Bolte 已提交
2738 2739
    result = 0;

2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);

    return result;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
2751
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
2752 2753
   esxVI_TaskInfo **pendingTaskInfoList)
{
M
Matthias Bolte 已提交
2754
    int result = -1;
2755 2756 2757 2758 2759 2760 2761
    esxVI_String *propertyNameList = NULL;
    esxVI_ManagedObjectReference *recentTaskList = NULL;
    esxVI_ManagedObjectReference *recentTask = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_TaskInfo *taskInfo = NULL;

    if (pendingTaskInfoList == NULL || *pendingTaskInfoList != NULL) {
2762
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2763 2764 2765 2766 2767 2768 2769 2770
        return -1;
    }

    /* Get list of recent tasks */
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "recentTask")) {
            if (esxVI_ManagedObjectReference_CastListFromAnyType
2771
                  (dynamicProperty->val, &recentTaskList) < 0) {
M
Matthias Bolte 已提交
2772
                goto cleanup;
2773 2774 2775 2776 2777 2778 2779 2780 2781
            }

            break;
        }
    }

    /* Lookup task info for each task */
    for (recentTask = recentTaskList; recentTask != NULL;
         recentTask = recentTask->_next) {
2782
        if (esxVI_LookupTaskInfoByTask(ctx, recentTask, &taskInfo) < 0) {
M
Matthias Bolte 已提交
2783
            goto cleanup;
2784 2785 2786 2787
        }

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
2788
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
2789
                                            taskInfo) < 0) {
M
Matthias Bolte 已提交
2790
                goto cleanup;
2791 2792 2793 2794 2795 2796 2797 2798
            }

            taskInfo = NULL;
        } else {
            esxVI_TaskInfo_Free(&taskInfo);
        }
    }

M
Matthias Bolte 已提交
2799 2800
    result = 0;

2801
  cleanup:
M
Matthias Bolte 已提交
2802 2803 2804 2805
    if (result < 0) {
        esxVI_TaskInfo_Free(pendingTaskInfoList);
    }

2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



int
2816
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
2817
                                            const unsigned char *uuid,
2818 2819 2820
                                            esxVI_Occurrence occurrence,
                                            esxVI_Boolean autoAnswer,
                                            esxVI_Boolean *blocked)
2821
{
M
Matthias Bolte 已提交
2822
    int result = -1;
2823 2824 2825 2826
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

2827
    if (esxVI_String_AppendValueToList(&propertyNameList,
2828
                                       "runtime.question") < 0 ||
2829
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
2830
                                         &virtualMachine, occurrence) < 0) {
M
Matthias Bolte 已提交
2831
        goto cleanup;
2832 2833
    }

2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
    if (virtualMachine != NULL) {
        if (esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
                                                &questionInfo) < 0) {
            goto cleanup;
        }

        if (questionInfo != NULL &&
            esxVI_HandleVirtualMachineQuestion(ctx, virtualMachine->obj,
                                               questionInfo, autoAnswer,
                                               blocked) < 0) {
            goto cleanup;
        }
2846 2847
    }

M
Matthias Bolte 已提交
2848 2849
    result = 0;

2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);

    return result;
}



2860 2861 2862 2863 2864
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
M
Matthias Bolte 已提交
2865
    int result = -1;
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (rootSnapshotTreeList == NULL || *rootSnapshotTreeList != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "snapshot.rootSnapshotList") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2880
        goto cleanup;
2881 2882 2883 2884 2885 2886 2887
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
2888
                goto cleanup;
2889 2890 2891 2892 2893 2894 2895 2896
            }

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

M
Matthias Bolte 已提交
2897 2898
    result = 0;

2899
  cleanup:
M
Matthias Bolte 已提交
2900 2901 2902 2903
    if (result < 0) {
        esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);
    }

2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



int
esxVI_LookupCurrentSnapshotTree
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **currentSnapshotTree,
   esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2918
    int result = -1;
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *currentSnapshot = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;

    if (currentSnapshotTree == NULL || *currentSnapshotTree != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "snapshot.currentSnapshot\0"
                                           "snapshot.rootSnapshotList\0") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2937
        goto cleanup;
2938 2939 2940 2941 2942 2943 2944
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.currentSnapshot")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, &currentSnapshot) < 0) {
M
Matthias Bolte 已提交
2945
                goto cleanup;
2946 2947 2948 2949
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
2950
                goto cleanup;
2951 2952 2953 2954 2955 2956 2957 2958
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (currentSnapshot == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2959 2960 2961
            result = 0;

            goto cleanup;
2962 2963 2964
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                         _("Domain has no current snapshot"));
M
Matthias Bolte 已提交
2965
            goto cleanup;
2966 2967 2968 2969 2970 2971
        }
    }

    if (rootSnapshotTreeList == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not lookup root snapshot list"));
M
Matthias Bolte 已提交
2972
        goto cleanup;
2973 2974 2975 2976 2977 2978
    }

    if (esxVI_GetSnapshotTreeBySnapshot(rootSnapshotTreeList, currentSnapshot,
                                        &snapshotTree) < 0 ||
        esxVI_VirtualMachineSnapshotTree_DeepCopy(currentSnapshotTree,
                                                  snapshotTree) < 0) {
M
Matthias Bolte 已提交
2979
        goto cleanup;
2980 2981
    }

M
Matthias Bolte 已提交
2982 2983
    result = 0;

2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



2995 2996 2997
int
esxVI_LookupFileInfoByDatastorePath(esxVI_Context *ctx,
                                    const char *datastorePath,
2998
                                    bool lookupFolder,
2999 3000 3001 3002 3003 3004
                                    esxVI_FileInfo **fileInfo,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    char *datastoreName = NULL;
    char *directoryName = NULL;
3005
    char *directoryAndFileName = NULL;
3006
    char *fileName = NULL;
3007
    size_t length;
3008 3009 3010 3011 3012
    char *datastorePathWithoutFileName = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
3013
    esxVI_FolderFileQuery *folderFileQuery = NULL;
3014 3015 3016 3017 3018
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3019
    char *taskInfoErrorMessage = NULL;
3020 3021 3022 3023 3024 3025 3026 3027 3028
    esxVI_TaskInfo *taskInfo = NULL;
    esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL;

    if (fileInfo == NULL || *fileInfo != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName,
3029
                                   &directoryName, &directoryAndFileName) < 0) {
3030 3031 3032
        goto cleanup;
    }

3033 3034 3035 3036 3037
    if (STREQ(directoryName, directoryAndFileName)) {
        /*
         * The <path> part of the datatore path didn't contain a '/', assume
         * that the <path> part is actually the file name.
         */
3038 3039 3040 3041 3042
        if (virAsprintf(&datastorePathWithoutFileName, "[%s]",
                        datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
3043 3044 3045 3046

        if (esxVI_String_DeepCopyValue(&fileName, directoryAndFileName) < 0) {
            goto cleanup;
        }
3047 3048 3049 3050 3051 3052
    } else {
        if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s",
                        datastoreName, directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067

        length = strlen(directoryName);

        if (directoryAndFileName[length] != '/' ||
            directoryAndFileName[length + 1] == '\0') {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Datastore path '%s' doesn't reference a file"),
                         datastorePath);
            goto cleanup;
        }

        if (esxVI_String_DeepCopyValue(&fileName,
                                       directoryAndFileName + length + 1) < 0) {
            goto cleanup;
        }
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
    }

    /* Lookup HostDatastoreBrowser */
    if (esxVI_String_AppendValueToList(&propertyNameList, "browser") < 0 ||
        esxVI_LookupDatastoreByName(ctx, datastoreName, propertyNameList,
                                    &datastore,
                                    esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetManagedObjectReference(datastore, "browser",
                                        &hostDatastoreBrowser,
                                        esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* Build HostDatastoreBrowserSearchSpec */
    if (esxVI_HostDatastoreBrowserSearchSpec_Alloc(&searchSpec) < 0 ||
        esxVI_FileQueryFlags_Alloc(&searchSpec->details) < 0) {
        goto cleanup;
    }

    searchSpec->details->fileType = esxVI_Boolean_True;
    searchSpec->details->fileSize = esxVI_Boolean_True;
    searchSpec->details->modification = esxVI_Boolean_False;

3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
    if (lookupFolder) {
        if (esxVI_FolderFileQuery_Alloc(&folderFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(folderFileQuery)) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_VmDiskFileQuery_Alloc(&vmDiskFileQuery) < 0 ||
            esxVI_VmDiskFileQueryFlags_Alloc(&vmDiskFileQuery->details) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(vmDiskFileQuery)) < 0) {
            goto cleanup;
        }
3106

3107 3108 3109 3110 3111
        vmDiskFileQuery->details->diskType = esxVI_Boolean_False;
        vmDiskFileQuery->details->capacityKb = esxVI_Boolean_True;
        vmDiskFileQuery->details->hardwareVersion = esxVI_Boolean_False;
        vmDiskFileQuery->details->controllerType = esxVI_Boolean_True;
        vmDiskFileQuery->details->diskExtents = esxVI_Boolean_False;
3112

3113 3114 3115 3116 3117 3118
        if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
            goto cleanup;
        }
3119

3120 3121 3122 3123 3124 3125
        if (esxVI_FloppyImageFileQuery_Alloc(&floppyImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(floppyImageFileQuery)) < 0) {
            goto cleanup;
        }
3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
    }

    if (esxVI_String_Alloc(&searchSpec->matchPattern) < 0) {
        goto cleanup;
    }

    searchSpec->matchPattern->value = fileName;

    /* Search datastore for file */
    if (esxVI_SearchDatastore_Task(ctx, hostDatastoreBrowser,
                                   datastorePathWithoutFileName, searchSpec,
                                   &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3139 3140
                                    esxVI_Boolean_False, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
3141 3142 3143 3144 3145
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3146 3147
                     _("Could not search in datastore '%s': %s"),
                     datastoreName, taskInfoErrorMessage);
3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183
        goto cleanup;
    }

    if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo) < 0 ||
        esxVI_HostDatastoreBrowserSearchResults_CastFromAnyType
          (taskInfo->result, &searchResults) < 0) {
        goto cleanup;
    }

    /* Interpret search result */
    if (searchResults->file == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
            result = 0;

            goto cleanup;
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_STORAGE_VOL,
                         _("No storage volume with key or path '%s'"),
                         datastorePath);
            goto cleanup;
        }
    }

    *fileInfo = searchResults->file;
    searchResults->file = NULL;

    result = 0;

  cleanup:
    /* Don't double free fileName */
    if (searchSpec != NULL && searchSpec->matchPattern != NULL) {
        searchSpec->matchPattern->value = NULL;
    }

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3184
    VIR_FREE(directoryAndFileName);
3185 3186 3187 3188 3189 3190 3191
    VIR_FREE(fileName);
    VIR_FREE(datastorePathWithoutFileName);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    esxVI_ManagedObjectReference_Free(&task);
3192
    VIR_FREE(taskInfoErrorMessage);
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216
    esxVI_TaskInfo_Free(&taskInfo);
    esxVI_HostDatastoreBrowserSearchResults_Free(&searchResults);

    return result;
}



int
esxVI_LookupDatastoreContentByDatastoreName
  (esxVI_Context *ctx, const char *datastoreName,
   esxVI_HostDatastoreBrowserSearchResults **searchResultsList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    char *datastorePath = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3217
    char *taskInfoErrorMessage = NULL;
3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
    esxVI_TaskInfo *taskInfo = NULL;

    if (searchResultsList == NULL || *searchResultsList != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    /* Lookup Datastore and HostDatastoreBrowser */
    if (esxVI_String_AppendValueToList(&propertyNameList, "browser") < 0 ||
        esxVI_LookupDatastoreByName(ctx, datastoreName, propertyNameList,
                                    &datastore,
                                    esxVI_Occurrence_RequiredItem) < 0 ||
        esxVI_GetManagedObjectReference(datastore, "browser",
                                        &hostDatastoreBrowser,
                                        esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }

    /* Build HostDatastoreBrowserSearchSpec */
    if (esxVI_HostDatastoreBrowserSearchSpec_Alloc(&searchSpec) < 0 ||
        esxVI_FileQueryFlags_Alloc(&searchSpec->details) < 0) {
        goto cleanup;
    }

    searchSpec->details->fileType = esxVI_Boolean_True;
    searchSpec->details->fileSize = esxVI_Boolean_True;
    searchSpec->details->modification = esxVI_Boolean_False;

    if (esxVI_VmDiskFileQuery_Alloc(&vmDiskFileQuery) < 0 ||
        esxVI_VmDiskFileQueryFlags_Alloc(&vmDiskFileQuery->details) < 0 ||
        esxVI_FileQuery_AppendToList
          (&searchSpec->query,
           esxVI_FileQuery_DynamicCast(vmDiskFileQuery)) < 0) {
        goto cleanup;
    }

    vmDiskFileQuery->details->diskType = esxVI_Boolean_False;
    vmDiskFileQuery->details->capacityKb = esxVI_Boolean_True;
    vmDiskFileQuery->details->hardwareVersion = esxVI_Boolean_False;
    vmDiskFileQuery->details->controllerType = esxVI_Boolean_True;
    vmDiskFileQuery->details->diskExtents = esxVI_Boolean_False;

    if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
        esxVI_FileQuery_AppendToList
          (&searchSpec->query,
           esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
        goto cleanup;
    }

    if (esxVI_FloppyImageFileQuery_Alloc(&floppyImageFileQuery) < 0 ||
        esxVI_FileQuery_AppendToList
          (&searchSpec->query,
           esxVI_FileQuery_DynamicCast(floppyImageFileQuery)) < 0) {
        goto cleanup;
    }

    /* Search datastore for files */
    if (virAsprintf(&datastorePath, "[%s]", datastoreName) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_SearchDatastoreSubFolders_Task(ctx, hostDatastoreBrowser,
                                             datastorePath, searchSpec,
                                             &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3284 3285
                                    esxVI_Boolean_False, &taskInfoState,
                                    &taskInfoErrorMessage) < 0) {
3286 3287 3288 3289 3290
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3291 3292
                     _("Could not serach in datastore '%s': %s"),
                     datastoreName, taskInfoErrorMessage);
3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
        goto cleanup;
    }

    if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo) < 0 ||
        esxVI_HostDatastoreBrowserSearchResults_CastListFromAnyType
          (taskInfo->result, searchResultsList) < 0) {
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    VIR_FREE(datastorePath);
    esxVI_ManagedObjectReference_Free(&task);
3311
    VIR_FREE(taskInfoErrorMessage);
3312 3313 3314 3315 3316 3317 3318
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
int
esxVI_LookupStorageVolumeKeyByDatastorePath(esxVI_Context *ctx,
                                            const char *datastorePath,
                                            char **key)
{
    int result = -1;
    esxVI_FileInfo *fileInfo = NULL;
    char *uuid_string = NULL;

    if (key == NULL || *key != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

3333 3334 3335 3336
    if (ctx->hasQueryVirtualDiskUuid) {
        if (esxVI_LookupFileInfoByDatastorePath
              (ctx, datastorePath, false, &fileInfo,
               esxVI_Occurrence_RequiredItem) < 0) {
3337 3338 3339
            goto cleanup;
        }

3340 3341 3342 3343 3344 3345 3346
        if (esxVI_VmDiskFileInfo_DynamicCast(fileInfo) != NULL) {
            /* VirtualDisks have a UUID, use it as key */
            if (esxVI_QueryVirtualDiskUuid(ctx, datastorePath,
                                           ctx->datacenter->_reference,
                                           &uuid_string) < 0) {
                goto cleanup;
            }
3347

3348 3349 3350 3351 3352 3353 3354 3355
            if (VIR_ALLOC_N(*key, VIR_UUID_STRING_BUFLEN) < 0) {
                virReportOOMError();
                goto cleanup;
            }

            if (esxUtil_ReformatUuid(uuid_string, *key) < 0) {
                goto cleanup;
            }
3356
        }
3357 3358 3359
    }

    if (*key == NULL) {
3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
        /* Other files don't have a UUID, fall back to the path as key */
        if (esxVI_String_DeepCopyValue(key, datastorePath) < 0) {
            goto cleanup;
        }
    }

    result = 0;

  cleanup:
    esxVI_FileInfo_Free(&fileInfo);
    VIR_FREE(uuid_string);

    return result;
}



3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400
int
esxVI_LookupAutoStartDefaults(esxVI_Context *ctx,
                              esxVI_AutoStartDefaults **defaults)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostAutoStartManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (defaults == NULL || *defaults != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    /*
     * Lookup HostAutoStartManagerConfig from the HostAutoStartManager because
     * for some reason this is much faster than looking up the same info from
     * the HostSystem config.
     */
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.defaults") < 0 ||
        esxVI_LookupObjectContentByType
          (ctx, ctx->hostSystem->configManager->autoStartManager,
           "HostAutoStartManager", propertyNameList,
3401
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457
        goto cleanup;
    }

    for (dynamicProperty = hostAutoStartManager->propSet;
         dynamicProperty != NULL; dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.defaults")) {
            if (esxVI_AutoStartDefaults_CastFromAnyType(dynamicProperty->val,
                                                        defaults) < 0) {
                goto cleanup;
            }

            break;
        }
    }

    if (*defaults == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve the AutoStartDefaults object"));
        goto cleanup;
    }

    result = 0;

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

    return result;
}



int
esxVI_LookupAutoStartPowerInfoList(esxVI_Context *ctx,
                                   esxVI_AutoStartPowerInfo **powerInfoList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostAutoStartManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (powerInfoList == NULL || *powerInfoList != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    /*
     * Lookup HostAutoStartManagerConfig from the HostAutoStartManager because
     * for some reason this is much faster than looking up the same info from
     * the HostSystem config.
     */
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.powerInfo") < 0 ||
        esxVI_LookupObjectContentByType
          (ctx, ctx->hostSystem->configManager->autoStartManager,
           "HostAutoStartManager", propertyNameList,
3458
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
        goto cleanup;
    }

    for (dynamicProperty = hostAutoStartManager->propSet;
         dynamicProperty != NULL; dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.powerInfo")) {
            if (esxVI_AutoStartPowerInfo_CastListFromAnyType
                  (dynamicProperty->val, powerInfoList) < 0) {
                goto cleanup;
            }

            break;
        }
    }

    result = 0;

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

    return result;
}



3485 3486
int
esxVI_HandleVirtualMachineQuestion
3487
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
3488
   esxVI_VirtualMachineQuestionInfo *questionInfo,
3489
   esxVI_Boolean autoAnswer, esxVI_Boolean *blocked)
3490
{
M
Matthias Bolte 已提交
3491
    int result = -1;
3492 3493 3494 3495 3496 3497
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

3498 3499 3500 3501 3502 3503 3504
    if (blocked == NULL || *blocked != esxVI_Boolean_Undefined) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    *blocked = esxVI_Boolean_False;

3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524
    if (questionInfo->choice->choiceInfo != NULL) {
        for (elementDescription = questionInfo->choice->choiceInfo;
             elementDescription != NULL;
             elementDescription = elementDescription->_next) {
            virBufferVSprintf(&buffer, "'%s'", elementDescription->label);

            if (elementDescription->_next != NULL) {
                virBufferAddLit(&buffer, ", ");
            }

            if (answerChoice == NULL &&
                questionInfo->choice->defaultIndex != NULL &&
                questionInfo->choice->defaultIndex->value == answerIndex) {
                answerChoice = elementDescription;
            }

            ++answerIndex;
        }

        if (virBufferError(&buffer)) {
3525
            virReportOOMError();
M
Matthias Bolte 已提交
3526
            goto cleanup;
3527 3528 3529 3530 3531 3532 3533
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

    if (autoAnswer == esxVI_Boolean_True) {
        if (possibleAnswers == NULL) {
3534
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3535 3536
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
3537
                         questionInfo->text);
3538 3539

            *blocked = esxVI_Boolean_True;
M
Matthias Bolte 已提交
3540
            goto cleanup;
3541
        } else if (answerChoice == NULL) {
3542
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3543 3544 3545
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s, but no "
                           "default answer is specified"), questionInfo->text,
3546
                         possibleAnswers);
3547 3548

            *blocked = esxVI_Boolean_True;
M
Matthias Bolte 已提交
3549
            goto cleanup;
3550 3551 3552 3553 3554 3555 3556
        }

        VIR_INFO("Pending question blocks virtual machine execution, "
                 "question is '%s', possible answers are %s, responding "
                 "with default answer '%s'", questionInfo->text,
                 possibleAnswers, answerChoice->label);

3557
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
3558
                           answerChoice->key) < 0) {
M
Matthias Bolte 已提交
3559
            goto cleanup;
3560 3561 3562
        }
    } else {
        if (possibleAnswers != NULL) {
3563
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3564 3565
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s"),
3566 3567
                         questionInfo->text, possibleAnswers);
        } else {
3568
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3569 3570
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
3571 3572 3573
                         questionInfo->text);
        }

3574
        *blocked = esxVI_Boolean_True;
M
Matthias Bolte 已提交
3575
        goto cleanup;
3576 3577
    }

M
Matthias Bolte 已提交
3578 3579
    result = 0;

3580
  cleanup:
M
Matthias Bolte 已提交
3581 3582 3583 3584
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

3585 3586 3587 3588 3589 3590 3591
    VIR_FREE(possibleAnswers);

    return result;
}



3592
int
3593
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
3594
                            esxVI_ManagedObjectReference *task,
3595
                            const unsigned char *virtualMachineUuid,
3596
                            esxVI_Occurrence virtualMachineOccurrence,
3597
                            esxVI_Boolean autoAnswer,
3598 3599
                            esxVI_TaskInfoState *finalState,
                            char **errorMessage)
3600
{
M
Matthias Bolte 已提交
3601
    int result = -1;
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;
    esxVI_ManagedObjectReference *propertyFilter = NULL;
    char *version = NULL;
    esxVI_UpdateSet *updateSet = NULL;
    esxVI_PropertyFilterUpdate *propertyFilterUpdate = NULL;
    esxVI_ObjectUpdate *objectUpdate = NULL;
    esxVI_PropertyChange *propertyChange = NULL;
    esxVI_AnyType *propertyValue = NULL;
    esxVI_TaskInfoState state = esxVI_TaskInfoState_Undefined;
3613
    esxVI_Boolean blocked = esxVI_Boolean_Undefined;
3614
    esxVI_TaskInfo *taskInfo = NULL;
3615

3616 3617 3618 3619 3620
    if (errorMessage == NULL || *errorMessage != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

3621 3622 3623
    version = strdup("");

    if (version == NULL) {
3624
        virReportOOMError();
M
Matthias Bolte 已提交
3625
        return -1;
3626 3627
    }

3628
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
3629
        goto cleanup;
3630 3631 3632 3633 3634
    }

    objectSpec->obj = task;
    objectSpec->skip = esxVI_Boolean_False;

3635
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
3636
        goto cleanup;
3637 3638 3639 3640
    }

    propertySpec->type = task->type;

3641
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
3642
                                       "info.state") < 0 ||
3643 3644
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
3645
                                        propertySpec) < 0 ||
3646
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
3647
                                      objectSpec) < 0 ||
3648
        esxVI_CreateFilter(ctx, propertyFilterSpec, esxVI_Boolean_True,
3649
                           &propertyFilter) < 0) {
M
Matthias Bolte 已提交
3650
        goto cleanup;
3651 3652 3653 3654 3655 3656
    }

    while (state != esxVI_TaskInfoState_Success &&
           state != esxVI_TaskInfoState_Error) {
        esxVI_UpdateSet_Free(&updateSet);

3657 3658
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
3659 3660
                  (ctx, virtualMachineUuid, virtualMachineOccurrence,
                   autoAnswer, &blocked) < 0) {
3661 3662 3663 3664 3665
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
3666
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
M
Matthias Bolte 已提交
3667
                    goto cleanup;
3668 3669 3670
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
3671 3672
                    if (esxVI_CancelTask(ctx, task) < 0 &&
                        blocked == esxVI_Boolean_True) {
3673 3674 3675
                        VIR_ERROR0(_("Cancelable task is blocked by an "
                                     "unanswered question but cancelation "
                                     "failed"));
3676
                    }
3677
                } else if (blocked == esxVI_Boolean_True) {
3678 3679
                    VIR_ERROR0(_("Non-cancelable task is blocked by an "
                                 "unanswered question"));
3680 3681 3682 3683
                }

                /* FIXME: Enable error reporting here again */

M
Matthias Bolte 已提交
3684
                goto cleanup;
3685 3686 3687
            }
        }

3688
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
M
Matthias Bolte 已提交
3689
            goto cleanup;
3690 3691 3692 3693 3694 3695
        }

        VIR_FREE(version);
        version = strdup(updateSet->version);

        if (version == NULL) {
3696
            virReportOOMError();
M
Matthias Bolte 已提交
3697
            goto cleanup;
3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
        }

        if (updateSet->filterSet == NULL) {
            continue;
        }

        for (propertyFilterUpdate = updateSet->filterSet;
             propertyFilterUpdate != NULL;
             propertyFilterUpdate = propertyFilterUpdate->_next) {
            for (objectUpdate = propertyFilterUpdate->objectSet;
                 objectUpdate != NULL; objectUpdate = objectUpdate->_next) {
                for (propertyChange = objectUpdate->changeSet;
                     propertyChange != NULL;
                     propertyChange = propertyChange->_next) {
                    if (STREQ(propertyChange->name, "info.state")) {
                        if (propertyChange->op == esxVI_PropertyChangeOp_Add ||
                            propertyChange->op == esxVI_PropertyChangeOp_Assign) {
                            propertyValue = propertyChange->val;
                        } else {
                            propertyValue = NULL;
                        }
                    }
                }
            }
        }

        if (propertyValue == NULL) {
            continue;
        }

3728
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
M
Matthias Bolte 已提交
3729
            goto cleanup;
3730 3731 3732
        }
    }

3733
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
3734 3735 3736
        VIR_DEBUG0("DestroyPropertyFilter failed");
    }

3737
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
M
Matthias Bolte 已提交
3738
        goto cleanup;
3739 3740
    }

3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
    if (*finalState != esxVI_TaskInfoState_Success) {
        if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
            goto cleanup;
        }

        if (taskInfo->error == NULL) {
            *errorMessage = strdup(_("Unknown error"));

            if (*errorMessage == NULL) {
                virReportOOMError();
                goto cleanup;
            }
        } else if (taskInfo->error->localizedMessage == NULL) {
            *errorMessage = strdup(taskInfo->error->fault->_actualType);

            if (*errorMessage == NULL) {
                virReportOOMError();
                goto cleanup;
            }
        } else {
            if (virAsprintf(errorMessage, "%s - %s",
                            taskInfo->error->fault->_actualType,
                            taskInfo->error->localizedMessage) < 0) {
                virReportOOMError();
                goto cleanup;
            }
        }
    }

M
Matthias Bolte 已提交
3770 3771
    result = 0;

3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788
  cleanup:
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
     */
    if (objectSpec != NULL) {
        objectSpec->obj = NULL;
    }

    if (propertySpec != NULL) {
        propertySpec->type = NULL;
    }

    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);
    esxVI_ManagedObjectReference_Free(&propertyFilter);
    VIR_FREE(version);
    esxVI_UpdateSet_Free(&updateSet);
3789
    esxVI_TaskInfo_Free(&taskInfo);
3790 3791 3792

    return result;
}
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816



int
esxVI_ParseHostCpuIdInfo(esxVI_ParsedHostCpuIdInfo *parsedHostCpuIdInfo,
                         esxVI_HostCpuIdInfo *hostCpuIdInfo)
{
    int expectedLength = 39; /* = strlen("----:----:----:----:----:----:----:----"); */
    char *input[4] = { hostCpuIdInfo->eax, hostCpuIdInfo->ebx,
                       hostCpuIdInfo->ecx, hostCpuIdInfo->edx };
    char *output[4] = { parsedHostCpuIdInfo->eax, parsedHostCpuIdInfo->ebx,
                        parsedHostCpuIdInfo->ecx, parsedHostCpuIdInfo->edx };
    const char *name[4] = { "eax", "ebx", "ecx", "edx" };
    int r, i, o;

    memset(parsedHostCpuIdInfo, 0, sizeof (*parsedHostCpuIdInfo));

    parsedHostCpuIdInfo->level = hostCpuIdInfo->level->value;

    for (r = 0; r < 4; ++r) {
        if (strlen(input[r]) != expectedLength) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("HostCpuIdInfo register '%s' has an unexpected length"),
                         name[r]);
M
Matthias Bolte 已提交
3817
            return -1;
3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830
        }

        /* Strip the ':' and invert the "bit" order from 31..0 to 0..31 */
        for (i = 0, o = 31; i < expectedLength; i += 5, o -= 4) {
            output[r][o] = input[r][i];
            output[r][o - 1] = input[r][i + 1];
            output[r][o - 2] = input[r][i + 2];
            output[r][o - 3] = input[r][i + 3];

            if (i + 4 < expectedLength && input[r][i + 4] != ':') {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("HostCpuIdInfo register '%s' has an unexpected format"),
                             name[r]);
M
Matthias Bolte 已提交
3831
                return -1;
3832 3833 3834 3835 3836 3837
            }
        }
    }

    return 0;
}
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874



int
esxVI_ProductVersionToDefaultVirtualHWVersion(esxVI_ProductVersion productVersion)
{
    /*
     * virtualHW.version compatibility matrix:
     *
     *              4 7    API
     *   ESX 3.5    +      2.5
     *   ESX 4.0    + +    4.0
     *   ESX 4.1    + +    4.1
     *   GSX 2.0    + +    2.5
     */
    switch (productVersion) {
      case esxVI_ProductVersion_ESX35:
      case esxVI_ProductVersion_VPX25:
        return 4;

      case esxVI_ProductVersion_GSX20:
      case esxVI_ProductVersion_ESX40:
      case esxVI_ProductVersion_ESX41:
      case esxVI_ProductVersion_VPX40:
      case esxVI_ProductVersion_VPX41:
        return 7;

      case esxVI_ProductVersion_ESX4x:
      case esxVI_ProductVersion_VPX4x:
        return 7;

      default:
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Unexpected product version"));
        return -1;
    }
}