esx_vi.c 83.3 KB
Newer Older
1 2 3 4 5 6 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 34 35 36

/*
 * esx_vi.c: client for the VMware VI API 2.5 to manage ESX hosts
 *
 * Copyright (C) 2009 Matthias Bolte <matthias.bolte@googlemail.com>
 *
 * 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>

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

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

#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "util.h"
#include "uuid.h"
#include "virterror_internal.h"
37
#include "xml.h"
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 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
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"

#define VIR_FROM_THIS VIR_FROM_ESX

#define ESX_VI_ERROR(conn, code, fmt...)                                      \
    virReportErrorHelper(conn, VIR_FROM_ESX, code, __FILE__, __FUNCTION__,    \
                         __LINE__, fmt)

#define ESX_VI__SOAP__REQUEST_HEADER                                          \
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"                            \
    "<soapenv:Envelope "                                                      \
      "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "          \
      "xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" "          \
      "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "              \
      "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"                       \
    "<soapenv:Body>"

#define ESX_VI__SOAP__REQUEST_FOOTER                                          \
    "</soapenv:Body>"                                                         \
    "</soapenv:Envelope>"

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

#define ESV_VI__XML_TAG__OPEN(_buffer, _element, _type)                       \
    do {                                                                      \
        virBufferAddLit(_buffer, "<");                                        \
        virBufferAdd(_buffer, _element, -1);                                  \
        virBufferAddLit(_buffer, " xmlns=\"urn:vim25\" xsi:type=\"");         \
        virBufferAdd(_buffer, _type, -1);                                     \
        virBufferAddLit(_buffer, "\">");                                      \
    } while (0)

#define ESV_VI__XML_TAG__CLOSE(_buffer, _element)                             \
    do {                                                                      \
        virBufferAddLit(_buffer, "</");                                       \
        virBufferAdd(_buffer, _element, -1);                                  \
        virBufferAddLit(_buffer, ">");                                        \
    } while (0)

#define ESX_VI__TEMPLATE__ALLOC(_type)                                        \
    int                                                                       \
    esxVI_##_type##_Alloc(virConnectPtr conn, esxVI_##_type **ptrptr)         \
    {                                                                         \
M
Matthias Bolte 已提交
85
        return esxVI_Alloc(conn, (void **)ptrptr, sizeof(esxVI_##_type));     \
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    }

#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 已提交
118
    VIR_FREE(item->ipAddress);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

    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);
    esxVI_ManagedObjectReference_Free(&item->datacenter);
    esxVI_ManagedObjectReference_Free(&item->vmFolder);
    esxVI_ManagedObjectReference_Free(&item->hostFolder);
    esxVI_SelectionSpec_Free(&item->fullTraversalSpecList);
});

static size_t
M
Matthias Bolte 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
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)
170 171 172 173 174 175 176 177 178 179 180 181 182 183
{
    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 已提交
184 185
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
                 char *info, size_t size, void *data ATTRIBUTE_UNUSED)
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
{
    switch (type) {
      case CURLINFO_TEXT:
        VIR_DEBUG0("CURLINFO_TEXT");
        fwrite(info, 1, size, stderr);
        printf("\n\n");
        break;

      case CURLINFO_HEADER_IN:
        VIR_DEBUG0("CURLINFO_HEADER_IN");
        break;

      case CURLINFO_HEADER_OUT:
        VIR_DEBUG0("CURLINFO_HEADER_OUT");
        break;

      case CURLINFO_DATA_IN:
        VIR_DEBUG0("CURLINFO_DATA_IN");
        break;

      case CURLINFO_DATA_OUT:
        VIR_DEBUG0("CURLINFO_DATA_OUT");
        break;

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

    return 0;
}
#endif

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
static int
esxVI_CURL_Perform(virConnectPtr conn, esxVI_Context *ctx, const char *url)
{
    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) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "curl_easy_perform() returned an error: %s (%d)",
                     curl_easy_strerror(errorCode), errorCode);
        return -1;
    }

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

    if (errorCode != CURLE_OK) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned an "
                     "error: %s (%d)", curl_easy_strerror(errorCode),
                     errorCode);
        return -1;
    }

    if (responseCode < 0) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned a "
                     "negative response code");
        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) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
                         "an error: %s (%d)", curl_easy_strerror(errorCode),
                         errorCode);
        } else {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "The server redirects from '%s' to '%s'", url,
                         redirectUrl);
        }
#else
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "The server redirects from '%s'", url);
#endif

        return -1;
    }

    return responseCode;
}

281 282
int
esxVI_Context_Connect(virConnectPtr conn, esxVI_Context *ctx, const char *url,
M
Matthias Bolte 已提交
283 284
                      const char *ipAddress, const char *username,
                      const char *password, int noVerify)
285 286 287 288 289 290
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datacenterList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
291 292 293
    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) {
294 295 296 297
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        goto failure;
    }

M
Matthias Bolte 已提交
298 299
    if (esxVI_String_DeepCopyValue(conn, &ctx->url, url) < 0 ||
        esxVI_String_DeepCopyValue(conn, &ctx->ipAddress, ipAddress) < 0) {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
        goto failure;
    }

    ctx->curl_handle = curl_easy_init();

    if (ctx->curl_handle == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Could not initialize CURL");
        goto failure;
    }

    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) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Could not build CURL header list");
        goto failure;
    }

    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);
334
    curl_easy_setopt(ctx->curl_handle, CURLOPT_FOLLOWLOCATION, 0);
335
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYPEER, noVerify ? 0 : 1);
336
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYHOST, noVerify ? 0 : 2);
337 338
    curl_easy_setopt(ctx->curl_handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPHEADER, ctx->curl_headers);
M
Matthias Bolte 已提交
339 340
    curl_easy_setopt(ctx->curl_handle, CURLOPT_READFUNCTION,
                     esxVI_CURL_ReadString);
341
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
342
                     esxVI_CURL_WriteBuffer);
343 344
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
    curl_easy_setopt(ctx->curl_handle, CURLOPT_DEBUGFUNCTION,
M
Matthias Bolte 已提交
345
                     esxVI_CURL_Debug);
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
#endif

    if (virMutexInit(&ctx->curl_lock) < 0) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Could not initialize CURL mutex");
        goto failure;
    }

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

    if (ctx->username == NULL || ctx->password == NULL) {
        virReportOOMError(conn);
        goto failure;
    }

    if (esxVI_RetrieveServiceContent(conn, ctx, &ctx->service) < 0) {
        goto failure;
    }

366 367 368
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
369
            ctx->apiVersion = esxVI_APIVersion_25;
370
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
371
            ctx->apiVersion = esxVI_APIVersion_40;
372
        } else {
373
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
374 375
                         "Expecting VI API major/minor version '2.5' or '4.0' "
                         "but found '%s'", ctx->service->about->apiVersion);
376 377
            goto failure;
        }
378

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
        if (STREQ(ctx->service->about->productLineId, "gsx")) {
            if (STRPREFIX(ctx->service->about->version, "2.0")) {
                ctx->productVersion = esxVI_ProductVersion_GSX20;
            } else {
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "Expecting GSX major/minor version '2.0' but "
                             "found '%s'", ctx->service->about->version);
                goto failure;
            }
        } 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;
            } else {
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "Expecting ESX major/minor version '3.5' or "
                             "'4.0' but found '%s'",
                             ctx->service->about->version);
                goto failure;
            }
        } 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;
            } else {
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "Expecting VPX major/minor version '2.5' or '4.0' "
                             "but found '%s'", ctx->service->about->version);
                goto failure;
            }
412
        } else {
413
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
414 415 416
                         "Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                         "or 'vpx' but found '%s'",
                         ctx->service->about->productLineId);
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
            goto failure;
        }
    } else {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                     "but found '%s'", ctx->service->about->apiType);
        goto failure;
    }

    if (esxVI_Login(conn, ctx, username, password, &ctx->session) < 0) {
        goto failure;
    }

    esxVI_BuildFullTraversalSpecList(conn, &ctx->fullTraversalSpecList);

    if (esxVI_String_AppendValueListToList(conn, &propertyNameList,
                                           "vmFolder\0"
                                           "hostFolder\0") < 0) {
        goto failure;
    }

    /* Get pointer to Datacenter for later use */
