esx_vi.c 90.5 KB
Newer Older
1 2 3 4

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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_ESX



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



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

56 57


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



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

/* esxVI_Context_Alloc */
ESX_VI__TEMPLATE__ALLOC(Context);

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

    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 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
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)
140 141 142 143 144 145 146 147 148 149 150 151 152 153
{
    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 已提交
154 155
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
                 char *info, size_t size, void *data ATTRIBUTE_UNUSED)
156
{
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    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;
    }

178 179
    switch (type) {
      case CURLINFO_TEXT:
180 181 182 183 184
        if (size > 0 && buffer[size - 1] == '\n') {
            buffer[size - 1] = '\0';
        }

        VIR_DEBUG("CURLINFO_TEXT [[[[%s]]]]", buffer);
185 186 187
        break;

      case CURLINFO_HEADER_IN:
188
        VIR_DEBUG("CURLINFO_HEADER_IN [[[[%s]]]]", buffer);
189 190 191
        break;

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

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

      case CURLINFO_DATA_OUT:
200
        VIR_DEBUG("CURLINFO_DATA_OUT [[[[%s]]]]", buffer);
201 202 203 204 205 206 207
        break;

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

208 209
    VIR_FREE(buffer);

210 211 212 213
    return 0;
}
#endif

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

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

    if (errorCode != CURLE_OK) {
236
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
237 238
                     _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned an "
                       "error: %s (%d) : %s"), curl_easy_strerror(errorCode),
239
                     errorCode, ctx->curl_error);
240 241 242 243
        return -1;
    }

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

        return -1;
    }

    return responseCode;
}

277
int
278
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
M
Matthias Bolte 已提交
279 280
                      const char *ipAddress, const char *username,
                      const char *password, int noVerify)
281 282 283 284 285 286
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datacenterList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
287 288 289
    if (ctx == NULL || url == NULL || ipAddress == NULL || username == NULL ||
        password == NULL || ctx->url != NULL || ctx->service != NULL ||
        ctx->curl_handle != NULL || ctx->curl_headers != NULL) {
290
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
291 292 293
        goto failure;
    }

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

    ctx->curl_handle = curl_easy_init();

    if (ctx->curl_handle == NULL) {
302 303
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL"));
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        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) {
322 323
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not build CURL header list"));
324 325 326 327 328 329
        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);
330
    curl_easy_setopt(ctx->curl_handle, CURLOPT_FOLLOWLOCATION, 0);
331
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYPEER, noVerify ? 0 : 1);
332
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYHOST, noVerify ? 0 : 2);
333 334
    curl_easy_setopt(ctx->curl_handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPHEADER, ctx->curl_headers);
M
Matthias Bolte 已提交
335 336
    curl_easy_setopt(ctx->curl_handle, CURLOPT_READFUNCTION,
                     esxVI_CURL_ReadString);
337
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
338
                     esxVI_CURL_WriteBuffer);
339 340
    curl_easy_setopt(ctx->curl_handle, CURLOPT_ERRORBUFFER,
                     ctx->curl_error);
341
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
342 343
    curl_easy_setopt(ctx->curl_handle, CURLOPT_DEBUGFUNCTION, esxVI_CURL_Debug);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 1);
344 345 346
#endif

    if (virMutexInit(&ctx->curl_lock) < 0) {
347 348
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL mutex"));
349 350 351 352 353 354 355
        goto failure;
    }

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

    if (ctx->username == NULL || ctx->password == NULL) {
356
        virReportOOMError();
357 358 359
        goto failure;
    }

360
    if (esxVI_RetrieveServiceContent(ctx, &ctx->service) < 0) {
361 362 363
        goto failure;
    }

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

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

424
    if (esxVI_Login(ctx, username, password, NULL, &ctx->session) < 0) {
425 426 427
        goto failure;
    }

428
    esxVI_BuildFullTraversalSpecList(&ctx->fullTraversalSpecList);
429

430
    if (esxVI_String_AppendValueListToList(&propertyNameList,
431 432 433 434 435 436
                                           "vmFolder\0"
                                           "hostFolder\0") < 0) {
        goto failure;
    }

    /* Get pointer to Datacenter for later use */
437
    if (esxVI_LookupObjectContentByType(ctx, ctx->service->rootFolder,
438 439 440
                                        "Datacenter", propertyNameList,
                                        esxVI_Boolean_True,
                                        &datacenterList) < 0) {
441 442 443 444
        goto failure;
    }

    if (datacenterList == NULL) {
445 446 447
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve the 'datacenter' object from the "
                       "VI host/center"));
448 449 450 451 452 453 454 455 456 457 458
        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
459
                  (dynamicProperty->val, &ctx->vmFolder)) {
460 461 462 463
                goto failure;
            }
        } else if (STREQ(dynamicProperty->name, "hostFolder")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
464
                  (dynamicProperty->val, &ctx->hostFolder)) {
465 466 467 468 469 470 471 472
                goto failure;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (ctx->vmFolder == NULL || ctx->hostFolder == NULL) {
473 474 475
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("The 'datacenter' object is missing the "
                       "'vmFolder'/'hostFolder' property"));
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}

int
492
esxVI_Context_DownloadFile(esxVI_Context *ctx, const char *url, char **content)
493 494
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
495
    int responseCode = 0;
