esx_vi.c 116.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 "xml.h"
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#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                                                                       \
51
    esxVI_##_type##_Alloc(esxVI_##_type **ptrptr)                             \
52
    {                                                                         \
53
        return esxVI_Alloc((void **)ptrptr, sizeof(esxVI_##_type));           \
54 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
#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 已提交
88
    VIR_FREE(item->ipAddress);
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

    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);
104 105 106
    esxVI_Datacenter_Free(&item->datacenter);
    esxVI_ComputeResource_Free(&item->computeResource);
    esxVI_HostSystem_Free(&item->hostSystem);
107 108 109 110 111 112
    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);
113 114 115
});

static size_t
M
Matthias Bolte 已提交
116 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
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)
145 146 147 148 149 150 151 152 153 154 155 156 157 158
{
    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 已提交
159 160
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
                 char *info, size_t size, void *data ATTRIBUTE_UNUSED)
161
{
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    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;
    }

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

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

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

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

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

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

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

213 214
    VIR_FREE(buffer);

215 216 217 218
    return 0;
}
#endif

219
static int
220
esxVI_CURL_Perform(esxVI_Context *ctx, const char *url)
221 222 223 224 225 226 227 228 229 230
{
    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) {
231
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
232
                     _("curl_easy_perform() returned an error: %s (%d) : %s"),
233
                     curl_easy_strerror(errorCode), errorCode, ctx->curl_error);
234 235 236 237 238 239 240
        return -1;
    }

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

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

    if (responseCode < 0) {
249 250 251
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned a "
                       "negative response code"));
252 253 254 255 256 257 258 259 260
        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) {
261
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
262 263 264
                         _("curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
                           "an error: %s (%d) : %s"),
                         curl_easy_strerror(errorCode),
265
                         errorCode, ctx->curl_error);
266
        } else {
267
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
268
                         _("The server redirects from '%s' to '%s'"), url,
269 270 271
                         redirectUrl);
        }
#else
272
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
273
                     _("The server redirects from '%s'"), url);
274 275 276 277 278 279 280 281
#endif

        return -1;
    }

    return responseCode;
}

282
int
283
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
M
Matthias Bolte 已提交
284
                      const char *ipAddress, const char *username,
M
Matthias Bolte 已提交
285
                      const char *password, esxUtil_ParsedUri *parsedUri)
286
{
M
Matthias Bolte 已提交
287 288 289
    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) {
290
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
291
        return -1;
292 293
    }

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

    ctx->curl_handle = curl_easy_init();

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

    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) {
322 323
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not build CURL header list"));
324
        return -1;
325 326 327 328 329
    }

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

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

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

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

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

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

375 376 377
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
378
            ctx->apiVersion = esxVI_APIVersion_25;
379
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
380
            ctx->apiVersion = esxVI_APIVersion_40;
M
Matthias Bolte 已提交
381 382 383 384 385 386 387
        } 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);
388
        } else {
389
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
390
                         _("Expecting VI API major/minor version '2.5' or '4.x' "
391
                           "but found '%s'"), ctx->service->about->apiVersion);
392
            return -1;
393
        }
394

395 396 397 398
        if (STREQ(ctx->service->about->productLineId, "gsx")) {
            if (STRPREFIX(ctx->service->about->version, "2.0")) {
                ctx->productVersion = esxVI_ProductVersion_GSX20;
            } else {
399
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
400 401
                             _("Expecting GSX major/minor version '2.0' but "
                               "found '%s'"), ctx->service->about->version);
402
                return -1;
403 404 405 406 407 408 409
            }
        } 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 已提交
410 411 412 413 414 415 416
            } 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);
417
            } else {
418
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
419
                             _("Expecting ESX major/minor version '3.5' or "
M
Matthias Bolte 已提交
420
                               "'4.x' but found '%s'"),
421
                             ctx->service->about->version);
422
                return -1;
423 424 425 426 427 428
            }
        } 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 已提交
429 430 431 432 433 434 435
            } 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);
436
            } else {
437
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
438
                             _("Expecting VPX major/minor version '2.5' or '4.x' "
439
                               "but found '%s'"), ctx->service->about->version);
440
                return -1;
441
            }
442
        } else {
443
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
444 445
                         _("Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                           "or 'vpx' but found '%s'"),
446
                         ctx->service->about->productLineId);
447
            return -1;
448 449
        }
    } else {
450
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
451 452
                     _("Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                       "but found '%s'"), ctx->service->about->apiType);
453
        return -1;
454 455
    }

456 457 458 459 460 461 462 463 464 465 466
    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;
    }

467
    if (esxVI_Login(ctx, username, password, NULL, &ctx->session) < 0 ||
468
        esxVI_BuildSelectSetCollection(ctx) < 0) {
469
        return -1;
470 471
    }

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    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,
496 497
                                        "Datacenter", propertyNameList,
                                        &datacenterList) < 0) {
M
Matthias Bolte 已提交
498
        goto cleanup;
499 500 501
    }

    if (datacenterList == NULL) {
502
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
503
                     _("Could not retrieve datacenter list"));
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 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

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

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

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "name\0"
                                           "host\0"
                                           "resourcePool\0") < 0 ||
        esxVI_LookupObjectContentByType(ctx, ctx->datacenter->hostFolder,
                                        "ComputeResource", propertyNameList,
                                        &computeResourceList) < 0) {
        goto cleanup;
    }

    if (computeResourceList == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve compute resource list"));
        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 已提交
563
                goto cleanup;
564
            }
565 566 567 568

            if (STREQ(name, parsedUri->path_computeResource)) {
                break;
            }
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 594 595 596 597 598

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

601 602 603 604 605 606 607 608 609 610 611
    esxVI_String_Free(&propertyNameList);

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "name\0") < 0 ||
        esxVI_LookupObjectContentByType(ctx, ctx->computeResource->_reference,
                                        "HostSystem", propertyNameList,
                                        &hostSystemList) < 0) {
        goto cleanup;
    }

    if (hostSystemList == NULL) {
612
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
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 642 643 644 645 646 647 648 649 650
                     _("Could not retrieve host system list"));
        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 已提交
651
        goto cleanup;
652 653
    }

M
Matthias Bolte 已提交
654 655
    result = 0;

