esx_vi.c 82.8 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

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

#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"
34
#include "xml.h"
35 36 37 38 39 40
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"

#define VIR_FROM_THIS VIR_FROM_ESX

41 42
#define ESX_VI_ERROR(code, fmt...)                                            \
    virReportErrorHelper(NULL, VIR_FROM_ESX, code, __FILE__, __FUNCTION__,    \
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
                         __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                                                                       \
80
    esxVI_##_type##_Alloc(esxVI_##_type **ptrptr)                             \
81
    {                                                                         \
82
        return esxVI_Alloc((void **)ptrptr, sizeof(esxVI_##_type));           \
83 84 85 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
    }

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

    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 已提交
138 139 140 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
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)
167 168 169 170 171 172 173 174 175 176 177 178 179 180
{
    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 已提交
181 182
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
                 char *info, size_t size, void *data ATTRIBUTE_UNUSED)
183
{
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    char *buffer = NULL;

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

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

205 206
    switch (type) {
      case CURLINFO_TEXT:
207 208 209 210 211
        if (size > 0 && buffer[size - 1] == '\n') {
            buffer[size - 1] = '\0';
        }

        VIR_DEBUG("CURLINFO_TEXT [[[[%s]]]]", buffer);
212 213 214
        break;

      case CURLINFO_HEADER_IN:
215
        VIR_DEBUG("CURLINFO_HEADER_IN [[[[%s]]]]", buffer);
216 217 218
        break;

      case CURLINFO_HEADER_OUT:
219
        VIR_DEBUG("CURLINFO_HEADER_OUT [[[[%s]]]]", buffer);
220 221 222
        break;

      case CURLINFO_DATA_IN:
223
        VIR_DEBUG("CURLINFO_DATA_IN [[[[%s]]]]", buffer);
224 225 226
        break;

      case CURLINFO_DATA_OUT:
227
        VIR_DEBUG("CURLINFO_DATA_OUT [[[[%s]]]]", buffer);
228 229 230 231 232 233 234
        break;

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

235 236
    VIR_FREE(buffer);

237 238 239 240
    return 0;
}
#endif

241
static int
242
esxVI_CURL_Perform(esxVI_Context *ctx, const char *url)
243 244 245 246 247 248 249 250 251 252
{
    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) {
253
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
254 255
                     "curl_easy_perform() returned an error: %s (%d) : %s",
                     curl_easy_strerror(errorCode), errorCode, ctx->curl_error);
256 257 258 259 260 261 262
        return -1;
    }

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

    if (errorCode != CURLE_OK) {
263
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
264
                     "curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned an "
265 266
                     "error: %s (%d) : %s", curl_easy_strerror(errorCode),
                     errorCode, ctx->curl_error);
267 268 269 270
        return -1;
    }

    if (responseCode < 0) {
271
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
272 273 274 275 276 277 278 279 280 281 282
                     "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) {
283
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
284
                         "curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
285 286
                         "an error: %s (%d) : %s", curl_easy_strerror(errorCode),
                         errorCode, ctx->curl_error);
287
        } else {
288
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
289 290 291 292
                         "The server redirects from '%s' to '%s'", url,
                         redirectUrl);
        }
#else
293
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
294 295 296 297 298 299 300 301 302
                     "The server redirects from '%s'", url);
#endif

        return -1;
    }

    return responseCode;
}

303
int
304
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
M
Matthias Bolte 已提交
305 306
                      const char *ipAddress, const char *username,
                      const char *password, int noVerify)
307 308 309 310 311 312
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datacenterList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
313 314 315
    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) {
316
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
317 318 319
        goto failure;
    }

320 321
    if (esxVI_String_DeepCopyValue(&ctx->url, url) < 0 ||
        esxVI_String_DeepCopyValue(&ctx->ipAddress, ipAddress) < 0) {
322 323 324 325 326 327
        goto failure;
    }

    ctx->curl_handle = curl_easy_init();

    if (ctx->curl_handle == NULL) {
328
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not initialize CURL");
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
        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) {
347
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not build CURL header list");
348 349 350 351 352 353
        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);
354
    curl_easy_setopt(ctx->curl_handle, CURLOPT_FOLLOWLOCATION, 0);
355
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYPEER, noVerify ? 0 : 1);
356
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYHOST, noVerify ? 0 : 2);
357 358
    curl_easy_setopt(ctx->curl_handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPHEADER, ctx->curl_headers);
M
Matthias Bolte 已提交
359 360
    curl_easy_setopt(ctx->curl_handle, CURLOPT_READFUNCTION,
                     esxVI_CURL_ReadString);
361
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
362
                     esxVI_CURL_WriteBuffer);
363 364
    curl_easy_setopt(ctx->curl_handle, CURLOPT_ERRORBUFFER,
                     ctx->curl_error);
365
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
366 367
    curl_easy_setopt(ctx->curl_handle, CURLOPT_DEBUGFUNCTION, esxVI_CURL_Debug);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 1);
368 369 370
#endif

    if (virMutexInit(&ctx->curl_lock) < 0) {
371
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Could not initialize CURL mutex");
372 373 374 375 376 377 378
        goto failure;
    }

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

    if (ctx->username == NULL || ctx->password == NULL) {
379
        virReportOOMError(NULL);
380 381 382
        goto failure;
    }

383
    if (esxVI_RetrieveServiceContent(ctx, &ctx->service) < 0) {
384 385 386
        goto failure;
    }

387 388 389
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
390
            ctx->apiVersion = esxVI_APIVersion_25;
391
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
392
            ctx->apiVersion = esxVI_APIVersion_40;