496 497

    if (content == NULL || *content != NULL) {
498
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
499 500 501 502 503 504 505
        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 已提交
506
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
507 508
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPGET, 1);

509
    responseCode = esxVI_CURL_Perform(ctx, url);
510

511
    virMutexUnlock(&ctx->curl_lock);
512

513 514 515
    if (responseCode < 0) {
        goto failure;
    } else if (responseCode != 200) {
516
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
517
                     _("HTTP response code %d for download from '%s'"),
518 519
                     responseCode, url);
        goto failure;
520 521 522
    }

    if (virBufferError(&buffer)) {
523
        virReportOOMError();
524 525 526 527 528 529 530 531
        goto failure;
    }

    *content = virBufferContentAndReset(&buffer);

    return 0;

  failure:
532
    virBufferFreeAndReset(&buffer);
533 534 535 536

    return -1;
}

M
Matthias Bolte 已提交
537
int
538 539
esxVI_Context_UploadFile(esxVI_Context *ctx, const char *url,
                         const char *content)
M
Matthias Bolte 已提交
540
{
541
    int responseCode = 0;
M
Matthias Bolte 已提交
542 543

    if (content == NULL) {
544
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
545 546 547 548 549 550 551 552 553 554
        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));

555
    responseCode = esxVI_CURL_Perform(ctx, url);
M
Matthias Bolte 已提交
556 557 558

    virMutexUnlock(&ctx->curl_lock);

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

    return 0;
}

571
int
572 573 574
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
575
{
576
    int result = 0;
577 578
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
579 580 581
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
582

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

588
    if (esxVI_Response_Alloc(response) < 0) {
589 590 591 592 593 594 595
        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 已提交
596
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
597 598
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDSIZE, strlen(request));
599

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

602
    virMutexUnlock(&ctx->curl_lock);
603

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

    if (virBufferError(&buffer)) {
609
        virReportOOMError();
610 611 612
        goto failure;
    }

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

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

619
        if ((*response)->document == NULL) {
620
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
621
                         _("Response for call to '%s' could not be parsed"),
622
                         methodName);
623 624 625
            goto failure;
        }

626
        if (xmlDocGetRootElement((*response)->document) == NULL) {
627
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
628
                         _("Response for call to '%s' is an empty XML document"),
629
                         methodName);
630 631 632
            goto failure;
        }

633
        xpathContext = xmlXPathNewContext((*response)->document);
634

635
        if (xpathContext == NULL) {
636 637
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not create XPath context"));
638 639 640
            goto failure;
        }

641
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
642
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
643
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
644

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

650
            if ((*response)->node == NULL) {
651
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
652 653
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, XPath evaluation failed"),
654
                             (*response)->responseCode, methodName);
655 656 657
                goto failure;
            }

658 659
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
660 661
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, deserialization failed"),
662
                             (*response)->responseCode, methodName);
663 664 665
                goto failure;
            }

666
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
667 668
                         _("HTTP response code %d for call to '%s'. "
                           "Fault: %s - %s"), (*response)->responseCode,
669
                         methodName, fault->faultcode, fault->faultstring);
670 671 672 673 674 675

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

676
            goto failure;
677 678 679 680
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
                            methodName) < 0) {
681
                virReportOOMError();
682 683
                goto failure;
            }
684

685
            responseNode = virXPathNode(xpathExpression, xpathContext);
686

687
            if (responseNode == NULL) {
688
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
689 690
                             _("XPath evaluation of response for call to '%s' "
                               "failed"), methodName);
691 692 693
                goto failure;
            }

694
            xpathContext->node = responseNode;
695
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
696

697 698
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
699 700
                if ((*response)->node == NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
701 702
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
703 704 705
                    goto failure;
                } else if ((*response)->node->next != NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
706 707
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
708 709 710 711 712 713
                    goto failure;
                }

                break;

              case esxVI_Occurrence_RequiredList:
714
                if ((*response)->node == NULL) {
715
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
716 717
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
718 719 720 721 722 723 724 725
                    goto failure;
                }

                break;

              case esxVI_Occurrence_OptionalItem:
                if ((*response)->node != NULL &&
                    (*response)->node->next != NULL) {
726
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
727 728
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
729 730 731 732 733
                    goto failure;
                }

                break;

734
              case esxVI_Occurrence_OptionalList:
735 736 737 738 739
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
                if ((*response)->node != NULL) {
740
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
741 742
                                 _("Call to '%s' returned something, expecting "
                                   "an empty result"), methodName);
743 744 745 746 747 748
                    goto failure;
                }

                break;

              default:
749 750
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Invalid argument (occurrence)"));
751 752
                goto failure;
            }
753
        }
754
    } else {
755
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
756
                     _("HTTP response code %d for call to '%s'"),
757
                     (*response)->responseCode, methodName);
758 759 760
        goto failure;
    }

761 762 763 764 765
  cleanup:
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
766 767

  failure:
768
    virBufferFreeAndReset(&buffer);
769
    esxVI_Response_Free(response);
770 771
    esxVI_Fault_Free(&fault);

772 773 774
    result = -1;

    goto cleanup;
775 776 777 778 779
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
780
 * Response
781 782
 */