656 657 658
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datacenterList);
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
    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,
                                           "name\0") < 0 ||
        esxVI_FindByIp(ctx, NULL, hostSystemIpAddress, esxVI_Boolean_False,
                       &managedObjectReference) < 0 ||
        esxVI_LookupObjectContentByType(ctx, managedObjectReference,
                                        "HostSystem", propertyNameList,
683
                                        &hostSystem) < 0) {
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
        goto cleanup;
    }

    if (hostSystem == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve host system"));
        goto cleanup;
    }

    if (esxVI_HostSystem_CastFromObjectContent(hostSystem,
                                               &ctx->hostSystem) < 0) {
        goto cleanup;
    }

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

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "name\0"
                                           "host\0"
                                           "resourcePool\0") < 0 ||
        esxVI_LookupObjectContentByType(ctx, hostSystem->obj,
                                        "ComputeResource", propertyNameList,
                                        &computeResource) < 0) {
        goto cleanup;
    }

    if (computeResource == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve compute resource of host system"));
        goto cleanup;
    }

    if (esxVI_ComputeResource_CastFromObjectContent(computeResource,
                                                    &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,
                                        &datacenter) < 0) {
        goto cleanup;
    }

    if (datacenter == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve datacenter of compute resource"));
        goto cleanup;
    }

    if (esxVI_Datacenter_CastFromObjectContent(datacenter,
                                               &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);
754 755 756 757 758

    return result;
}

int
759
esxVI_Context_DownloadFile(esxVI_Context *ctx, const char *url, char **content)
760 761
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
762
    int responseCode = 0;
763 764

    if (content == NULL || *content != NULL) {
765
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
766
        return -1;
767 768 769 770 771 772
    }

    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 已提交
773
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
774 775
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPGET, 1);

776
    responseCode = esxVI_CURL_Perform(ctx, url);
777

778
    virMutexUnlock(&ctx->curl_lock);
779

780
    if (responseCode < 0) {
M
Matthias Bolte 已提交
781
        goto cleanup;
782
    } else if (responseCode != 200) {
783
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
784
                     _("HTTP response code %d for download from '%s'"),
785
                     responseCode, url);
M
Matthias Bolte 已提交
786
        goto cleanup;
787 788 789
    }

    if (virBufferError(&buffer)) {
790
        virReportOOMError();
M
Matthias Bolte 已提交
791
        goto cleanup;
792 793 794 795
    }

    *content = virBufferContentAndReset(&buffer);

M
Matthias Bolte 已提交
796 797 798 799 800
  cleanup:
    if (*content == NULL) {
        virBufferFreeAndReset(&buffer);
        return -1;
    }
801

M
Matthias Bolte 已提交
802
    return 0;
803 804
}

M
Matthias Bolte 已提交
805
int
806 807
esxVI_Context_UploadFile(esxVI_Context *ctx, const char *url,
                         const char *content)
M
Matthias Bolte 已提交
808
{
809
    int responseCode = 0;
M
Matthias Bolte 已提交
810 811

    if (content == NULL) {
812
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
813 814 815 816 817 818 819 820 821 822
        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));

823
    responseCode = esxVI_CURL_Perform(ctx, url);
M
Matthias Bolte 已提交
824 825 826

    virMutexUnlock(&ctx->curl_lock);

827 828 829
    if (responseCode < 0) {
        return -1;
    } else if (responseCode != 200 && responseCode != 201) {
830
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
831
                     _("HTTP response code %d for upload to '%s'"),
832
                     responseCode, url);
M
Matthias Bolte 已提交
833 834 835 836 837 838
        return -1;
    }

    return 0;
}

839
int
840 841 842
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
843
{
M
Matthias Bolte 已提交
844
    int result = -1;
845 846
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
847 848 849
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
850

851
    if (request == NULL || response == NULL || *response != NULL) {
852
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
853
        return -1;
854 855
    }

856
    if (esxVI_Response_Alloc(response) < 0) {
M
Matthias Bolte 已提交
857
        return -1;
858 859 860 861 862 863
    }

    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 已提交
864
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
865 866
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDSIZE, strlen(request));
867

868
    (*response)->responseCode = esxVI_CURL_Perform(ctx, ctx->url);
869

870
    virMutexUnlock(&ctx->curl_lock);
871

872
    if ((*response)->responseCode < 0) {
M
Matthias Bolte 已提交
873
        goto cleanup;
874 875 876
    }

    if (virBufferError(&buffer)) {
877
        virReportOOMError();
M
Matthias Bolte 已提交
878
        goto cleanup;
879 880
    }

881
    (*response)->content = virBufferContentAndReset(&buffer);
882

883
    if ((*response)->responseCode == 500 || (*response)->responseCode == 200) {
884 885
        (*response)->document = xmlReadDoc(BAD_CAST (*response)->content, "",
                                           NULL, XML_PARSE_NONET);
886

887
        if ((*response)->document == NULL) {
888
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
889
                         _("Response for call to '%s' could not be parsed"),
890
                         methodName);
M
Matthias Bolte 已提交
891
            goto cleanup;
892 893
        }

894
        if (xmlDocGetRootElement((*response)->document) == NULL) {
895
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
896
                         _("Response for call to '%s' is an empty XML document"),
897
                         methodName);
M
Matthias Bolte 已提交
898
            goto cleanup;
899 900
        }

901
        xpathContext = xmlXPathNewContext((*response)->document);
902

903
        if (xpathContext == NULL) {
904 905
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not create XPath context"));
M
Matthias Bolte 已提交
906
            goto cleanup;
907 908
        }

909
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
910
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
911
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
912

913 914
        if ((*response)->responseCode == 500) {
            (*response)->node =
915
              virXPathNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault",
916
                           xpathContext);
917

918
            if ((*response)->node == NULL) {
919
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
920 921
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, XPath evaluation failed"),
922
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
923
                goto cleanup;
924 925
            }

926 927
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
928 929
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, deserialization failed"),
930
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
931
                goto cleanup;
932 933
            }

934
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
935 936
                         _("HTTP response code %d for call to '%s'. "
                           "Fault: %s - %s"), (*response)->responseCode,
937
                         methodName, fault->faultcode, fault->faultstring);