393
        } else {
394
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
395 396
                         "Expecting VI API major/minor version '2.5' or '4.0' "
                         "but found '%s'", ctx->service->about->apiVersion);
397 398
            goto failure;
        }
399

400 401 402 403
        if (STREQ(ctx->service->about->productLineId, "gsx")) {
            if (STRPREFIX(ctx->service->about->version, "2.0")) {
                ctx->productVersion = esxVI_ProductVersion_GSX20;
            } else {
404
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
405 406 407 408 409 410 411 412 413 414 415
                             "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 {
416
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
417 418 419 420 421 422 423 424 425 426 427
                             "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 {
428
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
429 430 431 432
                             "Expecting VPX major/minor version '2.5' or '4.0' "
                             "but found '%s'", ctx->service->about->version);
                goto failure;
            }
433
        } else {
434
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
435 436 437
                         "Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                         "or 'vpx' but found '%s'",
                         ctx->service->about->productLineId);
438 439 440
            goto failure;
        }
    } else {
441
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
442 443 444 445 446
                     "Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                     "but found '%s'", ctx->service->about->apiType);
        goto failure;
    }

447
    if (esxVI_Login(ctx, username, password, &ctx->session) < 0) {
448 449 450
        goto failure;
    }

451
    esxVI_BuildFullTraversalSpecList(&ctx->fullTraversalSpecList);
452

453
    if (esxVI_String_AppendValueListToList(&propertyNameList,
454 455 456 457 458 459
                                           "vmFolder\0"
                                           "hostFolder\0") < 0) {
        goto failure;
    }

    /* Get pointer to Datacenter for later use */
460
    if (esxVI_LookupObjectContentByType(ctx, ctx->service->rootFolder,
461 462 463
                                        "Datacenter", propertyNameList,
                                        esxVI_Boolean_True,
                                        &datacenterList) < 0) {
464 465 466 467
        goto failure;
    }

    if (datacenterList == NULL) {
468
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
469 470 471 472 473 474 475 476 477 478 479 480 481
                     "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
482
                  (dynamicProperty->val, &ctx->vmFolder, "Folder")) {
483 484 485 486
                goto failure;
            }
        } else if (STREQ(dynamicProperty->name, "hostFolder")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
487
                  (dynamicProperty->val, &ctx->hostFolder, "Folder")) {
488 489 490 491 492 493 494 495
                goto failure;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (ctx->vmFolder == NULL || ctx->hostFolder == NULL) {
496
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
497
                     "The 'datacenter' object is missing the "
M
Matthias Bolte 已提交
498
                     "'vmFolder'/'hostFolder' property");
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}

int
515
esxVI_Context_DownloadFile(esxVI_Context *ctx, const char *url, char **content)
516 517
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
518
    int responseCode = 0;
519 520

    if (content == NULL || *content != NULL) {
521
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
522 523 524 525 526 527 528
        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 已提交
529
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
530 531
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPGET, 1);

532
    responseCode = esxVI_CURL_Perform(ctx, url);
533

534
    virMutexUnlock(&ctx->curl_lock);
535

536 537 538
    if (responseCode < 0) {
        goto failure;
    } else if (responseCode != 200) {
539
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
540
                     "HTTP response code %d for download from '%s'",
541 542
                     responseCode, url);
        goto failure;
543 544 545
    }

    if (virBufferError(&buffer)) {
546
        virReportOOMError(NULL);
547 548 549 550 551 552 553 554
        goto failure;
    }

    *content = virBufferContentAndReset(&buffer);

    return 0;

  failure:
555
    virBufferFreeAndReset(&buffer);
556 557 558 559

    return -1;
}

M
Matthias Bolte 已提交
560
int
561 562
esxVI_Context_UploadFile(esxVI_Context *ctx, const char *url,
                         const char *content)
M
Matthias Bolte 已提交
563
{
564
    int responseCode = 0;
M
Matthias Bolte 已提交
565 566

    if (content == NULL) {
567
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
M
Matthias Bolte 已提交
568 569 570 571 572 573 574 575 576 577
        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));

578
    responseCode = esxVI_CURL_Perform(ctx, url);
M
Matthias Bolte 已提交
579 580 581

    virMutexUnlock(&ctx->curl_lock);

582 583 584
    if (responseCode < 0) {
        return -1;
    } else if (responseCode != 200 && responseCode != 201) {
585
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
586
                     "HTTP response code %d for upload to '%s'",
587
                     responseCode, url);
M
Matthias Bolte 已提交
588 589 590 591 592 593
        return -1;
    }

    return 0;
}

594
int
595 596 597
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
598
{
599
    int result = 0;
600 601
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
602 603 604
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
605

606
    if (request == NULL || response == NULL || *response != NULL) {
607
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
608 609 610
        goto failure;
    }

611
    if (esxVI_Response_Alloc(response) < 0) {
612 613 614 615 616 617 618
        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 已提交
619
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
620 621
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDSIZE, strlen(request));
622

623
    (*response)->responseCode = esxVI_CURL_Perform(ctx, ctx->url);
624

625
    virMutexUnlock(&ctx->curl_lock);
626

627 628
    if ((*response)->responseCode < 0) {
        goto failure;
629 630 631
    }

    if (virBufferError(&buffer)) {
632
        virReportOOMError(NULL);
633 634 635
        goto failure;
    }

636
    (*response)->content = virBufferContentAndReset(&buffer);
637

638
    if ((*response)->responseCode == 500 || (*response)->responseCode == 200) {
639 640
        (*response)->document = xmlReadDoc(BAD_CAST (*response)->content, "",
                                           NULL, XML_PARSE_NONET);
641

642
        if ((*response)->document == NULL) {
643
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
644 645
                         "Response for call to '%s' could not be parsed",
                         methodName);
646 647 648
            goto failure;
        }

649
        if (xmlDocGetRootElement((*response)->document) == NULL) {
650
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
651 652
                         "Response for call to '%s' is an empty XML document",
                         methodName);
653 654 655
            goto failure;
        }