783 784
/* esxVI_Response_Alloc */
ESX_VI__TEMPLATE__ALLOC(Response);
785

786 787
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
788
{
789
    VIR_FREE(item->content);
790 791 792 793 794 795 796 797 798 799 800 801 802

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



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

int
803
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
804 805 806 807 808
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
809
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
810 811 812 813 814
        return -1;
    }

    *value = 0; /* undefined */

815
    if (anyType->type != enumeration->type) {
816
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
817
                     _("Expecting type '%s' but found '%s'"),
818 819
                     esxVI_Type_ToString(enumeration->type),
                     esxVI_Type_ToString(anyType->type));
820 821 822 823 824 825 826 827 828 829
        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;
        }
    }

830
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
831
                 _("Unknown value '%s' for %s"), anyType->value,
832
                 esxVI_Type_ToString(enumeration->type));
833 834 835 836 837

    return -1;
}

int
838
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
839
                            int value, const char *element, virBufferPtr output)
840 841 842 843 844
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
845
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
846 847 848 849
        return -1;
    }

    if (value == 0) { /* undefined */
850
        return 0;
851 852 853 854 855 856 857 858 859 860
    }

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

    if (name == NULL) {
861
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
862 863 864
        return -1;
    }

865 866
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
867 868 869 870 871 872 873 874 875

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
876
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
877 878 879 880 881 882 883
                              xmlNodePtr node, int *value)
{
    int i;
    int result = 0;
    char *name = NULL;

    if (value == NULL) {
884
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
885 886 887 888 889
        goto failure;
    }

    *value = 0; /* undefined */

890
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
891 892 893 894 895 896 897 898 899 900
        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;
        }
    }

901
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, _("Unknown value '%s' for %s"),
902
                 name, esxVI_Type_ToString(enumeration->type));
903 904 905 906 907 908 909 910

  cleanup:
    VIR_FREE(name);

    return result;

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

912
    goto cleanup;
913 914 915 916 917 918 919 920 921
}



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

int
922
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
923 924 925 926
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
927
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
        return -1;
    }

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

    next = *list;

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

    next->_next = item;

    return 0;
}

int
948
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
949 950 951 952 953 954 955
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
956
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
957 958 959 960
        goto failure;
    }

    for (src = srcList; src != NULL; src = src->_next) {
961 962
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
            goto failure;
        }

        dest = NULL;
    }

    return 0;

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

    return -1;
}

978
int
979
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
980 981 982 983 984 985 986 987 988 989
                           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) {
990
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
991
        return -1;
992 993 994 995 996 997 998
    }

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

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
999
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1000
                     _("Expecting type to begin with 'ArrayOf' but found '%s'"),
1001
                     anyType->other);
1002
        return -1;
1003 1004
    }

1005
    for (childNode = anyType->node->children; childNode != NULL;
1006 1007
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1008
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1009
                         _("Wrong XML element type %d"), childNode->type);
1010 1011 1012 1013 1014
            goto failure;
        }

        esxVI_AnyType_Free(&childAnyType);

1015 1016 1017
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
            goto failure;
        }

        item = NULL;
    }

  cleanup:
    esxVI_AnyType_Free(&childAnyType);

    return result;

  failure:
1030
    freeFunc(&item);
1031 1032 1033 1034 1035 1036 1037
    freeFunc(list);

    result = -1;

    goto cleanup;
}

1038
int
1039
esxVI_List_Serialize(esxVI_List *list, const char *element,
1040
                     virBufferPtr output,
1041 1042 1043 1044 1045
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
1046
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1047 1048 1049 1050
        return -1;
    }

    if (list == NULL) {
1051
        return 0;
1052 1053 1054
    }

    for (item = list; item != NULL; item = item->_next) {
1055
        if (serializeFunc(item, element, output) < 0) {
1056 1057 1058 1059 1060 1061 1062 1063
            return -1;
        }
    }

    return 0;
}

int
1064
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1065 1066 1067 1068 1069 1070 1071
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
1072
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1073 1074 1075 1076 1077 1078 1079 1080 1081
        return -1;
    }

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

    for (; node != NULL; node = node->next) {
        if (node->type != XML_ELEMENT_NODE) {
1082
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1083
                         _("Wrong XML element type %d"), node->type);
1084 1085 1086
            goto failure;
        }

1087 1088
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1089 1090 1091
            goto failure;
        }

1092
        item = NULL;
1093 1094 1095 1096 1097
    }

    return 0;

  failure:
1098
    freeFunc(&item);
1099 1100 1101 1102 1103 1104 1105 1106 1107
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1108 1109 1110 1111
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1112 1113 1114
 */

int
1115
esxVI_Alloc(void **ptrptr, size_t size)
1116 1117
{
    if (ptrptr == NULL || *ptrptr != NULL) {
1118
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1119 1120 1121 1122
        return -1;
    }

    if (virAllocN(ptrptr, size, 1) < 0) {
1123
        virReportOOMError();
1124 1125 1126 1127 1128 1129
        return -1;
    }

    return 0;
}

1130 1131


1132
int
1133
esxVI_BuildFullTraversalSpecItem(esxVI_SelectionSpec **fullTraversalSpecList,
1134 1135 1136 1137 1138 1139 1140 1141
                                 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) {
1142
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1143 1144 1145
        return -1;
    }