938 939 940 941 942 943

            /* 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 已提交
944
            goto cleanup;
945 946 947 948
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
                            methodName) < 0) {
949
                virReportOOMError();
M
Matthias Bolte 已提交
950
                goto cleanup;
951
            }
952

953
            responseNode = virXPathNode(xpathExpression, xpathContext);
954

955
            if (responseNode == NULL) {
956
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
957 958
                             _("XPath evaluation of response for call to '%s' "
                               "failed"), methodName);
M
Matthias Bolte 已提交
959
                goto cleanup;
960 961
            }

962
            xpathContext->node = responseNode;
963
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
964

965 966
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
967 968
                if ((*response)->node == NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
969 970
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
971
                    goto cleanup;
972 973
                } else if ((*response)->node->next != NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
974 975
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
976
                    goto cleanup;
977 978 979 980 981
                }

                break;

              case esxVI_Occurrence_RequiredList:
982
                if ((*response)->node == NULL) {
983
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
984 985
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
986
                    goto cleanup;
987 988 989 990 991 992 993
                }

                break;

              case esxVI_Occurrence_OptionalItem:
                if ((*response)->node != NULL &&
                    (*response)->node->next != NULL) {
994
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
995 996
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
997
                    goto cleanup;
998 999 1000 1001
                }

                break;

1002
              case esxVI_Occurrence_OptionalList:
1003 1004 1005 1006 1007
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
                if ((*response)->node != NULL) {
1008
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1009 1010
                                 _("Call to '%s' returned something, expecting "
                                   "an empty result"), methodName);
M
Matthias Bolte 已提交
1011
                    goto cleanup;
1012 1013 1014 1015 1016
                }

                break;

              default:
1017 1018
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Invalid argument (occurrence)"));
M
Matthias Bolte 已提交
1019
                goto cleanup;
1020
            }
1021
        }
1022
    } else {
1023
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1024
                     _("HTTP response code %d for call to '%s'"),
1025
                     (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1026
        goto cleanup;
1027 1028
    }

M
Matthias Bolte 已提交
1029 1030
    result = 0;

1031
  cleanup:
M
Matthias Bolte 已提交
1032 1033 1034 1035 1036 1037
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
        esxVI_Response_Free(response);
        esxVI_Fault_Free(&fault);
    }

1038 1039 1040 1041
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
1042 1043 1044 1045 1046
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1047
 * Response
1048 1049
 */

1050 1051
/* esxVI_Response_Alloc */
ESX_VI__TEMPLATE__ALLOC(Response);
1052

1053 1054
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
1055
{
1056
    VIR_FREE(item->content);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

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



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

int
1070
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
1071 1072 1073 1074 1075
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
1076
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1077 1078 1079 1080 1081
        return -1;
    }

    *value = 0; /* undefined */

1082
    if (anyType->type != enumeration->type) {
1083
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1084
                     _("Expecting type '%s' but found '%s'"),
1085 1086
                     esxVI_Type_ToString(enumeration->type),
                     esxVI_Type_ToString(anyType->type));
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        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;
        }
    }

1097
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1098
                 _("Unknown value '%s' for %s"), anyType->value,
1099
                 esxVI_Type_ToString(enumeration->type));
1100 1101 1102 1103 1104

    return -1;
}

int
1105
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
1106
                            int value, const char *element, virBufferPtr output)
1107 1108 1109 1110 1111
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
1112
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1113 1114 1115 1116
        return -1;
    }

    if (value == 0) { /* undefined */
1117
        return 0;
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    }

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

    if (name == NULL) {
1128
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1129 1130 1131
        return -1;
    }

1132 1133
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
1134 1135 1136 1137 1138 1139 1140 1141 1142

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
1143
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
1144 1145 1146
                              xmlNodePtr node, int *value)
{
    int i;
M
Matthias Bolte 已提交
1147
    int result = -1;
1148 1149 1150
    char *name = NULL;

    if (value == NULL) {
1151
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1152
        return -1;
1153 1154 1155 1156
    }

    *value = 0; /* undefined */

1157
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
M
Matthias Bolte 已提交
1158
        return -1;
1159 1160 1161 1162 1163
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(name, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
M
Matthias Bolte 已提交
1164 1165
            result = 0;
            break;
1166 1167 1168
        }
    }

M
Matthias Bolte 已提交
1169 1170 1171 1172
    if (result < 0) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, _("Unknown value '%s' for %s"),
                     name, esxVI_Type_ToString(enumeration->type));
    }
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185

    VIR_FREE(name);

    return result;
}



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

int
1186
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
1187 1188 1189 1190
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
1191
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
        return -1;
    }

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

    next = *list;

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

    next->_next = item;

    return 0;
}

int
1212
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
1213 1214 1215 1216 1217 1218 1219
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
1220
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1221
        return -1;
1222 1223 1224
    }

    for (src = srcList; src != NULL; src = src->_next) {
1225 1226
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
            goto failure;
        }

        dest = NULL;
    }

    return 0;

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

    return -1;
}

1242
int
1243
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
1244 1245 1246
                           esxVI_List_CastFromAnyTypeFunc castFromAnyTypeFunc,
                           esxVI_List_FreeFunc freeFunc)
{
M
Matthias Bolte 已提交
1247
    int result = -1;
1248 1249 1250 1251 1252 1253
    xmlNodePtr childNode = NULL;
    esxVI_AnyType *childAnyType = NULL;
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        castFromAnyTypeFunc == NULL || freeFunc == NULL) {
1254
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1255
        return -1;
1256 1257 1258 1259 1260 1261 1262
    }

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

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
1263
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1264
                     _("Expecting type to begin with 'ArrayOf' but found '%s'"),
1265
                     anyType->other);
1266
        return -1;
1267 1268
    }

1269
    for (childNode = anyType->node->children; childNode != NULL;
1270 1271
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1272
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1273
                         _("Wrong XML element type %d"), childNode->type);
M
Matthias Bolte 已提交
1274
            goto cleanup;
1275 1276 1277 1278
        }

        esxVI_AnyType_Free(&childAnyType);

1279 1280 1281
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
M
Matthias Bolte 已提交
1282
            goto cleanup;
1283 1284 1285 1286 1287
        }

        item = NULL;
    }

M
Matthias Bolte 已提交
1288 1289
    result = 0;

1290
  cleanup:
M
Matthias Bolte 已提交
1291 1292 1293 1294 1295
    if (result < 0) {
        freeFunc(&item);
        freeFunc(list);
    }

1296 1297 1298 1299 1300
    esxVI_AnyType_Free(&childAnyType);

    return result;
}

1301
int
1302
esxVI_List_Serialize(esxVI_List *list, const char *element,
1303
                     virBufferPtr output,
1304 1305 1306 1307 1308
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
1309
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1310 1311 1312 1313
        return -1;
    }

    if (list == NULL) {
1314
        return 0;
1315 1316 1317
    }

    for (item = list; item != NULL; item = item->_next) {
1318
        if (serializeFunc(item, element, output) < 0) {
1319 1320 1321 1322 1323 1324 1325 1326
            return -1;
        }
    }

    return 0;
}

int
1327
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1328 1329 1330 1331 1332 1333 1334
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
1335
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1336 1337 1338 1339 1340 1341 1342 1343 1344
        return -1;
    }

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

    for (; node != NULL; node = node->next) {
        if (node->type != XML_ELEMENT_NODE) {
1345
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1346
                         _("Wrong XML element type %d"), node->type);
1347 1348 1349
            goto failure;
        }

1350 1351
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1352 1353 1354
            goto failure;
        }

1355
        item = NULL;
1356 1357 1358 1359 1360
    }

    return 0;

  failure:
1361
    freeFunc(&item);