656
        xpathContext = xmlXPathNewContext((*response)->document);
657

658
        if (xpathContext == NULL) {
659
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
660 661 662 663
                         "Could not create XPath context");
            goto failure;
        }

664
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
665
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
666
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
667

668 669
        if ((*response)->responseCode == 500) {
            (*response)->node =
670
              virXPathNode(NULL, "/soapenv:Envelope/soapenv:Body/soapenv:Fault",
671
                           xpathContext);
672

673
            if ((*response)->node == NULL) {
674
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
675 676 677
                             "HTTP response code %d for call to '%s'. "
                             "Fault is unknown, XPath evaluation failed",
                             (*response)->responseCode, methodName);
678 679 680
                goto failure;
            }

681 682
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
683 684 685
                             "HTTP response code %d for call to '%s'. "
                             "Fault is unknown, deserialization failed",
                             (*response)->responseCode, methodName);
686 687 688
                goto failure;
            }

689
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
690 691 692
                         "HTTP response code %d for call to '%s'. "
                         "Fault: %s - %s", (*response)->responseCode,
                         methodName, fault->faultcode, fault->faultstring);
693 694 695 696 697 698

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

699
            goto failure;
700 701 702 703
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
                            methodName) < 0) {
704
                virReportOOMError(NULL);
705 706
                goto failure;
            }
707

708
            responseNode = virXPathNode(NULL, xpathExpression, xpathContext);
709

710
            if (responseNode == NULL) {
711
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
712 713
                             "XPath evaluation of response for call to '%s' "
                             "failed", methodName);
714 715 716
                goto failure;
            }

717
            xpathContext->node = responseNode;
718
            (*response)->node = virXPathNode(NULL, "./vim:returnval",
719
                                             xpathContext);
720

721 722 723
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
                if ((*response)->node == NULL) {
724
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
725 726 727 728 729 730 731 732 733 734
                                 "Call to '%s' returned an empty result, "
                                 "expecting a non-empty result", methodName);
                    goto failure;
                }

                break;

              case esxVI_Occurrence_OptionalItem:
                if ((*response)->node != NULL &&
                    (*response)->node->next != NULL) {
735
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
736 737 738 739 740 741 742 743 744 745 746 747 748
                                 "Call to '%s' returned a list, expecting "
                                 "exactly one item", methodName);
                    goto failure;
                }

                break;

              case esxVI_Occurrence_List:
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
                if ((*response)->node != NULL) {
749
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
750 751 752 753 754 755 756 757
                                 "Call to '%s' returned something, expecting "
                                 "an empty result", methodName);
                    goto failure;
                }

                break;

              default:
758
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
759
                             "Invalid argument (occurrence)");
760 761
                goto failure;
            }
762
        }
763
    } else {
764
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
765 766
                     "HTTP response code %d for call to '%s'",
                     (*response)->responseCode, methodName);
767 768 769
        goto failure;
    }

770 771 772 773 774
  cleanup:
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
775 776

  failure:
777
    virBufferFreeAndReset(&buffer);
778
    esxVI_Response_Free(response);
779 780
    esxVI_Fault_Free(&fault);

781 782 783
    result = -1;

    goto cleanup;
784 785 786 787 788
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
789
 * Response
790 791
 */

792 793
/* esxVI_Response_Alloc */
ESX_VI__TEMPLATE__ALLOC(Response);
794

795 796
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
797
{
798
    VIR_FREE(item->content);
799 800 801 802 803 804 805 806 807 808 809 810 811

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



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

int
812
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
813 814 815 816 817
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
818
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
819 820 821 822 823 824
        return -1;
    }

    *value = 0; /* undefined */

    if (STRNEQ(anyType->other, enumeration->type)) {
825
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
826 827 828 829 830 831 832 833 834 835 836 837
                     "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;
        }
    }

838
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
839 840 841 842 843 844 845
                 "Unknown value '%s' for %s", anyType->value,
                 enumeration->type);

    return -1;
}

int
846
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
847 848 849 850 851 852 853
                            int value, const char *element,
                            virBufferPtr output, esxVI_Boolean required)
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
854
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
855 856 857 858
        return -1;
    }

    if (value == 0) { /* undefined */
859
        return esxVI_CheckSerializationNecessity(element, required);
860 861 862 863 864 865 866 867 868 869
    }

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

    if (name == NULL) {
870
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
871 872 873 874 875 876 877 878 879 880 881 882 883
        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
884
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
885 886 887 888 889 890 891
                              xmlNodePtr node, int *value)
{
    int i;
    int result = 0;
    char *name = NULL;

    if (value == NULL) {
892
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
893 894 895 896 897
        goto failure;
    }

    *value = 0; /* undefined */

898
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
899 900 901 902 903 904 905 906 907 908
        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;
        }
    }

909
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Unknown value '%s' for %s",
910 911 912 913 914 915 916 917 918
                 name, enumeration->type);

  cleanup:
    VIR_FREE(name);

    return result;

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

920
    goto cleanup;
921 922 923 924 925 926 927 928 929
}



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

int
930
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
931 932 933 934
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
935
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
        return -1;
    }

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

    next = *list;

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

    next->_next = item;

    return 0;
}

int
956
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
957 958 959 960 961 962 963
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
964
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
965 966 967 968
        goto failure;
    }

    for (src = srcList; src != NULL; src = src->_next) {
969 970
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
            goto failure;
        }

        dest = NULL;
    }

    return 0;

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

    return -1;
}