1146
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1147
        esxVI_String_DeepCopyValue(&traversalSpec->name, name) < 0 ||
1148 1149
        esxVI_String_DeepCopyValue(&traversalSpec->type, type) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->path, path) < 0) {
1150 1151 1152 1153 1154 1155 1156 1157 1158
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

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

        while (currentSelectSetName != NULL && *currentSelectSetName != '\0') {
1159 1160
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
                esxVI_String_DeepCopyValue(&selectionSpec->name,
1161
                                           currentSelectSetName) < 0 ||
1162
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1163 1164 1165 1166
                                                 selectionSpec) < 0) {
                goto failure;
            }

1167
            selectionSpec = NULL;
1168 1169 1170 1171
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1172
    if (esxVI_SelectionSpec_AppendToList(fullTraversalSpecList,
1173 1174
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1175 1176 1177 1178 1179 1180 1181
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);
1182
    esxVI_SelectionSpec_Free(&selectionSpec);
1183 1184 1185 1186 1187 1188 1189

    return -1;
}



int
1190
esxVI_BuildFullTraversalSpecList(esxVI_SelectionSpec **fullTraversalSpecList)
1191 1192
{
    if (fullTraversalSpecList == NULL || *fullTraversalSpecList != NULL) {
1193
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1194 1195 1196
        return -1;
    }

1197
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1198 1199 1200
                                         "visitFolders",
                                         "Folder", "childEntity",
                                         "visitFolders\0"
M
Matthias Bolte 已提交
1201
                                         "datacenterToDatastore\0"
1202 1203 1204 1205
                                         "datacenterToVmFolder\0"
                                         "datacenterToHostFolder\0"
                                         "computeResourceToHost\0"
                                         "computeResourceToResourcePool\0"
M
Matthias Bolte 已提交
1206
                                         "hostSystemToVm\0"
1207 1208 1209 1210
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

M
Matthias Bolte 已提交
1211
    /* Traversal through datastore branch */
1212
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
M
Matthias Bolte 已提交
1213 1214 1215 1216 1217 1218
                                         "datacenterToDatastore",
                                         "Datacenter", "datastore",
                                         NULL) < 0) {
        goto failure;
    }

1219
    /* Traversal through vmFolder branch */
1220
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1221 1222 1223 1224 1225 1226 1227
                                         "datacenterToVmFolder",
                                         "Datacenter", "vmFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through hostFolder branch  */
1228
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1229 1230 1231 1232 1233 1234 1235
                                         "datacenterToHostFolder",
                                         "Datacenter", "hostFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through host branch  */
1236
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1237 1238 1239 1240 1241 1242 1243
                                         "computeResourceToHost",
                                         "ComputeResource", "host",
                                         NULL) < 0) {
        goto failure;
    }

    /* Traversal through resourcePool branch */
1244
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1245 1246 1247 1248 1249 1250 1251 1252
                                         "computeResourceToResourcePool",
                                         "ComputeResource", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
1253
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1254 1255 1256 1257 1258 1259 1260 1261
                                         "resourcePoolToResourcePool",
                                         "ResourcePool", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all hosts */
1262
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
M
Matthias Bolte 已提交
1263
                                         "hostSystemToVm",
1264 1265 1266 1267 1268 1269
                                         "HostSystem", "vm",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
1270
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
                                         "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.
1292 1293
 *
 * Update: 'ESX 4.0.0 build-171294' doesn't implement this method.
1294 1295 1296 1297
 */
#define ESX_VI_USE_SESSION_IS_ACTIVE 0

int
1298
esxVI_EnsureSession(esxVI_Context *ctx)
1299 1300 1301 1302
{
#if ESX_VI_USE_SESSION_IS_ACTIVE
    esxVI_Boolean active = esxVI_Boolean_Undefined;
#else
1303
    int result = 0;
1304 1305 1306 1307 1308 1309 1310
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;
#endif

    if (ctx->session == NULL) {
1311
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
1312 1313 1314 1315
        return -1;
    }

#if ESX_VI_USE_SESSION_IS_ACTIVE
1316 1317
    if (esxVI_SessionIsActive(ctx, ctx->session->key, ctx->session->userName,
                              &active) < 0) {
1318 1319 1320 1321 1322 1323
        return -1;
    }

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

1324
        if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
1325 1326 1327 1328
                        &ctx->session) < 0) {
            return -1;
        }
    }
1329 1330

    return 0;
1331
#else
1332
    if (esxVI_String_AppendValueToList(&propertyNameList,
1333
                                       "currentSession") < 0 ||
1334
        esxVI_LookupObjectContentByType(ctx, ctx->service->sessionManager,
1335 1336 1337
                                        "SessionManager", propertyNameList,
                                        esxVI_Boolean_False,
                                        &sessionManager) < 0) {
1338 1339 1340 1341 1342 1343
        goto failure;
    }

    for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "currentSession")) {
1344
            if (esxVI_UserSession_CastFromAnyType(dynamicProperty->val,
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
                                                  &currentSession) < 0) {
                goto failure;
            }

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

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

1358 1359
        if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                        &ctx->session) < 0) {
1360 1361 1362
            goto failure;
        }
    } else if (STRNEQ(ctx->session->key, currentSession->key)) {
1363 1364 1365
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Key of the current session differs from the key at "
                       "last login"));
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
1380
#endif
1381 1382 1383 1384 1385
}