439 440 441 442
    if (esxVI_LookupObjectContentByType(conn, ctx, ctx->service->rootFolder,
                                        "Datacenter", propertyNameList,
                                        esxVI_Boolean_True,
                                        &datacenterList) < 0) {
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
        goto failure;
    }

    if (datacenterList == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Could not retrieve the 'datacenter' object from the VI "
                     "host/center");
        goto failure;
    }

    ctx->datacenter = datacenterList->obj;
    datacenterList->obj = NULL;

    /* Get pointer to vmFolder and hostFolder for later use */
    for (dynamicProperty = datacenterList->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "vmFolder")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (conn, dynamicProperty->val, &ctx->vmFolder, "Folder")) {
                goto failure;
            }
        } else if (STREQ(dynamicProperty->name, "hostFolder")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (conn, dynamicProperty->val, &ctx->hostFolder, "Folder")) {
                goto failure;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (ctx->vmFolder == NULL || ctx->hostFolder == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "The 'datacenter' object is missing the "
M
Matthias Bolte 已提交
477
                     "'vmFolder'/'hostFolder' property");
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}

int
M
Matthias Bolte 已提交
494 495
esxVI_Context_DownloadFile(virConnectPtr conn, esxVI_Context *ctx,
                           const char *url, char **content)
496 497
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
498
    int responseCode = 0;
499 500 501 502 503 504 505 506 507 508

    if (content == NULL || *content != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        goto failure;
    }

    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 已提交
509
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
510 511
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPGET, 1);

512
    responseCode = esxVI_CURL_Perform(conn, ctx, url);
513

514
    virMutexUnlock(&ctx->curl_lock);
515

516 517 518
    if (responseCode < 0) {
        goto failure;
    } else if (responseCode != 200) {
519
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
520 521 522
                     "HTTP response code %d while trying to download '%s'",
                     responseCode, url);
        goto failure;
523 524 525 526 527 528 529 530 531 532 533 534
    }

    if (virBufferError(&buffer)) {
        virReportOOMError(conn);
        goto failure;
    }

    *content = virBufferContentAndReset(&buffer);

    return 0;

  failure:
535
    virBufferFreeAndReset(&buffer);
536 537 538 539

    return -1;
}

M
Matthias Bolte 已提交
540 541 542 543
int
esxVI_Context_UploadFile(virConnectPtr conn, esxVI_Context *ctx,
                         const char *url, const char *content)
{
544
    int responseCode = 0;
M
Matthias Bolte 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557

    if (content == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        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));

558
    responseCode = esxVI_CURL_Perform(conn, ctx, url);
M
Matthias Bolte 已提交
559 560 561

    virMutexUnlock(&ctx->curl_lock);

562 563 564
    if (responseCode < 0) {
        return -1;
    } else if (responseCode != 200 && responseCode != 201) {
M
Matthias Bolte 已提交
565 566
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "HTTP response code %d while trying to upload to '%s'",
567
                     responseCode, url);
M
Matthias Bolte 已提交
568 569 570 571 572 573
        return -1;
    }

    return 0;
}

574
int
575 576 577
esxVI_Context_Execute(virConnectPtr conn, esxVI_Context *ctx,
                      const char *request, const char *xpathExpression,
                      esxVI_Response **response, esxVI_Boolean expectList)
578 579 580 581
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;

582
    if (request == NULL || response == NULL || *response != NULL) {
583 584 585 586
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        goto failure;
    }

587
    if (esxVI_Response_Alloc(conn, response) < 0) {
588 589 590 591 592 593 594
        goto failure;
    }

    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 已提交
595
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
596 597
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDSIZE, strlen(request));
598

599
    (*response)->responseCode = esxVI_CURL_Perform(conn, ctx, ctx->url);
600

601
    virMutexUnlock(&ctx->curl_lock);
602

603 604
    if ((*response)->responseCode < 0) {
        goto failure;
605 606 607 608 609 610 611
    }

    if (virBufferError(&buffer)) {
        virReportOOMError(conn);
        goto failure;
    }

612
    (*response)->content = virBufferContentAndReset(&buffer);
613

614 615 616 617
    if ((*response)->responseCode == 500 ||
        (xpathExpression != NULL && (*response)->responseCode == 200)) {
        (*response)->document = xmlReadDoc(BAD_CAST (*response)->content, "",
                                           NULL, XML_PARSE_NONET);
618

619
        if ((*response)->document == NULL) {
620 621 622 623 624
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Could not parse XML response");
            goto failure;
        }

625
        if (xmlDocGetRootElement((*response)->document) == NULL) {
626 627 628 629 630
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "XML response is an empty document");
            goto failure;
        }

631
        (*response)->xpathContext = xmlXPathNewContext((*response)->document);