986
int
987
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
988 989 990 991 992 993 994 995 996 997
                           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) {
998
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
999
        return -1;
1000 1001 1002 1003 1004 1005 1006
    }

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

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
1007
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1008 1009
                     "Expecting type to begin with 'ArrayOf' but found '%s'",
                     anyType->other);
1010
        return -1;
1011 1012
    }

1013
    for (childNode = anyType->_node->children; childNode != NULL;
1014 1015
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1016
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1017 1018 1019 1020 1021 1022
                         "Wrong XML element type %d", childNode->type);
            goto failure;
        }

        esxVI_AnyType_Free(&childAnyType);

1023 1024 1025
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
            goto failure;
        }

        item = NULL;
    }

  cleanup:
    esxVI_AnyType_Free(&childAnyType);

    return result;

  failure:
1038
    freeFunc(&item);
1039 1040 1041 1042 1043 1044 1045
    freeFunc(list);

    result = -1;

    goto cleanup;
}

1046
int
1047
esxVI_List_Serialize(esxVI_List *list, const char *element,
1048 1049 1050 1051 1052 1053
                     virBufferPtr output, esxVI_Boolean required,
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
1054
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1055 1056 1057 1058
        return -1;
    }

    if (list == NULL) {
1059
        return esxVI_CheckSerializationNecessity(element, required);
1060 1061 1062
    }

    for (item = list; item != NULL; item = item->_next) {
1063
        if (serializeFunc(item, element, output, esxVI_Boolean_True) < 0) {
1064 1065 1066 1067 1068 1069 1070 1071
            return -1;
        }
    }

    return 0;
}

int
1072
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1073 1074 1075 1076 1077 1078 1079
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
1080
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1081 1082 1083 1084 1085 1086 1087 1088 1089
        return -1;
    }

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

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

1095 1096
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1097 1098 1099
            goto failure;
        }

1100
        item = NULL;
1101 1102 1103 1104 1105
    }

    return 0;

  failure:
1106
    freeFunc(&item);
1107 1108 1109 1110 1111 1112 1113 1114 1115
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1116 1117 1118 1119
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1120 1121 1122
 */

int
1123
esxVI_Alloc(void **ptrptr, size_t size)
1124 1125
{
    if (ptrptr == NULL || *ptrptr != NULL) {
1126
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1127 1128 1129 1130
        return -1;
    }

    if (virAllocN(ptrptr, size, 1) < 0) {
1131
        virReportOOMError(NULL);
1132 1133 1134 1135 1136 1137
        return -1;
    }

    return 0;
}

1138 1139


1140
int
1141
esxVI_CheckSerializationNecessity(const char *element,
1142 1143 1144
                                  esxVI_Boolean required)
{
    if (element == NULL) {
1145
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1146 1147 1148 1149
        return -1;
    }

    if (required == esxVI_Boolean_True) {
1150
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
                     "Required property missing while trying to serialize "
                     "'%s'", element);
        return -1;
    } else {
        return 0;
    }
}



int
1162
esxVI_BuildFullTraversalSpecItem(esxVI_SelectionSpec **fullTraversalSpecList,
1163 1164 1165 1166 1167 1168 1169 1170
                                 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) {
1171
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1172 1173 1174
        return -1;
    }

1175 1176 1177 1178
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->_base->name, name) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->type, type) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->path, path) < 0) {
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

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

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

1190 1191
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
                esxVI_String_DeepCopyValue(&selectionSpec->name,
1192
                                           currentSelectSetName) < 0 ||
1193
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1194 1195 1196 1197 1198 1199 1200 1201
                                                 selectionSpec) < 0) {
                goto failure;
            }

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

1202
    if (esxVI_SelectionSpec_AppendToList(fullTraversalSpecList,
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
                                         traversalSpec->_base) < 0) {
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);

    return -1;
}



int
1218
esxVI_BuildFullTraversalSpecList(esxVI_SelectionSpec **fullTraversalSpecList)
1219 1220
{
    if (fullTraversalSpecList == NULL || *fullTraversalSpecList != NULL) {
1221
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1222 1223 1224
        return -1;
    }

1225
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1226 1227 1228
                                         "visitFolders",
                                         "Folder", "childEntity",
                                         "visitFolders\0"
M
Matthias Bolte 已提交
1229
                                         "datacenterToDatastore\0"
1230 1231 1232 1233
                                         "datacenterToVmFolder\0"
                                         "datacenterToHostFolder\0"
                                         "computeResourceToHost\0"
                                         "computeResourceToResourcePool\0"
M
Matthias Bolte 已提交
1234
                                         "hostSystemToVm\0"
1235 1236 1237 1238
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

M
Matthias Bolte 已提交
1239
    /* Traversal through datastore branch */
1240
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
M
Matthias Bolte 已提交
1241 1242 1243 1244 1245 1246
                                         "datacenterToDatastore",
                                         "Datacenter", "datastore",
                                         NULL) < 0) {
        goto failure;
    }

1247
    /* Traversal through vmFolder branch */
1248
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1249 1250 1251 1252 1253 1254 1255
                                         "datacenterToVmFolder",
                                         "Datacenter", "vmFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through hostFolder branch  */
1256
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1257 1258 1259 1260 1261 1262 1263
                                         "datacenterToHostFolder",
                                         "Datacenter", "hostFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through host branch  */
1264
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1265 1266 1267 1268 1269 1270 1271
                                         "computeResourceToHost",
                                         "ComputeResource", "host",
                                         NULL) < 0) {
        goto failure;
    }

    /* Traversal through resourcePool branch */
1272
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1273 1274 1275 1276 1277 1278 1279 1280
                                         "computeResourceToResourcePool",
                                         "ComputeResource", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