1362 1363 1364 1365 1366 1367 1368 1369 1370
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1371 1372 1373 1374
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1375 1376 1377
 */

int
1378
esxVI_Alloc(void **ptrptr, size_t size)
1379 1380
{
    if (ptrptr == NULL || *ptrptr != NULL) {
1381
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1382 1383 1384 1385
        return -1;
    }

    if (virAllocN(ptrptr, size, 1) < 0) {
1386
        virReportOOMError();
1387 1388 1389 1390 1391 1392
        return -1;
    }

    return 0;
}

1393 1394


1395
int
1396 1397 1398
esxVI_BuildSelectSet(esxVI_SelectionSpec **selectSet,
                     const char *name, const char *type,
                     const char *path, const char *selectSetNames)
1399 1400 1401 1402 1403
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

1404 1405 1406 1407 1408
    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.
         */
1409
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1410 1411 1412
        return -1;
    }

1413
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1414
        esxVI_String_DeepCopyValue(&traversalSpec->name, name) < 0 ||
1415 1416
        esxVI_String_DeepCopyValue(&traversalSpec->type, type) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->path, path) < 0) {
1417 1418 1419 1420 1421 1422 1423 1424 1425
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

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

        while (currentSelectSetName != NULL && *currentSelectSetName != '\0') {
1426 1427
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
                esxVI_String_DeepCopyValue(&selectionSpec->name,
1428
                                           currentSelectSetName) < 0 ||
1429
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1430 1431 1432 1433
                                                 selectionSpec) < 0) {
                goto failure;
            }

1434
            selectionSpec = NULL;
1435 1436 1437 1438
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1439
    if (esxVI_SelectionSpec_AppendToList(selectSet,
1440 1441
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1442 1443 1444 1445 1446 1447 1448
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);
1449
    esxVI_SelectionSpec_Free(&selectionSpec);
1450 1451 1452 1453 1454 1455

    return -1;
}


int
1456
esxVI_BuildSelectSetCollection(esxVI_Context *ctx)
1457
{
1458
    /* Folder -> childEntity (ManagedEntity) */
1459 1460 1461 1462 1463
    if (esxVI_BuildSelectSet(&ctx->selectSet_folderToChildEntity,
                             "folderToChildEntity",
                             "Folder", "childEntity",
                             "folderToChildEntity\0") < 0) {
        return -1;
1464 1465
    }

1466
    /* ComputeResource -> host (HostSystem) */
1467 1468 1469 1470
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToHost,
                             "computeResourceToHost",
                             "ComputeResource", "host", NULL) < 0) {
        return -1;
1471 1472
    }

1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    /* 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;
    }*/
1488

1489 1490 1491 1492 1493 1494
    /* ResourcePool -> vm (VirtualMachine) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_resourcePoolToVm,
                             "resourcePoolToVm",
                             "ResourcePool", "vm", NULL) < 0) {
        return -1;
    }*/
1495

1496
    /* HostSystem -> parent (ComputeResource) */
1497 1498 1499 1500
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToParent,
                             "hostSystemToParent",
                             "HostSystem", "parent", NULL) < 0) {
        return -1;
1501 1502
    }

1503
    /* HostSystem -> vm (VirtualMachine) */
1504 1505 1506 1507
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToVm,
                             "hostSystemToVm",
                             "HostSystem", "vm", NULL) < 0) {
        return -1;
1508 1509
    }

1510
    /* HostSystem -> datastore (Datastore) */
1511 1512 1513 1514
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToDatastore,
                             "hostSystemToDatastore",
                             "HostSystem", "datastore", NULL) < 0) {
        return -1;
1515 1516
    }

1517 1518 1519 1520 1521 1522
    /* Folder -> parent (Folder, Datacenter) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "managedEntityToParent",
                             "ManagedEntity", "parent", NULL) < 0) {
        return -1;
    }
1523

1524 1525 1526 1527 1528 1529 1530
    /* ComputeResource -> parent (Folder) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "computeResourceToParent",
                             "ComputeResource", "parent",
                             "managedEntityToParent\0") < 0) {
        return -1;
    }
1531

1532
    return 0;
1533 1534 1535 1536 1537 1538 1539 1540 1541
}


/*
 * Can't use the SessionIsActive() function here, because at least
 * 'ESX Server 3.5.0 build-64607' returns an 'method not implemented' fault if
 * you try to call it. Query the session manager for the current session of
 * this connection instead and re-login if there is no current session for this
 * connection.
1542 1543
 *
 * Update: 'ESX 4.0.0 build-171294' doesn't implement this method.
1544 1545 1546 1547
 */
#define ESX_VI_USE_SESSION_IS_ACTIVE 0

int
1548
esxVI_EnsureSession(esxVI_Context *ctx)
1549 1550 1551 1552
{
#if ESX_VI_USE_SESSION_IS_ACTIVE
    esxVI_Boolean active = esxVI_Boolean_Undefined;
#else
M
Matthias Bolte 已提交
1553
    int result = -1;
1554 1555 1556 1557 1558 1559 1560
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;
#endif

    if (ctx->session == NULL) {
1561
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
1562 1563 1564 1565
        return -1;
    }

#if ESX_VI_USE_SESSION_IS_ACTIVE
1566 1567
    if (esxVI_SessionIsActive(ctx, ctx->session->key, ctx->session->userName,
                              &active) < 0) {
1568 1569 1570 1571 1572 1573
        return -1;
    }

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

1574
        if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
1575 1576 1577 1578
                        &ctx->session) < 0) {
            return -1;
        }
    }
1579 1580

    return 0;
1581
#else
1582
    if (esxVI_String_AppendValueToList(&propertyNameList,
1583
                                       "currentSession") < 0 ||
1584
        esxVI_LookupObjectContentByType(ctx, ctx->service->sessionManager,
1585 1586
                                        "SessionManager", propertyNameList,
                                        &sessionManager) < 0) {
M
Matthias Bolte 已提交
1587
        goto cleanup;
1588 1589 1590 1591 1592
    }

    for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "currentSession")) {
1593
            if (esxVI_UserSession_CastFromAnyType(dynamicProperty->val,
1594
                                                  &currentSession) < 0) {
M
Matthias Bolte 已提交
1595
                goto cleanup;
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
            }

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

    if (currentSession == NULL) {
        esxVI_UserSession_Free(&ctx->session);

1607 1608
        if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                        &ctx->session) < 0) {
M
Matthias Bolte 已提交
1609
            goto cleanup;
1610 1611
        }
    } else if (STRNEQ(ctx->session->key, currentSession->key)) {
1612 1613 1614
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Key of the current session differs from the key at "
                       "last login"));
M
Matthias Bolte 已提交
1615
        goto cleanup;
1616 1617
    }

M
Matthias Bolte 已提交
1618 1619
    result = 0;