632

633
        if ((*response)->xpathContext == NULL) {
634 635 636 637 638
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Could not create XPath context");
            goto failure;
        }

639
        xmlXPathRegisterNs((*response)->xpathContext, BAD_CAST "soapenv",
640
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
641
        xmlXPathRegisterNs((*response)->xpathContext, BAD_CAST "vim",
642 643
                           BAD_CAST "urn:vim25");

644 645
        if ((*response)->responseCode == 500) {
            (*response)->node =
646
              virXPathNode(conn, "/soapenv:Envelope/soapenv:Body/soapenv:Fault",
647
                           (*response)->xpathContext);
648

649
            if ((*response)->node == NULL) {
650 651 652
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "HTTP response code %d. VI Fault is unknown, "
                             "XPath evaluation failed",
653
                             (int)(*response)->responseCode);
654 655 656
                goto failure;
            }

657
            if (esxVI_Fault_Deserialize(conn, (*response)->node, &fault) < 0) {
658 659 660
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "HTTP response code %d. VI Fault is unknown, "
                             "deserialization failed",
661
                             (int)(*response)->responseCode);
662 663 664 665 666
                goto failure;
            }

            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "HTTP response code %d. VI Fault: %s - %s",
667
                         (int)(*response)->responseCode,
668 669 670
                         fault->faultcode, fault->faultstring);

            goto failure;
671 672 673 674
        } else if (expectList == esxVI_Boolean_True) {
            xmlNodePtr *nodeSet = NULL;
            int nodeSet_size;

675 676
            nodeSet_size = virXPathNodeSet(conn, xpathExpression,
                                           (*response)->xpathContext,
677 678 679 680 681
                                           &nodeSet);

            if (nodeSet_size < 0) {
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "XPath evaluation of '%s' failed",
682
                             xpathExpression);
683 684
                goto failure;
            } else if (nodeSet_size == 0) {
685
                (*response)->node = NULL;
686
            } else {
687
                (*response)->node = nodeSet[0];
688 689 690
            }

            VIR_FREE(nodeSet);
691
        } else {
692 693
            (*response)->node = virXPathNode(conn, xpathExpression,
                                             (*response)->xpathContext);
694

695
            if ((*response)->node == NULL) {
696 697
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "XPath evaluation of '%s' failed",
698
                             xpathExpression);
699 700
                goto failure;
            }
701
        }
702
    } else if ((*response)->responseCode != 200) {
703
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
704
                     "HTTP response code %d", (*response)->responseCode);
705 706 707 708 709 710
        goto failure;
    }

    return 0;

  failure:
711
    virBufferFreeAndReset(&buffer);
712
    esxVI_Response_Free(response);
713 714 715 716 717 718 719 720
    esxVI_Fault_Free(&fault);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
721
 * Response
722 723
 */

724 725
/* esxVI_Response_Alloc */
ESX_VI__TEMPLATE__ALLOC(Response);
726

727 728
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
729
{
730
    VIR_FREE(item->content);
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

    xmlXPathFreeContext(item->xpathContext);

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



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

int
esxVI_Enumeration_CastFromAnyType(virConnectPtr conn,
                                  const esxVI_Enumeration *enumeration,
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    *value = 0; /* undefined */

    if (STRNEQ(anyType->other, enumeration->type)) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Expecting type '%s' but found '%s'", enumeration->type,
                     anyType->other);
        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;
        }
    }

    ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                 "Unknown value '%s' for %s", anyType->value,
                 enumeration->type);

    return -1;
}

int
esxVI_Enumeration_Serialize(virConnectPtr conn,
                            const esxVI_Enumeration *enumeration,
                            int value, const char *element,
                            virBufferPtr output, esxVI_Boolean required)
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (value == 0) { /* undefined */
        return esxVI_CheckSerializationNecessity(conn, element, required);
    }

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

    if (name == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    ESV_VI__XML_TAG__OPEN(output, element, enumeration->type);

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
esxVI_Enumeration_Deserialize(virConnectPtr conn,
                              const esxVI_Enumeration *enumeration,
                              xmlNodePtr node, int *value)
{
    int i;
    int result = 0;
    char *name = NULL;

    if (value == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        goto failure;
    }

    *value = 0; /* undefined */

    if (esxVI_String_DeserializeValue(conn, node, &name) < 0) {
        goto failure;
    }

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

    ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Unknown value '%s' for %s",
                 name, enumeration->type);

  cleanup:
    VIR_FREE(name);

    return result;

  failure:
    result = -1;
M
Matthias Bolte 已提交
856

857
    goto cleanup;
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
}



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

int
esxVI_List_Append(virConnectPtr conn, esxVI_List **list, esxVI_List *item)
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

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

    next = *list;

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

    next->_next = item;

    return 0;
}

int
esxVI_List_DeepCopy(virConnectPtr conn, esxVI_List **destList,
                    esxVI_List *srcList,
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        goto failure;
    }

    for (src = srcList; src != NULL; src = src->_next) {
        if (deepCopyFunc(conn, &dest, src) < 0 ||
            esxVI_List_Append(conn, destList, dest) < 0) {
            goto failure;
        }

        dest = NULL;
    }

    return 0;

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

    return -1;
}

924 925 926 927 928 929 930 931 932 933 934 935 936 937
int
esxVI_List_CastFromAnyType(virConnectPtr conn, esxVI_AnyType *anyType,
                           esxVI_List **list,
                           esxVI_List_CastFromAnyTypeFunc castFromAnyTypeFunc,
                           esxVI_List_FreeFunc freeFunc)
{
    int result = 0;
    xmlNodePtr childNode = NULL;
    esxVI_AnyType *childAnyType = NULL;
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        castFromAnyTypeFunc == NULL || freeFunc == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
938
        return -1;
939 940 941 942 943 944 945 946 947 948
    }

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

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Expecting type to begin with 'ArrayOf' but found '%s'",
                     anyType->other);
949
        return -1;
950 951
    }

952
    for (childNode = anyType->_node->children; childNode != NULL;
953 954 955 956 957 958 959 960 961
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Wrong XML element type %d", childNode->type);
            goto failure;
        }

        esxVI_AnyType_Free(&childAnyType);

962 963 964
        if (esxVI_AnyType_Deserialize(conn, childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(conn, childAnyType, &item) < 0 ||
            esxVI_List_Append(conn, list, item) < 0) {
965 966 967 968 969 970 971 972 973 974 975 976
            goto failure;
        }

        item = NULL;
    }

  cleanup:
    esxVI_AnyType_Free(&childAnyType);

    return result;

  failure:
977
    freeFunc(&item);
978 979 980 981 982 983 984
    freeFunc(list);

    result = -1;

    goto cleanup;
}

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
int
esxVI_List_Serialize(virConnectPtr conn, esxVI_List *list, const char *element,
                     virBufferPtr output, esxVI_Boolean required,
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (list == NULL) {
        return esxVI_CheckSerializationNecessity(conn, element, required);
    }

    for (item = list; item != NULL; item = item->_next) {
        if (serializeFunc(conn, item, element, output,
                          esxVI_Boolean_True) < 0) {
            return -1;
        }
    }

    return 0;
}

int
esxVI_List_Deserialize(virConnectPtr conn, xmlNodePtr node, esxVI_List **list,
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

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

    for (; node != NULL; node = node->next) {
        if (node->type != XML_ELEMENT_NODE) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Wrong XML element type %d", node->type);
            goto failure;
        }

1035 1036
        if (deserializeFunc(conn, node, &item) < 0 ||
            esxVI_List_Append(conn, list, item) < 0) {
1037 1038 1039
            goto failure;
        }

1040
        item = NULL;
1041 1042 1043 1044 1045
    }

    return 0;

  failure:
1046
    freeFunc(&item);
1047 1048 1049 1050 1051 1052 1053 1054 1055
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1056 1057 1058 1059
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
 */

int
esxVI_Alloc(virConnectPtr conn, void **ptrptr, size_t size)
{
    if (ptrptr == NULL || *ptrptr != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (virAllocN(ptrptr, size, 1) < 0) {
        virReportOOMError(conn);
        return -1;
    }

    return 0;
}

1078 1079


1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
int
esxVI_CheckSerializationNecessity(virConnectPtr conn, const char *element,
                                  esxVI_Boolean required)
{
    if (element == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (required == esxVI_Boolean_True) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Required property missing while trying to serialize "
                     "'%s'", element);
        return -1;
    } else {
        return 0;
    }
}



int
esxVI_BuildFullTraversalSpecItem(virConnectPtr conn,
                                 esxVI_SelectionSpec **fullTraversalSpecList,
                                 const char *name, const char *type,
                                 const char *path, const char *selectSetNames)
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

    if (fullTraversalSpecList == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (esxVI_TraversalSpec_Alloc(conn, &traversalSpec) < 0 ||
        esxVI_String_DeepCopyValue(conn, &traversalSpec->_base->name,
                                   name) < 0 ||
        esxVI_String_DeepCopyValue(conn, &traversalSpec->type, type) < 0 ||
        esxVI_String_DeepCopyValue(conn, &traversalSpec->path, path) < 0) {
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

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

        while (currentSelectSetName != NULL && *currentSelectSetName != '\0') {
            selectionSpec = NULL;

            if (esxVI_SelectionSpec_Alloc(conn, &selectionSpec) < 0 ||
                esxVI_String_DeepCopyValue(conn, &selectionSpec->name,
                                           currentSelectSetName) < 0 ||
                esxVI_SelectionSpec_AppendToList(conn,
                                                 &traversalSpec->selectSet,
                                                 selectionSpec) < 0) {
                goto failure;
            }

            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

    if (esxVI_SelectionSpec_AppendToList(conn, fullTraversalSpecList,
                                         traversalSpec->_base) < 0) {
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);

    return -1;
}



int
esxVI_BuildFullTraversalSpecList(virConnectPtr conn,
                                 esxVI_SelectionSpec **fullTraversalSpecList)
{
    if (fullTraversalSpecList == NULL || *fullTraversalSpecList != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "visitFolders",
                                         "Folder", "childEntity",
                                         "visitFolders\0"
M
Matthias Bolte 已提交
1173
                                         "datacenterToDatastore\0"
1174 1175 1176 1177
                                         "datacenterToVmFolder\0"
                                         "datacenterToHostFolder\0"
                                         "computeResourceToHost\0"
                                         "computeResourceToResourcePool\0"
M
Matthias Bolte 已提交
1178
                                         "hostSystemToVm\0"
1179 1180 1181 1182
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

M
Matthias Bolte 已提交
1183 1184 1185 1186 1187 1188 1189 1190
    /* Traversal through datastore branch */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "datacenterToDatastore",
                                         "Datacenter", "datastore",
                                         NULL) < 0) {
        goto failure;
    }

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    /* Traversal through vmFolder branch */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "datacenterToVmFolder",
                                         "Datacenter", "vmFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through hostFolder branch  */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "datacenterToHostFolder",
                                         "Datacenter", "hostFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through host branch  */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "computeResourceToHost",
                                         "ComputeResource", "host",
                                         NULL) < 0) {
        goto failure;
    }

    /* Traversal through resourcePool branch */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "computeResourceToResourcePool",
                                         "ComputeResource", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "resourcePoolToResourcePool",
                                         "ResourcePool", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all hosts */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
M
Matthias Bolte 已提交
1235
                                         "hostSystemToVm",
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
                                         "HostSystem", "vm",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
    if (esxVI_BuildFullTraversalSpecItem(conn, fullTraversalSpecList,
                                         "resourcePoolToVm",
                                         "ResourcePool", "vm", NULL) < 0) {
        goto failure;
    }

    return 0;

  failure:
    esxVI_SelectionSpec_Free(fullTraversalSpecList);

    return -1;
}



/*
 * 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.
 */
#define ESX_VI_USE_SESSION_IS_ACTIVE 0

int
esxVI_EnsureSession(virConnectPtr conn, esxVI_Context *ctx)
{
    int result = 0;
#if ESX_VI_USE_SESSION_IS_ACTIVE
    esxVI_Boolean active = esxVI_Boolean_Undefined;
#else
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;
#endif

    if (ctx->session == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid call");
        return -1;
    }

#if ESX_VI_USE_SESSION_IS_ACTIVE
    if (esxVI_SessionIsActive(conn, ctx, ctx->session->key,
                              ctx->session->userName, &active) < 0) {
        return -1;
    }

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

        if (esxVI_Login(conn, ctx, ctx->username, ctx->password,
                        &ctx->session) < 0) {
            return -1;
        }
    }