1281
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1282 1283 1284 1285 1286 1287 1288 1289
                                         "resourcePoolToResourcePool",
                                         "ResourcePool", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all hosts */
1290
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
M
Matthias Bolte 已提交
1291
                                         "hostSystemToVm",
1292 1293 1294 1295 1296 1297
                                         "HostSystem", "vm",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
1298
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
                                         "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.
1320 1321
 *
 * Update: 'ESX 4.0.0 build-171294' doesn't implement this method.
1322 1323 1324 1325
 */
#define ESX_VI_USE_SESSION_IS_ACTIVE 0

int
1326
esxVI_EnsureSession(esxVI_Context *ctx)
1327 1328 1329 1330
{
#if ESX_VI_USE_SESSION_IS_ACTIVE
    esxVI_Boolean active = esxVI_Boolean_Undefined;
#else
1331
    int result = 0;
1332 1333 1334 1335 1336 1337 1338
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;
#endif

    if (ctx->session == NULL) {
1339
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid call");
1340 1341 1342 1343
        return -1;
    }

#if ESX_VI_USE_SESSION_IS_ACTIVE
1344 1345
    if (esxVI_SessionIsActive(ctx, ctx->session->key, ctx->session->userName,
                              &active) < 0) {
1346 1347 1348 1349 1350 1351
        return -1;
    }

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

1352
        if (esxVI_Login(ctx, ctx->username, ctx->password,
1353 1354 1355 1356
                        &ctx->session) < 0) {
            return -1;
        }
    }
1357 1358

    return 0;
1359
#else
1360
    if (esxVI_String_AppendValueToList(&propertyNameList,
1361
                                       "currentSession") < 0 ||
1362
        esxVI_LookupObjectContentByType(ctx, ctx->service->sessionManager,
1363 1364 1365
                                        "SessionManager", propertyNameList,
                                        esxVI_Boolean_False,
                                        &sessionManager) < 0) {
1366 1367 1368 1369 1370 1371
        goto failure;
    }

    for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "currentSession")) {
1372
            if (esxVI_UserSession_CastFromAnyType(dynamicProperty->val,
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
                                                  &currentSession) < 0) {
                goto failure;
            }

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

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

1386
        if (esxVI_Login(ctx, ctx->username, ctx->password, &ctx->session) < 0) {
1387 1388 1389
            goto failure;
        }
    } else if (STRNEQ(ctx->session->key, currentSession->key)) {
1390
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
                     "Key of the current session differs from the key at "
                     "last login");
        goto failure;
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);

    return result;

  failure:
    result = -1;

    goto cleanup;
1407
#endif
1408 1409 1410 1411 1412
}



int
1413
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
1414 1415 1416 1417 1418
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
                                esxVI_Boolean recurse,
                                esxVI_ObjectContent **objectContentList)
1419 1420 1421 1422 1423 1424 1425
{
    int result = 0;
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

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

1430
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
        goto failure;
    }

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

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

1441
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
1442 1443 1444 1445 1446 1447
        goto failure;
    }

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

1448 1449
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
1450
                                        propertySpec) < 0 ||
1451
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
1452 1453 1454 1455
                                      objectSpec) < 0) {
        goto failure;
    }

1456
    result = esxVI_RetrieveProperties(ctx, propertyFilterSpec,
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
                                      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;
}



1486
int
1487
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
1488 1489 1490 1491 1492 1493 1494 1495 1496
                             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
1497
                     (dynamicProperty->val, managedEntityStatus);
1498 1499 1500
        }
    }

1501
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
1502 1503
                 "Missing '%s' property while looking for ManagedEntityStatus",
                 propertyName);
1504 1505 1506 1507 1508 1509

    return -1;
}



1510
int
1511
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
1512 1513 1514 1515 1516 1517 1518 1519
                                  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
1520
                     (dynamicProperty->val, powerState);
1521 1522 1523
        }
    }

1524
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1525 1526 1527 1528 1529 1530 1531
                 "Missing 'runtime.powerState' property");

    return -1;
}



1532 1533
int
esxVI_GetVirtualMachineQuestionInfo
1534
  (esxVI_ObjectContent *virtualMachine,
1535 1536 1537 1538 1539
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (questionInfo == NULL || *questionInfo != NULL) {
1540
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1541 1542 1543 1544 1545 1546 1547
        return -1;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
1548
                  (dynamicProperty->val, questionInfo) < 0) {
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
                return -1;
            }
        }
    }

    return 0;
}



1559
int
1560
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
1561 1562
                                        esxVI_VirtualMachinePowerState powerState,
                                        esxVI_Boolean inverse)
1563 1564 1565 1566 1567 1568 1569 1570
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
    int numberOfDomains = 0;

1571
    if (esxVI_String_AppendValueToList(&propertyNameList,
1572
                                       "runtime.powerState") < 0 ||
1573 1574
        esxVI_LookupObjectContentByType(ctx, ctx->vmFolder, "VirtualMachine",
                                        propertyNameList, esxVI_Boolean_True,
1575
                                        &virtualMachineList) < 0) {
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
        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
1586
                      (dynamicProperty->val, &powerState_) < 0) {
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
                    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
1617
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
1618 1619 1620 1621
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
1622
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
1623 1624

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
1625
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1626 1627 1628 1629 1630 1631 1632
                     "ObjectContent does not reference a virtual machine");
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
1633
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1634 1635 1636 1637 1638 1639 1640 1641
                         "Could not parse positive integer from '%s'",
                         virtualMachine->obj->value);
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
1642
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
1643 1644 1645 1646 1647 1648 1649
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
1650
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1651 1652 1653 1654 1655 1656 1657
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

                if (*name == NULL) {
1658
                    virReportOOMError(NULL);
1659 1660 1661 1662 1663 1664 1665 1666
                    goto failure;
                }

                break;
            }
        }

        if (*name == NULL) {
1667
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1668 1669 1670 1671 1672 1673
                         "Could not get name of virtual machine");
            goto failure;
        }
    }

    if (uuid != NULL) {
1674
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
1675 1676 1677 1678 1679 1680 1681 1682 1683
                                         &configStatus) < 0) {
            goto failure;
        }

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

                    uuid_string = dynamicProperty->val->string;
                    break;