1620 1621 1622 1623 1624 1625
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);

    return result;
1626
#endif
1627 1628 1629 1630 1631
}



int
1632
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
1633 1634 1635 1636
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
                                esxVI_ObjectContent **objectContentList)
1637
{
M
Matthias Bolte 已提交
1638
    int result = -1;
1639 1640 1641 1642
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

1643 1644 1645 1646 1647
    if (objectContentList == NULL || *objectContentList != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

1648
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
1649
        return -1;
1650 1651 1652 1653 1654
    }

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

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
    if (STRNEQ(root->type, type)) {
        if (STREQ(root->type, "Folder")) {
            if (STREQ(type, "Datacenter") || STREQ(type, "ComputeResource")) {
                objectSpec->selectSet = ctx->selectSet_folderToChildEntity;
            } else {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("Invalid lookup of '%s' from '%s'"),
                             type, root->type);
                goto cleanup;
            }
        } else if (STREQ(root->type, "ComputeResource")) {
            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")) {
            if (STREQ(type, "ComputeResource")) {
                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;
        }
1694 1695
    }

1696
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
1697
        goto cleanup;
1698 1699 1700 1701 1702
    }

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

1703 1704
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
1705
                                        propertySpec) < 0 ||
1706
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
1707
                                      objectSpec) < 0) {
M
Matthias Bolte 已提交
1708
        goto cleanup;
1709 1710
    }

1711
    result = esxVI_RetrieveProperties(ctx, propertyFilterSpec,
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
                                      objectContentList);

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



1736
int
1737
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
1738 1739 1740 1741 1742 1743 1744 1745 1746
                             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
1747
                     (dynamicProperty->val, managedEntityStatus);
1748 1749 1750
        }
    }

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

    return -1;
}



1760
int
1761
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
1762 1763 1764 1765 1766 1767 1768 1769
                                  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
1770
                     (dynamicProperty->val, powerState);
1771 1772 1773
        }
    }

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

    return -1;
}



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

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

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

    return 0;
}



1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
int
esxVI_GetBoolean(esxVI_ObjectContent *objectContent, const char *propertyName,
                 esxVI_Boolean *value, esxVI_Occurrence occurence)
{
    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 &&
        occurence == esxVI_Occurrence_RequiredItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



int
esxVI_GetStringValue(esxVI_ObjectContent *objectContent,
                     const char *propertyName,
                     char **value, esxVI_Occurrence occurence)
{
    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;
        }
    }

    if (*value == NULL && occurence == esxVI_Occurrence_RequiredItem) {
        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,
                                esxVI_Occurrence occurence)
{
    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;
        }
    }

    if (*value == NULL && occurence == esxVI_Occurrence_RequiredItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



1917
int
1918
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
1919 1920
                                        esxVI_VirtualMachinePowerState powerState,
                                        esxVI_Boolean inverse)
1921
{
M
Matthias Bolte 已提交
1922
    bool success = false;
1923 1924 1925 1926 1927
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
M
Matthias Bolte 已提交
1928
    int count = 0;
1929

1930
    if (esxVI_String_AppendValueToList(&propertyNameList,
1931
                                       "runtime.powerState") < 0 ||
1932 1933
        esxVI_LookupVirtualMachineList(ctx, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1934
        goto cleanup;
1935 1936 1937 1938 1939 1940 1941 1942 1943
    }

    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
1944
                      (dynamicProperty->val, &powerState_) < 0) {
M
Matthias Bolte 已提交
1945
                    goto cleanup;
1946 1947 1948 1949 1950 1951
                }

                if ((inverse != esxVI_Boolean_True &&
                     powerState_ == powerState) ||
                    (inverse == esxVI_Boolean_True &&
                     powerState_ != powerState)) {
M
Matthias Bolte 已提交
1952
                    count++;
1953 1954 1955 1956 1957 1958 1959
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

M
Matthias Bolte 已提交
1960 1961
    success = true;

1962 1963 1964 1965
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1966
    return success ? count : -1;
1967 1968 1969 1970 1971
}



int
1972
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
1973 1974 1975 1976
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
1977
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
1978 1979

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
1980 1981
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("ObjectContent does not reference a virtual machine"));
1982 1983 1984 1985 1986 1987
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
1988
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1989
                         _("Could not parse positive integer from '%s'"),
1990 1991 1992 1993 1994 1995 1996
                         virtualMachine->obj->value);
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
1997
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1998 1999 2000 2001 2002 2003 2004
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2005
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2006 2007 2008 2009 2010 2011 2012
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

                if (*name == NULL) {
2013
                    virReportOOMError();
2014 2015 2016 2017 2018 2019 2020 2021
                    goto failure;
                }

                break;
            }
        }

        if (*name == NULL) {
2022 2023
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not get name of virtual machine"));
2024 2025 2026 2027 2028
            goto failure;
        }
    }

    if (uuid != NULL) {
2029
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
2030 2031 2032 2033 2034 2035 2036 2037 2038
                                         &configStatus) < 0) {
            goto failure;
        }

        if (configStatus == esxVI_ManagedEntityStatus_Green) {
            for (dynamicProperty = virtualMachine->propSet;
                 dynamicProperty != NULL;
                 dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "config.uuid")) {
2039
                    if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2040 2041 2042 2043 2044 2045
                                                 esxVI_Type_String) < 0) {
                        goto failure;
                    }

                    uuid_string = dynamicProperty->val->string;
                    break;
2046
                }
2047
            }
2048

2049
            if (uuid_string == NULL) {
2050 2051
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Could not get UUID of virtual machine"));
2052
                goto failure;
2053 2054
            }

2055
            if (virUUIDParse(uuid_string, uuid) < 0) {
2056
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2057
                             _("Could not parse UUID from string '%s'"),
2058 2059 2060 2061 2062
                             uuid_string);
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
2063

2064 2065
            VIR_WARN0("Cannot access UUID, because 'configStatus' property "
                      "indicates a config problem");
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
        }
    }

    return 0;

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

    return -1;
}



2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 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
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;
}



2227 2228 2229
int esxVI_LookupHostSystemProperties(esxVI_Context *ctx,
                                     esxVI_String *propertyNameList,
                                     esxVI_ObjectContent **hostSystem)
M
Matthias Bolte 已提交
2230
{
2231 2232
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "HostSystem", propertyNameList,
2233
                                           hostSystem);
M
Matthias Bolte 已提交
2234 2235 2236 2237
}



2238
int
2239 2240 2241
esxVI_LookupVirtualMachineList(esxVI_Context *ctx,
                               esxVI_String *propertyNameList,
                               esxVI_ObjectContent **virtualMachineList)