#else
    if (esxVI_String_AppendValueToList(conn, &propertyNameList,
                                       "currentSession") < 0 ||
1302 1303 1304 1305 1306
        esxVI_LookupObjectContentByType(conn, ctx,
                                        ctx->service->sessionManager,
                                        "SessionManager", propertyNameList,
                                        esxVI_Boolean_False,
                                        &sessionManager) < 0) {
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        goto failure;
    }

    for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "currentSession")) {
            if (esxVI_UserSession_CastFromAnyType(conn, dynamicProperty->val,
                                                  &currentSession) < 0) {
                goto failure;
            }

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

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

        if (esxVI_Login(conn, ctx, ctx->username, ctx->password,
                        &ctx->session) < 0) {
            goto failure;
        }
    } else if (STRNEQ(ctx->session->key, currentSession->key)) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Key of the current session differs from the key at "
                     "last login");
        goto failure;
    }
#endif

  cleanup:
#if ESX_VI_USE_SESSION_IS_ACTIVE
    /* nothing */
#else
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);
#endif

    return result;

  failure:
    result = -1;

    goto cleanup;

    return 0;
}



int
1361 1362 1363 1364 1365 1366
esxVI_LookupObjectContentByType(virConnectPtr conn, esxVI_Context *ctx,
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
                                esxVI_Boolean recurse,
                                esxVI_ObjectContent **objectContentList)
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
{
    int result = 0;
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

    if (ctx->fullTraversalSpecList == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid call");
        return -1;
    }

    if (esxVI_ObjectSpec_Alloc(conn, &objectSpec) < 0) {
        goto failure;
    }

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

    if (recurse == esxVI_Boolean_True) {
        objectSpec->selectSet = ctx->fullTraversalSpecList;
    }

    if (esxVI_PropertySpec_Alloc(conn, &propertySpec) < 0) {
        goto failure;
    }

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

    if (esxVI_PropertyFilterSpec_Alloc(conn, &propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(conn, &propertyFilterSpec->propSet,
                                        propertySpec) < 0 ||
        esxVI_ObjectSpec_AppendToList(conn, &propertyFilterSpec->objectSet,
                                      objectSpec) < 0) {
        goto failure;
    }

    result = esxVI_RetrieveProperties(conn, ctx, propertyFilterSpec,
                                      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;

  failure:
    result = -1;

    goto cleanup;
}



1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
int
esxVI_GetManagedEntityStatus(virConnectPtr conn,
                             esxVI_ObjectContent *objectContent,
                             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
                     (conn, dynamicProperty->val, managedEntityStatus);
        }
    }

    ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
1451 1452
                 "Missing '%s' property while looking for ManagedEntityStatus",
                 propertyName);
1453 1454 1455 1456 1457 1458

    return -1;
}



1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
int
esxVI_GetVirtualMachinePowerState(virConnectPtr conn,
                                  esxVI_ObjectContent *virtualMachine,
                                  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
                     (conn, dynamicProperty->val, powerState);
        }
    }

    ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                 "Missing 'runtime.powerState' property");

    return -1;
}



1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
int
esxVI_GetVirtualMachineQuestionInfo
  (virConnectPtr conn, esxVI_ObjectContent *virtualMachine,
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (questionInfo == NULL || *questionInfo != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
                  (conn, dynamicProperty->val, questionInfo) < 0) {
                return -1;
            }
        }
    }

    return 0;
}



1509
int
1510 1511 1512
esxVI_LookupNumberOfDomainsByPowerState(virConnectPtr conn, esxVI_Context *ctx,
                                        esxVI_VirtualMachinePowerState powerState,
                                        esxVI_Boolean inverse)
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
    int numberOfDomains = 0;

    if (esxVI_String_AppendValueToList(conn, &propertyNameList,
                                       "runtime.powerState") < 0 ||
1523 1524 1525 1526
        esxVI_LookupObjectContentByType(conn, ctx, ctx->vmFolder,
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
        goto failure;
    }

    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
                      (conn, dynamicProperty->val, &powerState_) < 0) {
                    goto failure;
                }

                if ((inverse != esxVI_Boolean_True &&
                     powerState_ == powerState) ||
                    (inverse == esxVI_Boolean_True &&
                     powerState_ != powerState)) {
                    numberOfDomains++;
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

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

    return numberOfDomains;

  failure:
    numberOfDomains = -1;

    goto cleanup;
}



int
esxVI_GetVirtualMachineIdentity(virConnectPtr conn,
                                esxVI_ObjectContent *virtualMachine,
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
1574
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "ObjectContent does not reference a virtual machine");
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Could not parse positive integer from '%s'",
                         virtualMachine->obj->value);
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
                if (esxVI_AnyType_ExpectType(conn, dynamicProperty->val,
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

                if (*name == NULL) {
                    virReportOOMError(conn);
                    goto failure;
                }

                break;
            }
        }

        if (*name == NULL) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Could not get name of virtual machine");
            goto failure;
        }
    }

    if (uuid != NULL) {
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
        if (esxVI_GetManagedEntityStatus(conn, virtualMachine, "configStatus",
                                         &configStatus) < 0) {
            goto failure;
        }

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

                    uuid_string = dynamicProperty->val->string;
                    break;
1643
                }
1644
            }
1645

1646 1647 1648 1649
            if (uuid_string == NULL) {
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "Could not get UUID of virtual machine");
                goto failure;
1650 1651
            }

1652 1653 1654 1655 1656 1657 1658 1659
            if (virUUIDParse(uuid_string, uuid) < 0) {
                ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                             "Could not parse UUID from string '%s'",
                             uuid_string);
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
1660

1661 1662
            VIR_WARN0("Cannot access UUID, because 'configStatus' property "
                      "indicates a config problem");
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
        }
    }

    return 0;

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

    return -1;
}



1678 1679 1680 1681
int
esxVI_LookupResourcePoolByHostSystem
  (virConnectPtr conn, esxVI_Context *ctx, esxVI_ObjectContent *hostSystem,
   esxVI_ManagedObjectReference **resourcePool)
M
Matthias Bolte 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *computeResource = NULL;

    if (resourcePool == NULL || *resourcePool != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "parent")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (conn, dynamicProperty->val, &managedObjectReference,
                   "ComputeResource") < 0) {
                goto failure;
            }

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

    if (managedObjectReference == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Could not retrieve compute resource of host system");
        goto failure;
    }

    if (esxVI_String_AppendValueToList(conn, &propertyNameList,
                                       "resourcePool") < 0 ||
1717 1718 1719 1720
        esxVI_LookupObjectContentByType(conn, ctx, managedObjectReference,
                                        "ComputeResource", propertyNameList,
                                        esxVI_Boolean_False,
                                        &computeResource) < 0) {
M
Matthias Bolte 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
        goto failure;
    }

    if (computeResource == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Could not retrieve compute resource of host system");
        goto failure;
    }

    for (dynamicProperty = computeResource->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "resourcePool")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (conn, dynamicProperty->val, resourcePool,
                   "ResourcePool") < 0) {
                goto failure;
            }

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

    if ((*resourcePool) == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                     "Could not retrieve resource pool of compute resource");
        goto failure;
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
    esxVI_ObjectContent_Free(&computeResource);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