1691
                }
1692
            }
1693

1694
            if (uuid_string == NULL) {
1695
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1696 1697
                             "Could not get UUID of virtual machine");
                goto failure;
1698 1699
            }

1700
            if (virUUIDParse(uuid_string, uuid) < 0) {
1701
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1702 1703 1704 1705 1706 1707
                             "Could not parse UUID from string '%s'",
                             uuid_string);
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
1708

1709 1710
            VIR_WARN0("Cannot access UUID, because 'configStatus' property "
                      "indicates a config problem");
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
        }
    }

    return 0;

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

    return -1;
}



1726 1727
int
esxVI_LookupResourcePoolByHostSystem
1728
  (esxVI_Context *ctx, esxVI_ObjectContent *hostSystem,
1729
   esxVI_ManagedObjectReference **resourcePool)
M
Matthias Bolte 已提交
1730 1731 1732 1733 1734 1735 1736 1737
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *computeResource = NULL;

    if (resourcePool == NULL || *resourcePool != NULL) {
1738
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
M
Matthias Bolte 已提交
1739 1740 1741 1742 1743 1744 1745
        return -1;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "parent")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
1746
                  (dynamicProperty->val, &managedObjectReference,
M
Matthias Bolte 已提交
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
                   "ComputeResource") < 0) {
                goto failure;
            }

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

    if (managedObjectReference == NULL) {
1758
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
1759 1760 1761 1762
                     "Could not retrieve compute resource of host system");
        goto failure;
    }

1763 1764
    if (esxVI_String_AppendValueToList(&propertyNameList, "resourcePool") < 0 ||
        esxVI_LookupObjectContentByType(ctx, managedObjectReference,
1765 1766 1767
                                        "ComputeResource", propertyNameList,
                                        esxVI_Boolean_False,
                                        &computeResource) < 0) {
M
Matthias Bolte 已提交
1768 1769 1770 1771
        goto failure;
    }

    if (computeResource == NULL) {
1772
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
1773 1774 1775 1776 1777 1778 1779 1780
                     "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
1781
                  (dynamicProperty->val, resourcePool, "ResourcePool") < 0) {
M
Matthias Bolte 已提交
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
                goto failure;
            }

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

    if ((*resourcePool) == NULL) {
1792
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
                     "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;
}



1812
int
1813
esxVI_LookupHostSystemByIp(esxVI_Context *ctx, const char *ipAddress,
M
Matthias Bolte 已提交
1814
                           esxVI_String *propertyNameList,
1815 1816 1817 1818 1819 1820
                           esxVI_ObjectContent **hostSystem)
{
    int result = 0;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;

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

1825 1826
    if (esxVI_FindByIp(ctx, ctx->datacenter, ipAddress, esxVI_Boolean_False,
                       &managedObjectReference) < 0) {
1827 1828 1829
        goto failure;
    }

1830
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
1831 1832
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_False, hostSystem) < 0) {
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
        goto failure;
    }

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



int
1850
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
1851
                                 esxVI_String *propertyNameList,
1852
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
1853
                                 esxVI_Occurrence occurrence)
1854 1855 1856
{
    int result = 0;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
1857
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
1858 1859

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

1864
    if (esxVI_FindByUuid(ctx, ctx->datacenter, uuid, esxVI_Boolean_True,
1865 1866 1867 1868
                         &managedObjectReference) < 0) {
        goto failure;
    }

1869
    if (managedObjectReference == NULL) {
M
Matthias Bolte 已提交
1870
        if (occurrence == esxVI_Occurrence_OptionalItem) {
1871 1872 1873 1874
            return 0;
        } else {
            virUUIDFormat(uuid, uuid_string);

1875
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
1876 1877 1878 1879 1880
                         "Could not find domain with UUID '%s'", uuid_string);
            goto failure;
        }
    }

1881
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
1882 1883 1884
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_False,
                                        virtualMachine) < 0) {
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
        goto failure;
    }

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;

  failure:
    result = -1;
M
Matthias Bolte 已提交
1895 1896 1897 1898 1899 1900

    goto cleanup;
}



1901 1902
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
1903
  (esxVI_Context *ctx, const unsigned char *uuid,
1904 1905 1906 1907 1908 1909 1910 1911
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
   esxVI_Boolean autoAnswer)
{
    int result = 0;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;

1912
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
1913
                                  propertyNameList) < 0 ||
1914
        esxVI_String_AppendValueListToList(&completePropertyNameList,
1915 1916
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
1917
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
1918
                                         virtualMachine,
M
Matthias Bolte 已提交
1919
                                         esxVI_Occurrence_RequiredItem) < 0 ||