int
1386
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
1387 1388 1389 1390 1391
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
                                esxVI_Boolean recurse,
                                esxVI_ObjectContent **objectContentList)
1392 1393 1394 1395 1396 1397 1398
{
    int result = 0;
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

    if (ctx->fullTraversalSpecList == NULL) {
1399
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
1400 1401 1402
        return -1;
    }

1403
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
        goto failure;
    }

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

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

1414
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
1415 1416 1417 1418 1419 1420
        goto failure;
    }

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

1421 1422
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
1423
                                        propertySpec) < 0 ||
1424
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
1425 1426 1427 1428
                                      objectSpec) < 0) {
        goto failure;
    }

1429
    result = esxVI_RetrieveProperties(ctx, propertyFilterSpec,
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
                                      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;
}



1459
int
1460
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
1461 1462 1463 1464 1465 1466 1467 1468 1469
                             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
1470
                     (dynamicProperty->val, managedEntityStatus);
1471 1472 1473
        }
    }

1474
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1475 1476
                 _("Missing '%s' property while looking for "
                   "ManagedEntityStatus"), propertyName);
1477 1478 1479 1480 1481 1482

    return -1;
}



1483
int
1484
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
1485 1486 1487 1488 1489 1490 1491 1492
                                  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
1493
                     (dynamicProperty->val, powerState);
1494 1495 1496
        }
    }

1497 1498
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("Missing 'runtime.powerState' property"));
1499 1500 1501 1502 1503 1504

    return -1;
}



1505 1506
int
esxVI_GetVirtualMachineQuestionInfo
1507
  (esxVI_ObjectContent *virtualMachine,
1508 1509 1510 1511 1512
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (questionInfo == NULL || *questionInfo != NULL) {
1513
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1514 1515 1516 1517 1518 1519 1520
        return -1;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
1521
                  (dynamicProperty->val, questionInfo) < 0) {
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
                return -1;
            }
        }
    }

    return 0;
}



1532
int
1533
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
1534 1535
                                        esxVI_VirtualMachinePowerState powerState,
                                        esxVI_Boolean inverse)
1536 1537 1538 1539 1540 1541 1542 1543
{
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
    int numberOfDomains = 0;

1544
    if (esxVI_String_AppendValueToList(&propertyNameList,
1545
                                       "runtime.powerState") < 0 ||
1546 1547
        esxVI_LookupObjectContentByType(ctx, ctx->vmFolder, "VirtualMachine",
                                        propertyNameList, esxVI_Boolean_True,
1548
                                        &virtualMachineList) < 0) {
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
        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
1559
                      (dynamicProperty->val, &powerState_) < 0) {
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
                    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
1590
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
1591 1592 1593 1594
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
1595
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
1596 1597

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
1598 1599
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("ObjectContent does not reference a virtual machine"));
1600 1601 1602 1603 1604 1605
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
1606
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1607
                         _("Could not parse positive integer from '%s'"),
1608 1609 1610 1611 1612 1613 1614
                         virtualMachine->obj->value);
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
1615
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1616 1617 1618 1619 1620 1621 1622
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
1623
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1624 1625 1626 1627 1628 1629 1630
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

                if (*name == NULL) {
1631
                    virReportOOMError();
1632 1633 1634 1635 1636 1637 1638 1639
                    goto failure;
                }

                break;
            }
        }

        if (*name == NULL) {
1640 1641
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not get name of virtual machine"));
1642 1643 1644 1645 1646
            goto failure;
        }
    }

    if (uuid != NULL) {
1647
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
1648 1649 1650 1651 1652 1653 1654 1655 1656
                                         &configStatus) < 0) {
            goto failure;
        }

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

                    uuid_string = dynamicProperty->val->string;
                    break;
1664
                }
1665
            }
1666

1667
            if (uuid_string == NULL) {
1668 1669
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Could not get UUID of virtual machine"));
1670
                goto failure;
1671 1672
            }

1673
            if (virUUIDParse(uuid_string, uuid) < 0) {
1674
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1675
                             _("Could not parse UUID from string '%s'"),
1676 1677 1678 1679 1680
                             uuid_string);
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
1681

1682 1683
            VIR_WARN0("Cannot access UUID, because 'configStatus' property "
                      "indicates a config problem");
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
        }
    }

    return 0;

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

    return -1;
}



1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
int
esxVI_GetNumberOfSnapshotTrees
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList)
{
    int count = 0;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

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

    return count;
}



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

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

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

        count++;

        if (count >= nameslen) {
            break;
        }

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

        if (result < 0) {
            goto failure;
        }

        count += result;
    }

    return count;

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

    return -1;
}



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

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

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

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

            return 1;
        }
    }

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

        return -1;
    }
}



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

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

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

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

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

    return -1;
}



1845 1846
int
esxVI_LookupResourcePoolByHostSystem
1847
  (esxVI_Context *ctx, esxVI_ObjectContent *hostSystem,
1848
   esxVI_ManagedObjectReference **resourcePool)
M
Matthias Bolte 已提交
1849 1850 1851 1852 1853 1854 1855 1856
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *computeResource = NULL;

    if (resourcePool == NULL || *resourcePool != NULL) {
1857
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1858 1859 1860 1861 1862 1863 1864
        return -1;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "parent")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