1766 1767
int
esxVI_LookupHostSystemByIp(virConnectPtr conn, esxVI_Context *ctx,
M
Matthias Bolte 已提交
1768 1769
                           const char *ipAddress,
                           esxVI_String *propertyNameList,
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
                           esxVI_ObjectContent **hostSystem)
{
    int result = 0;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;

    if (hostSystem == NULL || *hostSystem != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

M
Matthias Bolte 已提交
1780 1781
    if (esxVI_FindByIp(conn, ctx, ctx->datacenter, ipAddress,
                       esxVI_Boolean_False, &managedObjectReference) < 0) {
1782 1783 1784
        goto failure;
    }

1785 1786 1787
    if (esxVI_LookupObjectContentByType(conn, ctx, managedObjectReference,
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_False, hostSystem) < 0) {
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
        goto failure;
    }

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



int
esxVI_LookupVirtualMachineByUuid(virConnectPtr conn, esxVI_Context *ctx,
                                 const unsigned char *uuid,
                                 esxVI_String *propertyNameList,
1808 1809
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurence occurence)
1810 1811 1812
{
    int result = 0;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
1813
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824

    if (virtualMachine == NULL || *virtualMachine != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (esxVI_FindByUuid(conn, ctx, ctx->datacenter, uuid, esxVI_Boolean_True,
                         &managedObjectReference) < 0) {
        goto failure;
    }

1825 1826 1827 1828 1829 1830
    if (managedObjectReference == NULL) {
        if (occurence == esxVI_Occurence_OptionalItem) {
            return 0;
        } else {
            virUUIDFormat(uuid, uuid_string);

1831
            ESX_VI_ERROR(conn, VIR_ERR_NO_DOMAIN,
1832 1833 1834 1835 1836
                         "Could not find domain with UUID '%s'", uuid_string);
            goto failure;
        }
    }

1837 1838 1839 1840
    if (esxVI_LookupObjectContentByType(conn, ctx, managedObjectReference,
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_False,
                                        virtualMachine) < 0) {
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
        goto failure;
    }

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;

  failure:
    result = -1;
M
Matthias Bolte 已提交
1851 1852 1853 1854 1855 1856

    goto cleanup;
}



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
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
  (virConnectPtr conn, esxVI_Context *ctx, const unsigned char *uuid,
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
   esxVI_Boolean autoAnswer)
{
    int result = 0;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;

    if (esxVI_String_DeepCopyList(conn, &completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueListToList(conn, &completePropertyNameList,
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
        esxVI_LookupVirtualMachineByUuid(conn, ctx, uuid,
                                         completePropertyNameList,
                                         virtualMachine,
                                         esxVI_Occurence_RequiredItem) < 0 ||
        esxVI_GetVirtualMachineQuestionInfo(conn, *virtualMachine,
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
           (conn, ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
        goto failure;
    }

    if (questionInfo != NULL &&
        esxVI_HandleVirtualMachineQuestion(conn, ctx, (*virtualMachine)->obj,
                                           questionInfo, autoAnswer) < 0) {
        goto failure;
    }

    if (pendingTaskInfoList != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_OPERATION_INVALID,
                     "Other tasks are pending for this domain");
        goto failure;
    }

  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



M
Matthias Bolte 已提交
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
int
esxVI_LookupDatastoreByName(virConnectPtr conn, esxVI_Context *ctx,
                            const char *name, esxVI_String *propertyNameList,
                            esxVI_ObjectContent **datastore,
                            esxVI_Occurence occurence)
{
    int result = 0;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
1922
    esxVI_Boolean accessible = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
1923
    size_t offset = strlen("/vmfs/volumes/");
1924
    int numInaccessibleDatastores = 0;
M
Matthias Bolte 已提交
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934

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

    /* Get all datastores */
    if (esxVI_String_DeepCopyList(conn, &completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueListToList(conn, &completePropertyNameList,
1935 1936 1937
                                           "summary.accessible\0"
                                           "summary.name\0"
                                           "summary.url\0") < 0) {
M
Matthias Bolte 已提交
1938 1939 1940
        goto failure;
    }

1941 1942 1943 1944
    if (esxVI_LookupObjectContentByType(conn, ctx, ctx->datacenter,
                                        "Datastore", completePropertyNameList,
                                        esxVI_Boolean_True,
                                        &datastoreList) < 0) {
M
Matthias Bolte 已提交
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
        goto failure;
    }

    if (datastoreList == NULL) {
        if (occurence == esxVI_Occurence_OptionalItem) {
            goto cleanup;
        } else {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "No datastores available");
            goto failure;
        }
    }

    /* Search for a matching datastore */
    for (candidate = datastoreList; candidate != NULL;
         candidate = candidate->_next) {
1961 1962
        accessible = esxVI_Boolean_Undefined;

M
Matthias Bolte 已提交
1963 1964
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
            if (STREQ(dynamicProperty->name, "summary.accessible")) {
                if (esxVI_AnyType_ExpectType(conn, dynamicProperty->val,
                                             esxVI_Type_Boolean) < 0) {
                    goto failure;
                }

                accessible = dynamicProperty->val->boolean;
                break;
            }
        }

        if (accessible == esxVI_Boolean_Undefined) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Got incomplete response while querying for the "
                         "datastore 'summary.accessible' property");
            goto failure;
        }

        if (accessible == esxVI_Boolean_False) {
            ++numInaccessibleDatastores;
        }

        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "summary.accessible")) {
                /* Ignore it */
            } else if (STREQ(dynamicProperty->name, "summary.name")) {
M
Matthias Bolte 已提交
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
                if (esxVI_AnyType_ExpectType(conn, dynamicProperty->val,
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                if (STREQ(dynamicProperty->val->string, name)) {
                    if (esxVI_ObjectContent_DeepCopy(conn, datastore,
                                                     candidate) < 0) {
                        goto failure;
                    }

                    /* Found datastore with matching name */
                    goto cleanup;
                }
2006 2007 2008 2009 2010 2011 2012 2013 2014
            } else if (STREQ(dynamicProperty->name, "summary.url")) {
                if (accessible == esxVI_Boolean_False) {
                    /*
                     * The 'summary.url' property of an inaccessible datastore
                     * is invalid and cannot be used to identify the datastore.
                     */
                    continue;
                }

M
Matthias Bolte 已提交
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
                if (esxVI_AnyType_ExpectType(conn, dynamicProperty->val,
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                if (! STRPREFIX(dynamicProperty->val->string,
                                "/vmfs/volumes/")) {
                    ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                                 "Datastore URL '%s' has unexpected prefix, "
                                 "expecting '/vmfs/volumes/' prefix",
                                 dynamicProperty->val->string);
                    goto failure;
                }

                if (STREQ(dynamicProperty->val->string + offset, name)) {
                    if (esxVI_ObjectContent_DeepCopy(conn, datastore,
                                                     candidate) < 0) {
                        goto failure;
                    }

                    /* Found datastore with matching URL suffix */
                    goto cleanup;
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

    if (occurence != esxVI_Occurence_OptionalItem) {
2045 2046 2047 2048 2049 2050 2051 2052 2053
        if (numInaccessibleDatastores > 0) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Could not find datastore '%s', maybe it's "
                         "inaccessible", name);
        } else {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Could not find datastore '%s'", name);
        }

M
Matthias Bolte 已提交
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
        goto failure;
    }

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

    return result;

  failure:
    result = -1;
2065 2066 2067 2068 2069 2070

    goto cleanup;
}



2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 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 2227 2228
int esxVI_LookupTaskInfoByTask(virConnectPtr conn, esxVI_Context *ctx,
                               esxVI_ManagedObjectReference *task,
                               esxVI_TaskInfo **taskInfo)
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (taskInfo == NULL || *taskInfo != NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    if (esxVI_String_AppendValueToList(conn, &propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(conn, ctx, task, "Task",
                                        propertyNameList, esxVI_Boolean_False,
                                        &objectContent) < 0) {
        goto failure;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
            if (esxVI_TaskInfo_CastFromAnyType(conn, dynamicProperty->val,
                                               taskInfo) < 0) {
                goto failure;
            }

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

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
  (virConnectPtr conn, esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
   esxVI_TaskInfo **pendingTaskInfoList)
{
    int result = 0;
    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) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        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
                  (conn, dynamicProperty->val, &recentTaskList, "Task") < 0) {
                goto failure;
            }

            break;
        }
    }

    /* Lookup task info for each task */
    for (recentTask = recentTaskList; recentTask != NULL;
         recentTask = recentTask->_next) {
        if (esxVI_LookupTaskInfoByTask(conn, ctx, recentTask, &taskInfo) < 0) {
            goto failure;
        }

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
            if (esxVI_TaskInfo_AppendToList(conn, pendingTaskInfoList,
                                            taskInfo) < 0) {
                goto failure;
            }

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

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;

  failure:
    esxVI_TaskInfo_Free(pendingTaskInfoList);

    result = -1;

    goto cleanup;
}



int
esxVI_LookupAndHandleVirtualMachineQuestion(virConnectPtr conn,
                                            esxVI_Context *ctx,
                                            const unsigned char *uuid,
                                            esxVI_Boolean autoAnswer)
{
    int result = 0;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

    if (esxVI_String_AppendValueToList(conn, &propertyNameList,
                                       "runtime.question") < 0 ||
        esxVI_LookupVirtualMachineByUuid(conn, ctx, uuid, propertyNameList,
                                         &virtualMachine,
                                         esxVI_Occurence_RequiredItem) < 0 ||
        esxVI_GetVirtualMachineQuestionInfo(conn, virtualMachine,
                                            &questionInfo) < 0) {
        goto failure;
    }

    if (questionInfo != NULL &&
        esxVI_HandleVirtualMachineQuestion(conn, ctx, virtualMachine->obj,
                                           questionInfo, autoAnswer) < 0) {
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



2229 2230 2231 2232 2233 2234
int
esxVI_StartVirtualMachineTask(virConnectPtr conn, esxVI_Context *ctx,
                              const char *name, const char *request,
                              esxVI_ManagedObjectReference **task)
{
    int result = 0;
2235 2236
    char *xpathExpression = NULL;
    esxVI_Response *response = NULL;
2237

2238
    if (virAsprintf(&xpathExpression,
2239 2240 2241 2242 2243
                    ESX_VI__SOAP__RESPONSE_XPATH("%s_Task"), name) < 0) {
        virReportOOMError(conn);
        goto failure;
    }

2244 2245 2246 2247
    if (esxVI_Context_Execute(conn, ctx, request, xpathExpression, &response,
                              esxVI_Boolean_False) < 0 ||
        esxVI_ManagedObjectReference_Deserialize(conn, response->node, task,
                                                 "Task") < 0) {
2248 2249 2250 2251
        goto failure;
    }

  cleanup:
2252 2253
    VIR_FREE(xpathExpression);
    esxVI_Response_Free(&response);
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307

    return result;

  failure:
    result = -1;

    goto cleanup;
}



int
esxVI_StartSimpleVirtualMachineTask
  (virConnectPtr conn, esxVI_Context *ctx, const char *name,
   esxVI_ManagedObjectReference *virtualMachine,
   esxVI_ManagedObjectReference **task)
{
    int result = 0;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    char *request = NULL;

    virBufferAddLit(&buffer, ESX_VI__SOAP__REQUEST_HEADER);
    virBufferAddLit(&buffer, "<");
    virBufferAdd(&buffer, name, -1);
    virBufferAddLit(&buffer, "_Task xmlns=\"urn:vim25\">");

    if (esxVI_ManagedObjectReference_Serialize(conn, virtualMachine, "_this",
                                               &buffer,
                                               esxVI_Boolean_True) < 0) {
        goto failure;
    }

    virBufferAddLit(&buffer, "</");
    virBufferAdd(&buffer, name, -1);
    virBufferAddLit(&buffer, "_Task>");
    virBufferAddLit(&buffer, ESX_VI__SOAP__REQUEST_FOOTER);

    if (virBufferError(&buffer)) {
        virReportOOMError(conn);
        goto failure;
    }

    request = virBufferContentAndReset(&buffer);

    if (esxVI_StartVirtualMachineTask(conn, ctx, name, request, task) < 0) {
        goto failure;
    }

  cleanup:
    VIR_FREE(request);

    return result;

  failure:
2308
    virBufferFreeAndReset(&buffer);
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318

    result = -1;

    goto cleanup;
}



int
esxVI_SimpleVirtualMachineMethod(virConnectPtr conn, esxVI_Context *ctx,
2319 2320
                                 const char *name,
                                 esxVI_ManagedObjectReference *virtualMachine)
2321 2322 2323
{
    int result = 0;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2324 2325
    char *request = NULL;
    esxVI_Response *response = NULL;
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336

    if (ctx->service == NULL) {
        ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR, "Invalid argument");
        return -1;
    }

    virBufferAddLit(&buffer, ESX_VI__SOAP__REQUEST_HEADER);
    virBufferAddLit(&buffer, "<");
    virBufferAdd(&buffer, name, -1);
    virBufferAddLit(&buffer, " xmlns=\"urn:vim25\">");

2337
    if (esxVI_ManagedObjectReference_Serialize(conn, virtualMachine, "_this",
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
                                               &buffer,
                                               esxVI_Boolean_True) < 0) {
        goto failure;
    }

    virBufferAddLit(&buffer, "</");
    virBufferAdd(&buffer, name, -1);
    virBufferAddLit(&buffer, ">");
    virBufferAddLit(&buffer, ESX_VI__SOAP__REQUEST_FOOTER);

    if (virBufferError(&buffer)) {
        virReportOOMError(conn);
        goto failure;
    }

2353
    request = virBufferContentAndReset(&buffer);
2354

2355 2356
    if (esxVI_Context_Execute(conn, ctx, request, NULL, &response,
                              esxVI_Boolean_False) < 0) {
2357 2358 2359 2360
        goto failure;
    }

  cleanup:
2361 2362
    VIR_FREE(request);
    esxVI_Response_Free(&response);
2363 2364 2365 2366

    return result;

  failure:
2367
    virBufferFreeAndReset(&buffer);
2368 2369 2370 2371 2372 2373 2374 2375

    result = -1;

    goto cleanup;
}



2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
int
esxVI_HandleVirtualMachineQuestion
  (virConnectPtr conn, esxVI_Context *ctx,
   esxVI_ManagedObjectReference *virtualMachine,
   esxVI_VirtualMachineQuestionInfo *questionInfo,
   esxVI_Boolean autoAnswer)
{
    int result = 0;
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

    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)) {
            virReportOOMError(conn);
            goto failure;
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

    if (autoAnswer == esxVI_Boolean_True) {
        if (possibleAnswers == NULL) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Pending question blocks virtual machine execution, "
                         "question is '%s', no possible answers",
                         questionInfo->text);
            goto failure;
        } else if (answerChoice == NULL) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Pending question blocks virtual machine execution, "
                         "question is '%s', possible answers are %s, but no "
                         "default answer is specified", questionInfo->text,
                         possibleAnswers);
            goto failure;
        }

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

        if (esxVI_AnswerVM(conn, ctx, virtualMachine, questionInfo->id,
                           answerChoice->key) < 0) {
            goto failure;
        }
    } else {
        if (possibleAnswers != NULL) {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Pending question blocks virtual machine execution, "
                         "question is '%s', possible answers are %s",
                         questionInfo->text, possibleAnswers);
        } else {
            ESX_VI_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                         "Pending question blocks virtual machine execution, "
                         "question is '%s', no possible answers",
                         questionInfo->text);
        }

        goto failure;
    }

  cleanup:
    VIR_FREE(possibleAnswers);

    return result;

  failure:
    if (possibleAnswers == NULL) {
        possibleAnswers = virBufferContentAndReset(&buffer);
    }

    result = -1;

    goto cleanup;
}