1920
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
1921 1922
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
1923
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
1924 1925 1926 1927
        goto failure;
    }

    if (questionInfo != NULL &&
1928
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
1929 1930 1931 1932 1933
                                           questionInfo, autoAnswer) < 0) {
        goto failure;
    }

    if (pendingTaskInfoList != NULL) {
1934
        ESX_VI_ERROR(VIR_ERR_OPERATION_INVALID,
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
                     "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 已提交
1954
int
1955 1956
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
1957
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
1958
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
1959 1960 1961 1962 1963 1964
{
    int result = 0;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
1965
    esxVI_Boolean accessible = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
1966
    size_t offset = strlen("/vmfs/volumes/");
1967
    int numInaccessibleDatastores = 0;
M
Matthias Bolte 已提交
1968 1969

    if (datastore == NULL || *datastore != NULL) {
1970
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
M
Matthias Bolte 已提交
1971 1972 1973 1974
        return -1;
    }

    /* Get all datastores */
1975
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
1976
                                  propertyNameList) < 0 ||
1977
        esxVI_String_AppendValueListToList(&completePropertyNameList,
1978 1979 1980
                                           "summary.accessible\0"
                                           "summary.name\0"
                                           "summary.url\0") < 0) {
M
Matthias Bolte 已提交
1981 1982 1983
        goto failure;
    }

1984 1985
    if (esxVI_LookupObjectContentByType(ctx, ctx->datacenter, "Datastore",
                                        completePropertyNameList,
1986 1987
                                        esxVI_Boolean_True,
                                        &datastoreList) < 0) {
M
Matthias Bolte 已提交
1988 1989 1990 1991
        goto failure;
    }

    if (datastoreList == NULL) {
M
Matthias Bolte 已提交
1992
        if (occurrence == esxVI_Occurrence_OptionalItem) {
M
Matthias Bolte 已提交
1993 1994
            goto cleanup;
        } else {
1995
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "No datastores available");
M
Matthias Bolte 已提交
1996 1997 1998 1999 2000 2001 2002
            goto failure;
        }
    }

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

M
Matthias Bolte 已提交
2005 2006
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
2007
            if (STREQ(dynamicProperty->name, "summary.accessible")) {
2008
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
                                             esxVI_Type_Boolean) < 0) {
                    goto failure;
                }

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

        if (accessible == esxVI_Boolean_Undefined) {
2019
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
                         "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")) {
2034
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
M
Matthias Bolte 已提交
2035 2036 2037 2038 2039
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                if (STREQ(dynamicProperty->val->string, name)) {
2040
                    if (esxVI_ObjectContent_DeepCopy(datastore,
M
Matthias Bolte 已提交
2041 2042 2043 2044 2045 2046 2047
                                                     candidate) < 0) {
                        goto failure;
                    }

                    /* Found datastore with matching name */
                    goto cleanup;
                }
2048 2049 2050 2051 2052 2053 2054 2055 2056
            } 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;
                }

2057
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
M
Matthias Bolte 已提交
2058 2059 2060 2061 2062 2063
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                if (! STRPREFIX(dynamicProperty->val->string,
                                "/vmfs/volumes/")) {
2064
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
M
Matthias Bolte 已提交
2065 2066 2067 2068 2069 2070 2071
                                 "Datastore URL '%s' has unexpected prefix, "
                                 "expecting '/vmfs/volumes/' prefix",
                                 dynamicProperty->val->string);
                    goto failure;
                }

                if (STREQ(dynamicProperty->val->string + offset, name)) {
2072
                    if (esxVI_ObjectContent_DeepCopy(datastore,
M
Matthias Bolte 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
                                                     candidate) < 0) {
                        goto failure;
                    }

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

M
Matthias Bolte 已提交
2086
    if (occurrence != esxVI_Occurrence_OptionalItem) {
2087
        if (numInaccessibleDatastores > 0) {
2088
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2089 2090 2091
                         "Could not find datastore '%s', maybe it's "
                         "inaccessible", name);
        } else {
2092
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2093 2094 2095
                         "Could not find datastore '%s'", name);
        }

M
Matthias Bolte 已提交
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
        goto failure;
    }

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

    return result;

  failure:
    result = -1;
2107 2108 2109 2110 2111 2112

    goto cleanup;
}



2113
int esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
2114 2115 2116 2117 2118 2119 2120 2121 2122
                               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) {
2123
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
2124 2125 2126
        return -1;
    }

2127 2128 2129
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
                                        esxVI_Boolean_False,
2130 2131 2132 2133 2134 2135 2136
                                        &objectContent) < 0) {
        goto failure;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
2137
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
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
                                               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
2164
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
   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) {
2175
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
2176 2177 2178 2179 2180 2181 2182 2183
        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
2184
                  (dynamicProperty->val, &recentTaskList, "Task") < 0) {
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
                goto failure;
            }

            break;
        }
    }

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

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
2201
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
                                            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