1865
                  (dynamicProperty->val, &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
                goto failure;
            }

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

    if (managedObjectReference == NULL) {
1876 1877
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve compute resource of host system"));
M
Matthias Bolte 已提交
1878 1879 1880
        goto failure;
    }

1881 1882
    if (esxVI_String_AppendValueToList(&propertyNameList, "resourcePool") < 0 ||
        esxVI_LookupObjectContentByType(ctx, managedObjectReference,
1883 1884 1885
                                        "ComputeResource", propertyNameList,
                                        esxVI_Boolean_False,
                                        &computeResource) < 0) {
M
Matthias Bolte 已提交
1886 1887 1888 1889
        goto failure;
    }

    if (computeResource == NULL) {
1890 1891
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve compute resource of host system"));
M
Matthias Bolte 已提交
1892 1893 1894 1895 1896 1897 1898
        goto failure;
    }

    for (dynamicProperty = computeResource->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "resourcePool")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
1899
                  (dynamicProperty->val, resourcePool) < 0) {
M
Matthias Bolte 已提交
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
                goto failure;
            }

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

    if ((*resourcePool) == NULL) {
1910 1911
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve resource pool of compute resource"));
M
Matthias Bolte 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
        goto failure;
    }

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

    return result;

  failure:
    result = -1;

    goto cleanup;
}



1930
int
1931
esxVI_LookupHostSystemByIp(esxVI_Context *ctx, const char *ipAddress,
M
Matthias Bolte 已提交
1932
                           esxVI_String *propertyNameList,
1933 1934 1935 1936 1937 1938
                           esxVI_ObjectContent **hostSystem)
{
    int result = 0;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;

    if (hostSystem == NULL || *hostSystem != NULL) {
1939
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1940 1941 1942
        return -1;
    }

1943 1944
    if (esxVI_FindByIp(ctx, ctx->datacenter, ipAddress, esxVI_Boolean_False,
                       &managedObjectReference) < 0) {
1945 1946 1947
        goto failure;
    }

1948 1949 1950 1951 1952 1953 1954
    if (managedObjectReference == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find host system with IP address '%s'"),
                     ipAddress);
        goto failure;
    }

1955
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
1956 1957
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_False, hostSystem) < 0) {
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
        goto failure;
    }

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



int
1975
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
1976
                                 esxVI_String *propertyNameList,
1977
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
1978
                                 esxVI_Occurrence occurrence)
1979 1980 1981
{
    int result = 0;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
1982
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
1983 1984

    if (virtualMachine == NULL || *virtualMachine != NULL) {
1985
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1986 1987 1988
        return -1;
    }

1989 1990 1991
    virUUIDFormat(uuid, uuid_string);

    if (esxVI_FindByUuid(ctx, ctx->datacenter, uuid_string, esxVI_Boolean_True,
1992 1993 1994 1995
                         &managedObjectReference) < 0) {
        goto failure;
    }

1996
    if (managedObjectReference == NULL) {
M
Matthias Bolte 已提交
1997
        if (occurrence == esxVI_Occurrence_OptionalItem) {
1998 1999
            return 0;
        } else {
2000
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2001 2002
                         _("Could not find domain with UUID '%s'"),
                         uuid_string);
2003 2004 2005 2006
            goto failure;
        }
    }

2007
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2008 2009 2010
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_False,
                                        virtualMachine) < 0) {
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
        goto failure;
    }

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;

  failure:
    result = -1;
M
Matthias Bolte 已提交
2021 2022 2023 2024 2025 2026

    goto cleanup;
}



2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
int
esxVI_LookupVirtualMachineByName(esxVI_Context *ctx, const char *name,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurrence occurrence)
{
    int result = 0;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate = NULL;

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2040
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
        return -1;
    }

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
        esxVI_LookupObjectContentByType(ctx, ctx->vmFolder, "VirtualMachine",
                                        completePropertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
        goto failure;
    }

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

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
            goto failure;
        }

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

        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0) {
            goto failure;
        }

        break;
    }

    if (*virtualMachine == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
            return 0;
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2079
                         _("Could not find domain with name '%s'"), name);
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
            goto failure;
        }
    }

  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



2099 2100
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2101
  (esxVI_Context *ctx, const unsigned char *uuid,
2102 2103 2104 2105 2106 2107 2108 2109
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
   esxVI_Boolean autoAnswer)
{
    int result = 0;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;

2110
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2111
                                  propertyNameList) < 0 ||
2112
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2113 2114
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2115
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2116
                                         virtualMachine,
M
Matthias Bolte 已提交
2117
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2118
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
2119 2120
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
2121
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
2122 2123 2124 2125
        goto failure;
    }

    if (questionInfo != NULL &&
2126
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
2127 2128 2129 2130 2131
                                           questionInfo, autoAnswer) < 0) {
        goto failure;
    }

    if (pendingTaskInfoList != NULL) {
2132 2133
        ESX_VI_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                     _("Other tasks are pending for this domain"));
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
        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 已提交