2242
{
2243 2244 2245 2246 2247
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource->resourcePool
     *        for cluster support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "VirtualMachine", propertyNameList,
                                           virtualMachineList);
2248 2249 2250 2251 2252
}



int
2253
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
2254
                                 esxVI_String *propertyNameList,
2255
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
2256
                                 esxVI_Occurrence occurrence)
2257
{
M
Matthias Bolte 已提交
2258
    int result = -1;
2259
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
2260
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
2261 2262

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2263
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2264 2265 2266
        return -1;
    }

2267 2268
    virUUIDFormat(uuid, uuid_string);

2269 2270
    if (esxVI_FindByUuid(ctx, ctx->datacenter->_reference, uuid_string,
                         esxVI_Boolean_True, &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2271
        return -1;
2272 2273
    }

2274
    if (managedObjectReference == NULL) {
M
Matthias Bolte 已提交
2275
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2276 2277 2278
            result = 0;

            goto cleanup;
2279
        } else {
2280
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2281 2282
                         _("Could not find domain with UUID '%s'"),
                         uuid_string);
M
Matthias Bolte 已提交
2283
            goto cleanup;
2284 2285 2286
        }
    }

2287
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2288 2289
                                        "VirtualMachine", propertyNameList,
                                        virtualMachine) < 0) {
M
Matthias Bolte 已提交
2290
        goto cleanup;
2291 2292
    }

M
Matthias Bolte 已提交
2293 2294
    result = 0;

2295 2296 2297 2298
  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
M
Matthias Bolte 已提交
2299 2300 2301 2302
}



2303 2304 2305 2306 2307 2308
int
esxVI_LookupVirtualMachineByName(esxVI_Context *ctx, const char *name,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2309
    int result = -1;
2310 2311 2312 2313 2314 2315
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate = NULL;

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2316
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2317 2318 2319 2320 2321 2322
        return -1;
    }

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
2323 2324
        esxVI_LookupVirtualMachineList(ctx, completePropertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2325
        goto cleanup;
2326 2327 2328 2329 2330 2331 2332 2333
    }

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

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
M
Matthias Bolte 已提交
2334
            goto cleanup;
2335 2336 2337 2338 2339 2340 2341
        }

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

        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0) {
M
Matthias Bolte 已提交
2342
            goto cleanup;
2343 2344 2345 2346 2347 2348 2349
        }

        break;
    }

    if (*virtualMachine == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2350 2351 2352
            result = 0;

            goto cleanup;
2353 2354
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2355
                         _("Could not find domain with name '%s'"), name);
M
Matthias Bolte 已提交
2356
            goto cleanup;
2357 2358 2359
        }
    }

M
Matthias Bolte 已提交
2360 2361
    result = 0;

2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;
}



2372 2373
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2374
  (esxVI_Context *ctx, const unsigned char *uuid,
2375 2376 2377
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
   esxVI_Boolean autoAnswer)
{
M
Matthias Bolte 已提交
2378
    int result = -1;
2379 2380 2381
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;
2382
    esxVI_Boolean blocked = esxVI_Boolean_Undefined;
2383

2384
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2385
                                  propertyNameList) < 0 ||
2386
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2387 2388
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2389
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2390
                                         virtualMachine,
M
Matthias Bolte 已提交
2391
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2392
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
2393 2394
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
2395
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
M
Matthias Bolte 已提交
2396
        goto cleanup;
2397 2398 2399
    }

    if (questionInfo != NULL &&
2400
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
2401 2402
                                           questionInfo, autoAnswer,
                                           &blocked) < 0) {
M
Matthias Bolte 已提交
2403
        goto cleanup;
2404 2405 2406
    }

    if (pendingTaskInfoList != NULL) {
2407 2408
        ESX_VI_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                     _("Other tasks are pending for this domain"));
M
Matthias Bolte 已提交
2409
        goto cleanup;
2410 2411
    }

M
Matthias Bolte 已提交
2412 2413
    result = 0;

2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;
}



2424 2425 2426 2427 2428 2429 2430 2431
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,
2432
                                           datastoreList);
2433 2434 2435 2436
}



M
Matthias Bolte 已提交
2437
int
2438 2439
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
2440
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
2441
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
2442
{
M
Matthias Bolte 已提交
2443
    int result = -1;
M
Matthias Bolte 已提交
2444 2445 2446
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
2447
    char *name_candidate;
M
Matthias Bolte 已提交
2448 2449

    if (datastore == NULL || *datastore != NULL) {
2450
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
2451 2452 2453 2454
        return -1;
    }

    /* Get all datastores */
2455
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
2456
                                  propertyNameList) < 0 ||
2457 2458
        esxVI_String_AppendValueToList(&completePropertyNameList,
                                       "summary.name") < 0 ||
2459 2460
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
M
Matthias Bolte 已提交
2461
        goto cleanup;
M
Matthias Bolte 已提交
2462 2463
    }

2464 2465 2466 2467 2468 2469 2470
    /* 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 已提交
2471
            goto cleanup;
M
Matthias Bolte 已提交
2472
        }
2473 2474 2475 2476 2477 2478

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

2479 2480 2481 2482
            /* Found datastore with matching name */
            result = 0;

            goto cleanup;
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
        }
    }

    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 已提交
2529 2530 2531 2532 2533
    }

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

M
Matthias Bolte 已提交
2536 2537
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
2538 2539 2540
            if (STREQ(dynamicProperty->name, "host")) {
                if (esxVI_DatastoreHostMount_CastListFromAnyType
                      (dynamicProperty->val, &datastoreHostMountList) < 0) {
M
Matthias Bolte 已提交
2541
                    goto cleanup;
2542 2543 2544 2545 2546 2547
                }

                break;
            }
        }

2548 2549
        if (datastoreHostMountList == NULL) {
            continue;
2550 2551
        }

2552 2553 2554 2555 2556 2557 2558
        for (datastoreHostMount = datastoreHostMountList;
             datastoreHostMount != NULL;
             datastoreHostMount = datastoreHostMount->_next) {
            if (STRNEQ(ctx->hostSystem->_reference->value,
                       datastoreHostMount->key->value)) {
                continue;
            }
2559

2560 2561
            if (STRPREFIX(absolutePath, datastoreHostMount->mountInfo->path)) {
                if (esxVI_ObjectContent_DeepCopy(datastore, candidate) < 0) {
M
Matthias Bolte 已提交
2562
                    goto cleanup;
M
Matthias Bolte 已提交
2563 2564
                }

2565
                /* Found datastore with matching mount path */
2566 2567 2568
                result = 0;

                goto cleanup;
M
Matthias Bolte 已提交
2569 2570 2571 2572
            }
        }
    }

2573 2574 2575 2576
    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 已提交
2577
        goto cleanup;