2230
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
2231 2232 2233 2234 2235 2236 2237 2238
                                            const unsigned char *uuid,
                                            esxVI_Boolean autoAnswer)
{
    int result = 0;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

2239
    if (esxVI_String_AppendValueToList(&propertyNameList,
2240
                                       "runtime.question") < 0 ||
2241
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
2242
                                         &virtualMachine,
M
Matthias Bolte 已提交
2243
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2244
        esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
2245 2246 2247 2248 2249
                                            &questionInfo) < 0) {
        goto failure;
    }

    if (questionInfo != NULL &&
2250
        esxVI_HandleVirtualMachineQuestion(ctx, virtualMachine->obj,
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
                                           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;
}



2270
int
2271 2272
esxVI_StartVirtualMachineTask(esxVI_Context *ctx, const char *name,
                              const char *request,
2273 2274 2275
                              esxVI_ManagedObjectReference **task)
{
    int result = 0;
2276
    char *methodName = NULL;
2277
    esxVI_Response *response = NULL;
2278

2279
    if (virAsprintf(&methodName, "%s_Task", name) < 0) {
2280
        virReportOOMError(NULL);
2281 2282 2283
        goto failure;
    }

2284
    if (esxVI_Context_Execute(ctx, methodName, request, &response,
2285
                              esxVI_Occurrence_RequiredItem) < 0 ||
2286
        esxVI_ManagedObjectReference_Deserialize(response->node, task,
2287
                                                 "Task") < 0) {
2288 2289 2290 2291
        goto failure;
    }

  cleanup:
2292
    VIR_FREE(methodName);
2293
    esxVI_Response_Free(&response);
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

    return result;

  failure:
    result = -1;

    goto cleanup;
}



int
esxVI_StartSimpleVirtualMachineTask
2307
  (esxVI_Context *ctx, const char *name,
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
   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\">");

2320
    if (esxVI_ManagedObjectReference_Serialize(virtualMachine, "_this", &buffer,
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
                                               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)) {
2331
        virReportOOMError(NULL);
2332 2333 2334 2335 2336
        goto failure;
    }

    request = virBufferContentAndReset(&buffer);

2337
    if (esxVI_StartVirtualMachineTask(ctx, name, request, task) < 0) {
2338 2339 2340 2341 2342 2343 2344 2345 2346
        goto failure;
    }

  cleanup:
    VIR_FREE(request);

    return result;

  failure:
2347
    virBufferFreeAndReset(&buffer);
2348 2349 2350 2351 2352 2353 2354 2355 2356

    result = -1;

    goto cleanup;
}



int
2357
esxVI_SimpleVirtualMachineMethod(esxVI_Context *ctx, const char *name,
2358
                                 esxVI_ManagedObjectReference *virtualMachine)
2359 2360 2361
{
    int result = 0;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
2362 2363
    char *request = NULL;
    esxVI_Response *response = NULL;
2364 2365

    if (ctx->service == NULL) {
2366
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "Invalid argument");
2367 2368 2369 2370 2371 2372 2373 2374
        return -1;
    }

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

2375
    if (esxVI_ManagedObjectReference_Serialize(virtualMachine, "_this", &buffer,
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
                                               esxVI_Boolean_True) < 0) {
        goto failure;
    }

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

    if (virBufferError(&buffer)) {
2386
        virReportOOMError(NULL);
2387 2388 2389
        goto failure;
    }

2390
    request = virBufferContentAndReset(&buffer);
2391

2392
    if (esxVI_Context_Execute(ctx, name, request, &response,
2393
                              esxVI_Occurrence_None) < 0) {
2394 2395 2396 2397
        goto failure;
    }

  cleanup:
2398 2399
    VIR_FREE(request);
    esxVI_Response_Free(&response);
2400 2401 2402 2403

    return result;

  failure:
2404
    virBufferFreeAndReset(&buffer);
2405 2406 2407 2408 2409 2410 2411 2412

    result = -1;

    goto cleanup;
}



2413 2414
int
esxVI_HandleVirtualMachineQuestion
2415
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
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
   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)) {
2446
            virReportOOMError(NULL);
2447 2448 2449 2450 2451 2452 2453 2454
            goto failure;
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

    if (autoAnswer == esxVI_Boolean_True) {
        if (possibleAnswers == NULL) {
2455
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2456 2457 2458 2459 2460
                         "Pending question blocks virtual machine execution, "
                         "question is '%s', no possible answers",
                         questionInfo->text);
            goto failure;
        } else if (answerChoice == NULL) {
2461
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
                         "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);

2474
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
2475 2476 2477 2478 2479
                           answerChoice->key) < 0) {
            goto failure;
        }
    } else {
        if (possibleAnswers != NULL) {
2480
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2481 2482 2483 2484
                         "Pending question blocks virtual machine execution, "
                         "question is '%s', possible answers are %s",
                         questionInfo->text, possibleAnswers);
        } else {
2485
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
                         "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;
}



2511
int
2512
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
2513
                            esxVI_ManagedObjectReference *task,
2514 2515
                            const unsigned char *virtualMachineUuid,
                            esxVI_Boolean autoAnswer,
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
                            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;
2530
    esxVI_TaskInfo *taskInfo = NULL;
2531 2532 2533 2534

    version = strdup("");

    if (version == NULL) {
2535
        virReportOOMError(NULL);
2536 2537 2538
        goto failure;
    }

2539
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
2540 2541 2542 2543 2544 2545
        goto failure;
    }

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

2546
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
2547 2548 2549 2550 2551
        goto failure;
    }

    propertySpec->type = task->type;

2552
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
2553
                                       "info.state") < 0 ||
2554 2555
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
2556
                                        propertySpec) < 0 ||
2557
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
2558
                                      objectSpec) < 0 ||
2559
        esxVI_CreateFilter(ctx, propertyFilterSpec, esxVI_Boolean_True,
2560 2561 2562 2563 2564 2565 2566 2567
                           &propertyFilter) < 0) {
        goto failure;
    }

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

2568 2569
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
2570
                  (ctx, virtualMachineUuid, autoAnswer) < 0) {
2571 2572 2573 2574 2575
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
2576
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
2577 2578 2579 2580
                    goto failure;
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
2581
                    if (esxVI_CancelTask(ctx, task) < 0) {
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
                        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;
            }
        }

2597
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
2598 2599 2600 2601 2602 2603 2604
            goto failure;
        }

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

        if (version == NULL) {
2605
            virReportOOMError(NULL);
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 2633 2634 2635 2636
            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;
        }

2637
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
2638 2639 2640 2641
            goto failure;
        }
    }

2642
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
2643 2644 2645
        VIR_DEBUG0("DestroyPropertyFilter failed");
    }

2646
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
        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);
2667
    esxVI_TaskInfo_Free(&taskInfo);
2668 2669 2670 2671 2672 2673 2674 2675

    return result;

  failure:
    result = -1;

    goto cleanup;
}