2152
int
2153 2154
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
2155
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
2156
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
2157 2158 2159 2160 2161 2162
{
    int result = 0;
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
2163
    esxVI_Boolean accessible = esxVI_Boolean_Undefined;
M
Matthias Bolte 已提交
2164
    size_t offset = strlen("/vmfs/volumes/");
2165
    int numInaccessibleDatastores = 0;
M
Matthias Bolte 已提交
2166 2167

    if (datastore == NULL || *datastore != NULL) {
2168
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
2169 2170 2171 2172
        return -1;
    }

    /* Get all datastores */
2173
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
2174
                                  propertyNameList) < 0 ||
2175
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2176 2177 2178
                                           "summary.accessible\0"
                                           "summary.name\0"
                                           "summary.url\0") < 0) {
M
Matthias Bolte 已提交
2179 2180 2181
        goto failure;
    }

2182 2183
    if (esxVI_LookupObjectContentByType(ctx, ctx->datacenter, "Datastore",
                                        completePropertyNameList,
2184 2185
                                        esxVI_Boolean_True,
                                        &datastoreList) < 0) {
M
Matthias Bolte 已提交
2186 2187 2188 2189
        goto failure;
    }

    if (datastoreList == NULL) {
M
Matthias Bolte 已提交
2190
        if (occurrence == esxVI_Occurrence_OptionalItem) {
M
Matthias Bolte 已提交
2191 2192
            goto cleanup;
        } else {
2193 2194
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("No datastores available"));
M
Matthias Bolte 已提交
2195 2196 2197 2198 2199 2200 2201
            goto failure;
        }
    }

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

M
Matthias Bolte 已提交
2204 2205
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
2206
            if (STREQ(dynamicProperty->name, "summary.accessible")) {
2207
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
                                             esxVI_Type_Boolean) < 0) {
                    goto failure;
                }

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

        if (accessible == esxVI_Boolean_Undefined) {
2218 2219 2220
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Got incomplete response while querying for the "
                           "datastore 'summary.accessible' property"));
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
            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")) {
2233
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
M
Matthias Bolte 已提交
2234 2235 2236 2237 2238
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                if (STREQ(dynamicProperty->val->string, name)) {
2239
                    if (esxVI_ObjectContent_DeepCopy(datastore,
M
Matthias Bolte 已提交
2240 2241 2242 2243 2244 2245 2246
                                                     candidate) < 0) {
                        goto failure;
                    }

                    /* Found datastore with matching name */
                    goto cleanup;
                }
2247 2248 2249 2250 2251 2252 2253 2254 2255
            } 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;
                }

2256
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
M
Matthias Bolte 已提交
2257 2258 2259 2260 2261 2262
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                if (! STRPREFIX(dynamicProperty->val->string,
                                "/vmfs/volumes/")) {
2263
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2264 2265
                                 _("Datastore URL '%s' has unexpected prefix, "
                                   "expecting '/vmfs/volumes/' prefix"),
M
Matthias Bolte 已提交
2266 2267 2268 2269 2270
                                 dynamicProperty->val->string);
                    goto failure;
                }

                if (STREQ(dynamicProperty->val->string + offset, name)) {
2271
                    if (esxVI_ObjectContent_DeepCopy(datastore,
M
Matthias Bolte 已提交
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
                                                     candidate) < 0) {
                        goto failure;
                    }

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

M
Matthias Bolte 已提交
2285
    if (occurrence != esxVI_Occurrence_OptionalItem) {
2286
        if (numInaccessibleDatastores > 0) {
2287
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2288 2289
                         _("Could not find datastore '%s', maybe it's "
                           "inaccessible"), name);
2290
        } else {
2291
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2292
                         _("Could not find datastore '%s'"), name);
2293 2294
        }

M
Matthias Bolte 已提交
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
        goto failure;
    }

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

    return result;

  failure:
    result = -1;
2306 2307 2308 2309 2310 2311

    goto cleanup;
}



2312
int esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
2313 2314 2315 2316 2317 2318 2319 2320 2321
                               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) {
2322
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2323 2324 2325
        return -1;
    }

2326 2327 2328
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
                                        esxVI_Boolean_False,
2329 2330 2331 2332 2333 2334 2335
                                        &objectContent) < 0) {
        goto failure;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
2336
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
                                               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
2363
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
   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) {
2374
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2375 2376 2377 2378 2379 2380 2381 2382
        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
2383
                  (dynamicProperty->val, &recentTaskList) < 0) {
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
                goto failure;
            }

            break;
        }
    }

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

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
2400
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
                                            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
2429
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
2430 2431 2432 2433 2434 2435 2436 2437
                                            const unsigned char *uuid,
                                            esxVI_Boolean autoAnswer)
{
    int result = 0;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

2438
    if (esxVI_String_AppendValueToList(&propertyNameList,
2439
                                       "runtime.question") < 0 ||
2440
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
2441
                                         &virtualMachine,
M
Matthias Bolte 已提交
2442
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2443
        esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
2444 2445 2446 2447 2448
                                            &questionInfo) < 0) {
        goto failure;
    }

    if (questionInfo != NULL &&
2449
        esxVI_HandleVirtualMachineQuestion(ctx, virtualMachine->obj,
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
                                           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;
}



2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "snapshot.rootSnapshotList") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
        goto failure;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, rootSnapshotTreeList) < 0) {
                goto failure;
            }

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

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

    return result;

  failure:
    esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);

    result = -1;

    goto cleanup;
}