2475 2476 2477
int
esxVI_WaitForTaskCompletion(virConnectPtr conn, esxVI_Context *ctx,
                            esxVI_ManagedObjectReference *task,
2478 2479
                            const unsigned char *virtualMachineUuid,
                            esxVI_Boolean autoAnswer,
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
                            esxVI_TaskInfoState *finalState)
{
    int result = 0;
    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;
2494
    esxVI_TaskInfo *taskInfo = NULL;
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 2529 2530 2531

    version = strdup("");

    if (version == NULL) {
        virReportOOMError(conn);
        goto failure;
    }

    if (esxVI_ObjectSpec_Alloc(conn, &objectSpec) < 0) {
        goto failure;
    }

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

    if (esxVI_PropertySpec_Alloc(conn, &propertySpec) < 0) {
        goto failure;
    }

    propertySpec->type = task->type;

    if (esxVI_String_AppendValueToList(conn, &propertySpec->pathSet,
                                       "info.state") < 0 ||
        esxVI_PropertyFilterSpec_Alloc(conn, &propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(conn, &propertyFilterSpec->propSet,
                                        propertySpec) < 0 ||
        esxVI_ObjectSpec_AppendToList(conn, &propertyFilterSpec->objectSet,
                                      objectSpec) < 0 ||
        esxVI_CreateFilter(conn, ctx, propertyFilterSpec, esxVI_Boolean_True,
                           &propertyFilter) < 0) {
        goto failure;
    }

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

2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
                  (conn, ctx, virtualMachineUuid, autoAnswer) < 0) {
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
                if (esxVI_LookupTaskInfoByTask(conn, ctx, task, &taskInfo)) {
                    goto failure;
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
                    if (esxVI_CancelTask(conn, ctx, task) < 0) {
                        VIR_ERROR0("Cancelable task is blocked by an "
                                   "unanswered question but cancelation "
                                   "failed");
                    }
                } else {
                    VIR_ERROR0("Non-cancelable task is blocked by an "
                               "unanswered question");
                }

                /* FIXME: Enable error reporting here again */

                goto failure;
            }
        }

2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
        if (esxVI_WaitForUpdates(conn, ctx, version, &updateSet) < 0) {
            goto failure;
        }

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

        if (version == NULL) {
            virReportOOMError(conn);
            goto failure;
        }

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

        if (esxVI_TaskInfoState_CastFromAnyType(conn, propertyValue,
                                                &state) < 0) {
            goto failure;
        }
    }

    if (esxVI_DestroyPropertyFilter(conn, ctx, propertyFilter) < 0) {
        VIR_DEBUG0("DestroyPropertyFilter failed");
    }

    if (esxVI_TaskInfoState_CastFromAnyType(conn, propertyValue,
                                            finalState) < 0) {
        goto failure;
    }

  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);
2633
    esxVI_TaskInfo_Free(&taskInfo);
2634 2635 2636 2637 2638 2639 2640 2641

    return result;

  failure:
    result = -1;

    goto cleanup;
}