M
Matthias Bolte 已提交
2578 2579
    }

M
Matthias Bolte 已提交
2580 2581
    result = 0;

M
Matthias Bolte 已提交
2582 2583 2584
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
2585
    esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
M
Matthias Bolte 已提交
2586 2587

    return result;
2588 2589 2590 2591
}



2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
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",
2611
                                        propertyNameList, &objectContent) < 0) {
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
        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;
}


2659 2660 2661 2662
int
esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
                           esxVI_ManagedObjectReference *task,
                           esxVI_TaskInfo **taskInfo)
2663
{
M
Matthias Bolte 已提交
2664
    int result = -1;
2665 2666 2667 2668 2669
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (taskInfo == NULL || *taskInfo != NULL) {
2670
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2671 2672 2673
        return -1;
    }

2674 2675
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
2676
                                        &objectContent) < 0) {
M
Matthias Bolte 已提交
2677
        goto cleanup;
2678 2679 2680 2681 2682
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
2683
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
2684
                                               taskInfo) < 0) {
M
Matthias Bolte 已提交
2685
                goto cleanup;
2686 2687 2688 2689 2690 2691 2692 2693
            }

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

M
Matthias Bolte 已提交
2694 2695
    result = 0;

2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);

    return result;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
2707
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
2708 2709
   esxVI_TaskInfo **pendingTaskInfoList)
{
M
Matthias Bolte 已提交
2710
    int result = -1;
2711 2712 2713 2714 2715 2716 2717
    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) {
2718
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2719 2720 2721 2722 2723 2724 2725 2726
        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
2727
                  (dynamicProperty->val, &recentTaskList) < 0) {
M
Matthias Bolte 已提交
2728
                goto cleanup;
2729 2730 2731 2732 2733 2734 2735 2736 2737
            }

            break;
        }
    }

    /* Lookup task info for each task */
    for (recentTask = recentTaskList; recentTask != NULL;
         recentTask = recentTask->_next) {
2738
        if (esxVI_LookupTaskInfoByTask(ctx, recentTask, &taskInfo) < 0) {
M
Matthias Bolte 已提交
2739
            goto cleanup;
2740 2741 2742 2743
        }

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
2744
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
2745
                                            taskInfo) < 0) {
M
Matthias Bolte 已提交
2746
                goto cleanup;
2747 2748 2749 2750 2751 2752 2753 2754
            }

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

M
Matthias Bolte 已提交
2755 2756
    result = 0;

2757
  cleanup:
M
Matthias Bolte 已提交
2758 2759 2760 2761
    if (result < 0) {
        esxVI_TaskInfo_Free(pendingTaskInfoList);
    }

2762 2763 2764 2765 2766 2767 2768 2769 2770 2771
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



int
2772
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
2773
                                            const unsigned char *uuid,
2774 2775 2776
                                            esxVI_Occurrence occurrence,
                                            esxVI_Boolean autoAnswer,
                                            esxVI_Boolean *blocked)
2777
{
M
Matthias Bolte 已提交
2778
    int result = -1;
2779 2780 2781 2782
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

2783
    if (esxVI_String_AppendValueToList(&propertyNameList,
2784
                                       "runtime.question") < 0 ||
2785
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
2786
                                         &virtualMachine, occurrence) < 0) {
M
Matthias Bolte 已提交
2787
        goto cleanup;
2788 2789
    }

2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
    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;
        }
2802 2803
    }

M
Matthias Bolte 已提交
2804 2805
    result = 0;

2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);

    return result;
}



2816 2817 2818 2819 2820
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
M
Matthias Bolte 已提交
2821
    int result = -1;
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
    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 已提交
2836
        goto cleanup;
2837 2838 2839 2840 2841 2842 2843
    }

    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 已提交
2844
                goto cleanup;
2845 2846 2847 2848 2849 2850 2851 2852
            }

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

M
Matthias Bolte 已提交
2853 2854
    result = 0;

2855
  cleanup:
M
Matthias Bolte 已提交
2856 2857 2858 2859
    if (result < 0) {
        esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);
    }

2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
    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 已提交
2874
    int result = -1;
2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
    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 已提交
2893
        goto cleanup;
2894 2895 2896 2897 2898 2899 2900
    }

    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 已提交
2901
                goto cleanup;
2902 2903 2904 2905
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
2906
                goto cleanup;
2907 2908 2909 2910 2911 2912 2913 2914
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (currentSnapshot == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2915 2916 2917
            result = 0;

            goto cleanup;
2918 2919 2920
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                         _("Domain has no current snapshot"));
M
Matthias Bolte 已提交
2921
            goto cleanup;
2922 2923 2924 2925 2926 2927
        }
    }

    if (rootSnapshotTreeList == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not lookup root snapshot list"));
M
Matthias Bolte 已提交
2928
        goto cleanup;
2929 2930 2931 2932 2933 2934
    }

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

M
Matthias Bolte 已提交
2938 2939
    result = 0;

2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



2951 2952 2953
int
esxVI_LookupFileInfoByDatastorePath(esxVI_Context *ctx,
                                    const char *datastorePath,
2954
                                    bool lookupFolder,
2955 2956 2957 2958 2959 2960
                                    esxVI_FileInfo **fileInfo,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    char *datastoreName = NULL;
    char *directoryName = NULL;
2961
    char *directoryAndFileName = NULL;
2962
    char *fileName = NULL;
2963
    size_t length;
2964 2965 2966 2967 2968
    char *datastorePathWithoutFileName = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
2969
    esxVI_FolderFileQuery *folderFileQuery = NULL;
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
    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,
2984
                                   &directoryName, &directoryAndFileName) < 0) {
2985 2986 2987
        goto cleanup;
    }

2988 2989 2990 2991 2992
    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.
         */