int
esxVI_LookupCurrentSnapshotTree
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **currentSnapshotTree,
   esxVI_Occurrence occurrence)
{
    int result = 0;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *currentSnapshot = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;

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

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "snapshot.currentSnapshot\0"
                                           "snapshot.rootSnapshotList\0") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
        goto failure;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.currentSnapshot")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, &currentSnapshot) < 0) {
                goto failure;
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
                goto failure;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (currentSnapshot == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
            return 0;
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                         _("Domain has no current snapshot"));
            goto failure;
        }
    }

    if (rootSnapshotTreeList == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not lookup root snapshot list"));
        goto failure;
    }

    if (esxVI_GetSnapshotTreeBySnapshot(rootSnapshotTreeList, currentSnapshot,
                                        &snapshotTree) < 0 ||
        esxVI_VirtualMachineSnapshotTree_DeepCopy(currentSnapshotTree,
                                                  snapshotTree) < 0) {
        goto failure;
    }

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;

  failure:
    result = -1;

    goto cleanup;
}



2606 2607
int
esxVI_HandleVirtualMachineQuestion
2608
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
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 2637 2638
   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)) {
2639
            virReportOOMError();
2640 2641 2642 2643 2644 2645 2646 2647
            goto failure;
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

    if (autoAnswer == esxVI_Boolean_True) {
        if (possibleAnswers == NULL) {
2648
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2649 2650
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
2651 2652 2653
                         questionInfo->text);
            goto failure;
        } else if (answerChoice == NULL) {
2654
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2655 2656 2657
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s, but no "
                           "default answer is specified"), questionInfo->text,
2658 2659 2660 2661 2662 2663 2664 2665 2666
                         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);

2667
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
2668 2669 2670 2671 2672
                           answerChoice->key) < 0) {
            goto failure;
        }
    } else {
        if (possibleAnswers != NULL) {
2673
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2674 2675
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s"),
2676 2677
                         questionInfo->text, possibleAnswers);
        } else {
2678
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2679 2680
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
                         questionInfo->text);
        }

        goto failure;
    }

  cleanup:
    VIR_FREE(possibleAnswers);

    return result;

  failure:
2693
    virBufferFreeAndReset(&buffer);
2694 2695 2696 2697 2698 2699 2700 2701

    result = -1;

    goto cleanup;
}



2702
int
2703
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
2704
                            esxVI_ManagedObjectReference *task,
2705 2706
                            const unsigned char *virtualMachineUuid,
                            esxVI_Boolean autoAnswer,
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
                            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;
2721
    esxVI_TaskInfo *taskInfo = NULL;
2722 2723 2724 2725

    version = strdup("");

    if (version == NULL) {
2726
        virReportOOMError();
2727 2728 2729
        goto failure;
    }

2730
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
2731 2732 2733 2734 2735 2736
        goto failure;
    }

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

2737
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
2738 2739 2740 2741 2742
        goto failure;
    }

    propertySpec->type = task->type;

2743
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
2744
                                       "info.state") < 0 ||
2745 2746
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
2747
                                        propertySpec) < 0 ||
2748
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
2749
                                      objectSpec) < 0 ||
2750
        esxVI_CreateFilter(ctx, propertyFilterSpec, esxVI_Boolean_True,
2751 2752 2753 2754 2755 2756 2757 2758
                           &propertyFilter) < 0) {
        goto failure;
    }

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

2759 2760
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
2761
                  (ctx, virtualMachineUuid, autoAnswer) < 0) {
2762 2763 2764 2765 2766
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
2767
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
2768 2769 2770 2771
                    goto failure;
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
2772
                    if (esxVI_CancelTask(ctx, task) < 0) {
2773 2774 2775
                        VIR_ERROR0(_("Cancelable task is blocked by an "
                                     "unanswered question but cancelation "
                                     "failed"));
2776 2777
                    }
                } else {
2778 2779
                    VIR_ERROR0(_("Non-cancelable task is blocked by an "
                                 "unanswered question"));
2780 2781 2782 2783 2784 2785 2786 2787
                }

                /* FIXME: Enable error reporting here again */

                goto failure;
            }
        }

2788
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
2789 2790 2791 2792 2793 2794 2795
            goto failure;
        }

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

        if (version == NULL) {
2796
            virReportOOMError();
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
            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;
        }

2828
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
2829 2830 2831 2832
            goto failure;
        }
    }

2833
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
2834 2835 2836
        VIR_DEBUG0("DestroyPropertyFilter failed");
    }

2837
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
        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);
2858
    esxVI_TaskInfo_Free(&taskInfo);
2859 2860 2861 2862 2863 2864 2865 2866

    return result;

  failure:
    result = -1;

    goto cleanup;
}
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916



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

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

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

    for (r = 0; r < 4; ++r) {
        if (strlen(input[r]) != expectedLength) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("HostCpuIdInfo register '%s' has an unexpected length"),
                         name[r]);
            goto failure;
        }

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

            if (i + 4 < expectedLength && input[r][i + 4] != ':') {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("HostCpuIdInfo register '%s' has an unexpected format"),
                             name[r]);
                goto failure;
            }
        }
    }

    return 0;

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

    return -1;
}