2993 2994 2995 2996 2997
        if (virAsprintf(&datastorePathWithoutFileName, "[%s]",
                        datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
2998 2999 3000 3001

        if (esxVI_String_DeepCopyValue(&fileName, directoryAndFileName) < 0) {
            goto cleanup;
        }
3002 3003 3004 3005 3006 3007
    } else {
        if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s",
                        datastoreName, directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022

        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;
        }
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
    }

    /* 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;

3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
    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;
        }
3061

3062 3063 3064 3065 3066
        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;
3067

3068 3069 3070 3071 3072 3073
        if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
            goto cleanup;
        }
3074

3075 3076 3077 3078 3079 3080
        if (esxVI_FloppyImageFileQuery_Alloc(&floppyImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(floppyImageFileQuery)) < 0) {
            goto cleanup;
        }
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136
    }

    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,
                                    esxVI_Boolean_False, &taskInfoState) < 0) {
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not serach in datastore '%s'"), datastoreName);
        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);
3137
    VIR_FREE(directoryAndFileName);
3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 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
    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);
    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;
    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,
                                    esxVI_Boolean_False, &taskInfoState) < 0) {
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not serach in datastore '%s'"), datastoreName);
        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);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
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;
    }

3281 3282 3283 3284
    if (ctx->hasQueryVirtualDiskUuid) {
        if (esxVI_LookupFileInfoByDatastorePath
              (ctx, datastorePath, false, &fileInfo,
               esxVI_Occurrence_RequiredItem) < 0) {
3285 3286 3287
            goto cleanup;
        }

3288 3289 3290 3291 3292 3293 3294
        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;
            }
3295

3296 3297 3298 3299 3300 3301 3302 3303
            if (VIR_ALLOC_N(*key, VIR_UUID_STRING_BUFLEN) < 0) {
                virReportOOMError();
                goto cleanup;
            }

            if (esxUtil_ReformatUuid(uuid_string, *key) < 0) {
                goto cleanup;
            }
3304
        }
3305 3306 3307
    }

    if (*key == NULL) {
3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
        /* 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;
}



3325 3326
int
esxVI_HandleVirtualMachineQuestion
3327
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
3328
   esxVI_VirtualMachineQuestionInfo *questionInfo,
3329
   esxVI_Boolean autoAnswer, esxVI_Boolean *blocked)
3330
{
M
Matthias Bolte 已提交
3331
    int result = -1;
3332 3333 3334 3335 3336 3337
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

3338 3339 3340 3341 3342 3343 3344
    if (blocked == NULL || *blocked != esxVI_Boolean_Undefined) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    *blocked = esxVI_Boolean_False;

3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
    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)) {
3365
            virReportOOMError();
M
Matthias Bolte 已提交
3366
            goto cleanup;
3367 3368 3369 3370 3371 3372 3373
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

    if (autoAnswer == esxVI_Boolean_True) {
        if (possibleAnswers == NULL) {
3374
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3375 3376
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
3377
                         questionInfo->text);
3378 3379

            *blocked = esxVI_Boolean_True;
M
Matthias Bolte 已提交
3380
            goto cleanup;
3381
        } else if (answerChoice == NULL) {
3382
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3383 3384 3385
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s, but no "
                           "default answer is specified"), questionInfo->text,
3386
                         possibleAnswers);
3387 3388

            *blocked = esxVI_Boolean_True;
M
Matthias Bolte 已提交
3389
            goto cleanup;
3390 3391 3392 3393 3394 3395 3396
        }

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

3397
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
3398
                           answerChoice->key) < 0) {
M
Matthias Bolte 已提交
3399
            goto cleanup;
3400 3401 3402
        }
    } else {
        if (possibleAnswers != NULL) {
3403
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3404 3405
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s"),
3406 3407
                         questionInfo->text, possibleAnswers);
        } else {
3408
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3409 3410
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
3411 3412 3413
                         questionInfo->text);
        }

3414
        *blocked = esxVI_Boolean_True;
M
Matthias Bolte 已提交
3415
        goto cleanup;
3416 3417
    }

M
Matthias Bolte 已提交
3418 3419
    result = 0;

3420
  cleanup:
M
Matthias Bolte 已提交
3421 3422 3423 3424
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

3425 3426 3427 3428 3429 3430 3431
    VIR_FREE(possibleAnswers);

    return result;
}



3432
int
3433
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
3434
                            esxVI_ManagedObjectReference *task,
3435
                            const unsigned char *virtualMachineUuid,
3436
                            esxVI_Occurrence virtualMachineOccurrence,
3437
                            esxVI_Boolean autoAnswer,
3438 3439
                            esxVI_TaskInfoState *finalState)
{
M
Matthias Bolte 已提交
3440
    int result = -1;
3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451
    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;
3452
    esxVI_Boolean blocked = esxVI_Boolean_Undefined;
3453
    esxVI_TaskInfo *taskInfo = NULL;
3454 3455 3456 3457

    version = strdup("");

    if (version == NULL) {
3458
        virReportOOMError();
M
Matthias Bolte 已提交
3459
        return -1;
3460 3461
    }

3462
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
3463
        goto cleanup;
3464 3465 3466 3467 3468
    }

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

3469
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
3470
        goto cleanup;
3471 3472 3473 3474
    }

    propertySpec->type = task->type;

3475
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
3476
                                       "info.state") < 0 ||
3477 3478
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
3479
                                        propertySpec) < 0 ||
3480
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
3481
                                      objectSpec) < 0 ||
3482
        esxVI_CreateFilter(ctx, propertyFilterSpec, esxVI_Boolean_True,
3483
                           &propertyFilter) < 0) {
M
Matthias Bolte 已提交
3484
        goto cleanup;
3485 3486 3487 3488 3489 3490
    }

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

3491 3492
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
3493 3494
                  (ctx, virtualMachineUuid, virtualMachineOccurrence,
                   autoAnswer, &blocked) < 0) {
3495 3496 3497 3498 3499
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
3500
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
M
Matthias Bolte 已提交
3501
                    goto cleanup;
3502 3503 3504
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
3505 3506
                    if (esxVI_CancelTask(ctx, task) < 0 &&
                        blocked == esxVI_Boolean_True) {
3507 3508 3509
                        VIR_ERROR0(_("Cancelable task is blocked by an "
                                     "unanswered question but cancelation "
                                     "failed"));
3510
                    }
3511
                } else if (blocked == esxVI_Boolean_True) {
3512 3513
                    VIR_ERROR0(_("Non-cancelable task is blocked by an "
                                 "unanswered question"));
3514 3515 3516 3517
                }

                /* FIXME: Enable error reporting here again */

M
Matthias Bolte 已提交
3518
                goto cleanup;
3519 3520 3521
            }
        }

3522
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
M
Matthias Bolte 已提交
3523
            goto cleanup;
3524 3525 3526 3527 3528 3529
        }

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

        if (version == NULL) {
3530
            virReportOOMError();
M
Matthias Bolte 已提交
3531
            goto cleanup;
3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
        }

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

3562
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
M
Matthias Bolte 已提交
3563
            goto cleanup;
3564 3565 3566
        }
    }

3567
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
3568 3569 3570
        VIR_DEBUG0("DestroyPropertyFilter failed");
    }

3571
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
M
Matthias Bolte 已提交
3572
        goto cleanup;
3573 3574
    }

M
Matthias Bolte 已提交
3575 3576
    result = 0;

3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
  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);
3594
    esxVI_TaskInfo_Free(&taskInfo);
3595 3596 3597

    return result;
}
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621



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 已提交
3622
            return -1;
3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635
        }

        /* 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 已提交
3636
                return -1;
3637 3638 3639 3640 3641 3642
            }
        }
    }

    return 0;
}