esx_vi.c 140.9 KB
Newer Older
1 2 3 4

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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_ESX



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



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

57 58


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



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
79
 * CURL
80 81
 */

82 83
/* esxVI_CURL_Alloc */
ESX_VI__TEMPLATE__ALLOC(CURL)
84

85 86
/* esxVI_CURL_Free */
ESX_VI__TEMPLATE__FREE(CURL,
87
{
88 89 90 91 92 93 94 95 96 97
    esxVI_SharedCURL *shared = item->shared;

    if (shared != NULL) {
        esxVI_SharedCURL_Remove(shared, item);

        if (shared->count == 0) {
            esxVI_SharedCURL_Free(&shared);
        }
    }

98 99
    if (item->handle != NULL) {
        curl_easy_cleanup(item->handle);
100 101
    }

102 103
    if (item->headers != NULL) {
        curl_slist_free_all(item->headers);
104 105
    }

106 107
    virMutexDestroy(&item->lock);
})
108 109

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

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

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

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

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

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

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

      default:
203
        VIR_DEBUG("unknown");
204 205 206
        break;
    }

207 208
    VIR_FREE(buffer);

209 210 211 212
    return 0;
}
#endif

213
static int
214
esxVI_CURL_Perform(esxVI_CURL *curl, const char *url)
215 216 217 218 219 220 221
{
    CURLcode errorCode;
    long responseCode = 0;
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
    const char *redirectUrl = NULL;
#endif

222
    errorCode = curl_easy_perform(curl->handle);
223 224

    if (errorCode != CURLE_OK) {
225
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
226
                     _("curl_easy_perform() returned an error: %s (%d) : %s"),
227
                     curl_easy_strerror(errorCode), errorCode, curl->error);
228 229 230
        return -1;
    }

231
    errorCode = curl_easy_getinfo(curl->handle, CURLINFO_RESPONSE_CODE,
232 233 234
                                  &responseCode);

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

    if (responseCode < 0) {
243 244 245
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned a "
                       "negative response code"));
246 247 248 249 250
        return -1;
    }

    if (responseCode == 301) {
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
251
        errorCode = curl_easy_getinfo(curl->handle, CURLINFO_REDIRECT_URL,
252 253 254
                                      &redirectUrl);

        if (errorCode != CURLE_OK) {
255
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
256 257 258
                         _("curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
                           "an error: %s (%d) : %s"),
                         curl_easy_strerror(errorCode),
259
                         errorCode, curl->error);
260
        } else {
261
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
262
                         _("The server redirects from '%s' to '%s'"), url,
263 264 265
                         redirectUrl);
        }
#else
266
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
267
                     _("The server redirects from '%s'"), url);
268 269 270 271 272 273 274 275
#endif

        return -1;
    }

    return responseCode;
}

276
int
277
esxVI_CURL_Connect(esxVI_CURL *curl, esxUtil_ParsedUri *parsedUri)
278
{
279 280
    if (curl->handle != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
M
Matthias Bolte 已提交
281
        return -1;
282 283
    }

284
    curl->handle = curl_easy_init();
285

286
    if (curl->handle == NULL) {
287 288
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL"));
289
        return -1;
290 291
    }

292 293
    curl->headers = curl_slist_append(curl->headers,
                                      "Content-Type: text/xml; charset=UTF-8");
294 295

    /*
296
     * Add an empty expect header to stop CURL from waiting for a response code
297 298 299 300 301 302
     * 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.
     */
303
    curl->headers = curl_slist_append(curl->headers, "Expect:");
304

305
    if (curl->headers == NULL) {
306 307
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not build CURL header list"));
308
        return -1;
309 310
    }

311 312 313 314
    curl_easy_setopt(curl->handle, CURLOPT_USERAGENT, "libvirt-esx");
    curl_easy_setopt(curl->handle, CURLOPT_HEADER, 0);
    curl_easy_setopt(curl->handle, CURLOPT_FOLLOWLOCATION, 0);
    curl_easy_setopt(curl->handle, CURLOPT_SSL_VERIFYPEER,
M
Matthias Bolte 已提交
315
                     parsedUri->noVerify ? 0 : 1);
316
    curl_easy_setopt(curl->handle, CURLOPT_SSL_VERIFYHOST,
M
Matthias Bolte 已提交
317
                     parsedUri->noVerify ? 0 : 2);
318 319 320
    curl_easy_setopt(curl->handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(curl->handle, CURLOPT_HTTPHEADER, curl->headers);
    curl_easy_setopt(curl->handle, CURLOPT_READFUNCTION,
M
Matthias Bolte 已提交
321
                     esxVI_CURL_ReadString);
322
    curl_easy_setopt(curl->handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
323
                     esxVI_CURL_WriteBuffer);
324
    curl_easy_setopt(curl->handle, CURLOPT_ERRORBUFFER, curl->error);
325
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
326 327
    curl_easy_setopt(curl->handle, CURLOPT_DEBUGFUNCTION, esxVI_CURL_Debug);
    curl_easy_setopt(curl->handle, CURLOPT_VERBOSE, 1);
328 329
#endif

M
Matthias Bolte 已提交
330
    if (parsedUri->proxy) {
331
        curl_easy_setopt(curl->handle, CURLOPT_PROXY,
M
Matthias Bolte 已提交
332
                         parsedUri->proxy_hostname);
333
        curl_easy_setopt(curl->handle, CURLOPT_PROXYTYPE,
M
Matthias Bolte 已提交
334
                         parsedUri->proxy_type);
335
        curl_easy_setopt(curl->handle, CURLOPT_PROXYPORT,
M
Matthias Bolte 已提交
336
                         parsedUri->proxy_port);
M
Matthias Bolte 已提交
337 338
    }

339
    if (virMutexInit(&curl->lock) < 0) {
340 341
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL mutex"));
342
        return -1;
343 344
    }

345 346
    return 0;
}
347

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
int
esxVI_CURL_Download(esxVI_CURL *curl, const char *url, char **content)
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    int responseCode = 0;

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

    virMutexLock(&curl->lock);

    curl_easy_setopt(curl->handle, CURLOPT_URL, url);
    curl_easy_setopt(curl->handle, CURLOPT_WRITEDATA, &buffer);
    curl_easy_setopt(curl->handle, CURLOPT_UPLOAD, 0);
    curl_easy_setopt(curl->handle, CURLOPT_HTTPGET, 1);

    responseCode = esxVI_CURL_Perform(curl, url);

    virMutexUnlock(&curl->lock);

    if (responseCode < 0) {
        goto cleanup;
    } else if (responseCode != 200) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("HTTP response code %d for download from '%s'"),
                     responseCode, url);
        goto cleanup;
    }

    if (virBufferError(&buffer)) {
380
        virReportOOMError();
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
        goto cleanup;
    }

    *content = virBufferContentAndReset(&buffer);

  cleanup:
    if (*content == NULL) {
        virBufferFreeAndReset(&buffer);
        return -1;
    }

    return 0;
}

int
esxVI_CURL_Upload(esxVI_CURL *curl, const char *url, const char *content)
{
    int responseCode = 0;

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

    virMutexLock(&curl->lock);

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

    responseCode = esxVI_CURL_Perform(curl, url);

    virMutexUnlock(&curl->lock);

    if (responseCode < 0) {
        return -1;
    } else if (responseCode != 200 && responseCode != 201) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("HTTP response code %d for upload to '%s'"),
                     responseCode, url);
        return -1;
    }

    return 0;
}



430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * SharedCURL
 */

static void
esxVI_SharedCURL_Lock(CURL *handle ATTRIBUTE_UNUSED, curl_lock_data data,
                      curl_lock_access access_ ATTRIBUTE_UNUSED, void *userptr)
{
    int i;
    esxVI_SharedCURL *shared = userptr;

    switch (data) {
      case CURL_LOCK_DATA_SHARE:
        i = 0;
        break;

      case CURL_LOCK_DATA_COOKIE:
        i = 1;
        break;

      case CURL_LOCK_DATA_DNS:
        i = 2;
        break;

      default:
        VIR_ERROR(_("Trying to lock unknown SharedCURL lock %d"), (int)data);
        return;
    }

    virMutexLock(&shared->locks[i]);
}

static void
esxVI_SharedCURL_Unlock(CURL *handle ATTRIBUTE_UNUSED, curl_lock_data data,
                        void *userptr)
{
    int i;
    esxVI_SharedCURL *shared = userptr;

    switch (data) {
      case CURL_LOCK_DATA_SHARE:
        i = 0;
        break;

      case CURL_LOCK_DATA_COOKIE:
        i = 1;
        break;

      case CURL_LOCK_DATA_DNS:
        i = 2;
        break;

      default:
        VIR_ERROR(_("Trying to unlock unknown SharedCURL lock %d"), (int)data);
        return;
    }

    virMutexUnlock(&shared->locks[i]);
}

/* esxVI_SharedCURL_Alloc */
ESX_VI__TEMPLATE__ALLOC(SharedCURL)

/* esxVI_SharedCURL_Free */
ESX_VI__TEMPLATE__FREE(SharedCURL,
{
    int i;

    if (item->count > 0) {
        /* Better leak than crash */
500
        VIR_ERROR(_("Trying to free SharedCURL object that is still in use"));
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        return;
    }

    if (item->handle != NULL) {
        curl_share_cleanup(item->handle);
    }

    for (i = 0; i < ARRAY_CARDINALITY(item->locks); ++i) {
        virMutexDestroy(&item->locks[i]);
    }
})

int
esxVI_SharedCURL_Add(esxVI_SharedCURL *shared, esxVI_CURL *curl)
{
    int i;

    if (curl->handle == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Cannot share uninitialized CURL handle"));
        return -1;
    }

    if (curl->shared != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Cannot share CURL handle that is already shared"));
        return -1;
    }

    if (shared->handle == NULL) {
        shared->handle = curl_share_init();

        if (shared->handle == NULL) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not initialize CURL (share)"));
            return -1;
        }

        curl_share_setopt(shared->handle, CURLSHOPT_LOCKFUNC,
                          esxVI_SharedCURL_Lock);
        curl_share_setopt(shared->handle, CURLSHOPT_UNLOCKFUNC,
                          esxVI_SharedCURL_Unlock);
        curl_share_setopt(shared->handle, CURLSHOPT_USERDATA, shared);
        curl_share_setopt(shared->handle, CURLSHOPT_SHARE,
                          CURL_LOCK_DATA_COOKIE);
        curl_share_setopt(shared->handle, CURLSHOPT_SHARE,
                          CURL_LOCK_DATA_DNS);

        for (i = 0; i < ARRAY_CARDINALITY(shared->locks); ++i) {
            if (virMutexInit(&shared->locks[i]) < 0) {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Could not initialize a CURL (share) mutex"));
                return -1;
            }
        }
    }

    curl_easy_setopt(curl->handle, CURLOPT_SHARE, shared->handle);

    curl->shared = shared;
    ++shared->count;

    return 0;
}

int
esxVI_SharedCURL_Remove(esxVI_SharedCURL *shared, esxVI_CURL *curl)
{
    if (curl->handle == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Cannot unshare uninitialized CURL handle"));
        return -1;
    }

    if (curl->shared == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Cannot unshare CURL handle that is not shared"));
        return -1;
    }

    if (curl->shared != shared) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("CURL (share) mismatch"));
        return -1;
    }

    curl_easy_setopt(curl->handle, CURLOPT_SHARE, NULL);

    curl->shared = NULL;
    --shared->count;

    return 0;
}



596 597 598 599 600 601 602 603 604 605
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Context
 */

/* esxVI_Context_Alloc */
ESX_VI__TEMPLATE__ALLOC(Context)

/* esxVI_Context_Free */
ESX_VI__TEMPLATE__FREE(Context,
{
606 607 608 609
    if (item->sessionLock != NULL) {
        virMutexDestroy(item->sessionLock);
    }

610 611 612 613 614 615 616
    esxVI_CURL_Free(&item->curl);
    VIR_FREE(item->url);
    VIR_FREE(item->ipAddress);
    VIR_FREE(item->username);
    VIR_FREE(item->password);
    esxVI_ServiceContent_Free(&item->service);
    esxVI_UserSession_Free(&item->session);
617
    VIR_FREE(item->sessionLock);
618
    esxVI_Datacenter_Free(&item->datacenter);
619
    VIR_FREE(item->datacenterPath);
620
    esxVI_ComputeResource_Free(&item->computeResource);
621
    VIR_FREE(item->computeResourcePath);
622
    esxVI_HostSystem_Free(&item->hostSystem);
623
    VIR_FREE(item->hostSystemName);
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    esxVI_SelectionSpec_Free(&item->selectSet_folderToChildEntity);
    esxVI_SelectionSpec_Free(&item->selectSet_hostSystemToParent);
    esxVI_SelectionSpec_Free(&item->selectSet_hostSystemToVm);
    esxVI_SelectionSpec_Free(&item->selectSet_hostSystemToDatastore);
    esxVI_SelectionSpec_Free(&item->selectSet_computeResourceToHost);
    esxVI_SelectionSpec_Free(&item->selectSet_computeResourceToParentToParent);
})

int
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
                      const char *ipAddress, const char *username,
                      const char *password, esxUtil_ParsedUri *parsedUri)
{
    if (ctx == NULL || url == NULL || ipAddress == NULL || username == NULL ||
        password == NULL || ctx->url != NULL || ctx->service != NULL ||
        ctx->curl != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_CURL_Alloc(&ctx->curl) < 0 ||
        esxVI_CURL_Connect(ctx->curl, parsedUri) < 0 ||
        esxVI_String_DeepCopyValue(&ctx->url, url) < 0 ||
        esxVI_String_DeepCopyValue(&ctx->ipAddress, ipAddress) < 0 ||
        esxVI_String_DeepCopyValue(&ctx->username, username) < 0 ||
        esxVI_String_DeepCopyValue(&ctx->password, password) < 0) {
650
        return -1;
651 652
    }

653 654 655 656 657 658 659 660 661 662 663
    if (VIR_ALLOC(ctx->sessionLock) < 0) {
        virReportOOMError();
        return -1;
    }

    if (virMutexInit(ctx->sessionLock) < 0) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize session mutex"));
        return -1;
    }

664
    if (esxVI_RetrieveServiceContent(ctx, &ctx->service) < 0) {
665
        return -1;
666 667
    }

668 669 670
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
671
            ctx->apiVersion = esxVI_APIVersion_25;
672
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
673
            ctx->apiVersion = esxVI_APIVersion_40;
M
Matthias Bolte 已提交
674 675 676 677 678
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.1")) {
            ctx->apiVersion = esxVI_APIVersion_41;
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.")) {
            ctx->apiVersion = esxVI_APIVersion_4x;

P
Patrice LACHANCE 已提交
679 680 681 682 683 684 685
            VIR_WARN("Found untested VI API major/minor version '%s'",
                     ctx->service->about->apiVersion);
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.0")) {
            ctx->apiVersion = esxVI_APIVersion_50;
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.")) {
            ctx->apiVersion = esxVI_APIVersion_5x;

M
Matthias Bolte 已提交
686 687
            VIR_WARN("Found untested VI API major/minor version '%s'",
                     ctx->service->about->apiVersion);
688
        } else {
689
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
P
Patrice LACHANCE 已提交
690 691
                         _("Expecting VI API major/minor version '2.5', '4.x' or "
                           "'5.x' but found '%s'"), ctx->service->about->apiVersion);
692
            return -1;
693
        }
694

695 696 697 698
        if (STREQ(ctx->service->about->productLineId, "gsx")) {
            if (STRPREFIX(ctx->service->about->version, "2.0")) {
                ctx->productVersion = esxVI_ProductVersion_GSX20;
            } else {
699
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
700 701
                             _("Expecting GSX major/minor version '2.0' but "
                               "found '%s'"), ctx->service->about->version);
702
                return -1;
703 704 705 706 707 708 709
            }
        } else if (STREQ(ctx->service->about->productLineId, "esx") ||
                   STREQ(ctx->service->about->productLineId, "embeddedEsx")) {
            if (STRPREFIX(ctx->service->about->version, "3.5")) {
                ctx->productVersion = esxVI_ProductVersion_ESX35;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_ESX40;
M
Matthias Bolte 已提交
710 711 712 713 714
            } else if (STRPREFIX(ctx->service->about->version, "4.1")) {
                ctx->productVersion = esxVI_ProductVersion_ESX41;
            } else if (STRPREFIX(ctx->service->about->version, "4.")) {
                ctx->productVersion = esxVI_ProductVersion_ESX4x;

P
Patrice LACHANCE 已提交
715 716 717 718 719 720 721
                VIR_WARN("Found untested ESX major/minor version '%s'",
                         ctx->service->about->version);
            } else if (STRPREFIX(ctx->service->about->version, "5.0")) {
                ctx->productVersion = esxVI_ProductVersion_ESX50;
            } else if (STRPREFIX(ctx->service->about->version, "5.")) {
                ctx->productVersion = esxVI_ProductVersion_ESX5x;

M
Matthias Bolte 已提交
722 723
                VIR_WARN("Found untested ESX major/minor version '%s'",
                         ctx->service->about->version);
724
            } else {
725
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
P
Patrice LACHANCE 已提交
726 727
                             _("Expecting ESX major/minor version '3.5', "
                               "'4.x' or '5.x' but found '%s'"),
728
                             ctx->service->about->version);
729
                return -1;
730 731 732 733 734 735
            }
        } else if (STREQ(ctx->service->about->productLineId, "vpx")) {
            if (STRPREFIX(ctx->service->about->version, "2.5")) {
                ctx->productVersion = esxVI_ProductVersion_VPX25;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_VPX40;
M
Matthias Bolte 已提交
736 737 738 739 740
            } else if (STRPREFIX(ctx->service->about->version, "4.1")) {
                ctx->productVersion = esxVI_ProductVersion_VPX41;
            } else if (STRPREFIX(ctx->service->about->version, "4.")) {
                ctx->productVersion = esxVI_ProductVersion_VPX4x;

P
Patrice LACHANCE 已提交
741 742 743 744 745 746 747
                VIR_WARN("Found untested VPX major/minor version '%s'",
                         ctx->service->about->version);
            } else if (STRPREFIX(ctx->service->about->version, "5.0")) {
                ctx->productVersion = esxVI_ProductVersion_VPX50;
            } else if (STRPREFIX(ctx->service->about->version, "5.")) {
                ctx->productVersion = esxVI_ProductVersion_VPX5x;

M
Matthias Bolte 已提交
748 749
                VIR_WARN("Found untested VPX major/minor version '%s'",
                         ctx->service->about->version);
750
            } else {
751
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
P
Patrice LACHANCE 已提交
752 753 754
                             _("Expecting VPX major/minor version '2.5', '4.x' "
                               "or '5.x' but found '%s'"),
                               ctx->service->about->version);
755
                return -1;
756
            }
757
        } else {
758
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
759 760
                         _("Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                           "or 'vpx' but found '%s'"),
761
                         ctx->service->about->productLineId);
762
            return -1;
763 764
        }
    } else {
765
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
766 767
                     _("Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                       "but found '%s'"), ctx->service->about->apiType);
768
        return -1;
769 770
    }

771 772 773 774 775 776 777 778 779 780 781
    if (ctx->productVersion & esxVI_ProductVersion_ESX) {
        /*
         * FIXME: Actually this should be detected by really calling
         * QueryVirtualDiskUuid and checking if a NotImplemented fault is
         * returned. But currently we don't deserialized the details of a
         * possbile fault and therefore we don't know if the fault was a
         * NotImplemented fault or not.
         */
        ctx->hasQueryVirtualDiskUuid = true;
    }

782 783 784 785
    if (ctx->productVersion & esxVI_ProductVersion_VPX) {
        ctx->hasSessionIsActive = true;
    }

786
    if (esxVI_Login(ctx, username, password, NULL, &ctx->session) < 0 ||
787
        esxVI_BuildSelectSetCollection(ctx) < 0) {
788
        return -1;
789 790
    }

791 792 793 794
    return 0;
}

int
795
esxVI_Context_LookupManagedObjects(esxVI_Context *ctx)
796 797
{
    /* Lookup Datacenter */
798 799
    if (esxVI_LookupDatacenter(ctx, NULL, ctx->service->rootFolder, NULL,
                               &ctx->datacenter,
800 801
                               esxVI_Occurrence_RequiredItem) < 0) {
        return -1;
802 803
    }

804 805 806 807 808 809 810
    ctx->datacenterPath = strdup(ctx->datacenter->name);

    if (ctx->datacenterPath == NULL) {
        virReportOOMError();
        return -1;
    }

811
    /* Lookup (Cluster)ComputeResource */
812 813
    if (esxVI_LookupComputeResource(ctx, NULL, ctx->datacenter->hostFolder,
                                    NULL, &ctx->computeResource,
814 815
                                    esxVI_Occurrence_RequiredItem) < 0) {
        return -1;
816 817 818 819 820
    }

    if (ctx->computeResource->resourcePool == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve resource pool"));
821
        return -1;
822 823
    }

824 825 826 827 828 829 830
    ctx->computeResourcePath = strdup(ctx->computeResource->name);

    if (ctx->computeResourcePath == NULL) {
        virReportOOMError();
        return -1;
    }

831
    /* Lookup HostSystem */
832 833 834
    if (esxVI_LookupHostSystem(ctx, NULL, ctx->computeResource->_reference,
                               NULL, &ctx->hostSystem,
                               esxVI_Occurrence_RequiredItem) < 0) {
835
        return -1;
836 837
    }

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    ctx->hostSystemName = strdup(ctx->hostSystem->name);

    if (ctx->hostSystemName == NULL) {
        virReportOOMError();
        return -1;
    }

    return 0;
}

int
esxVI_Context_LookupManagedObjectsByPath(esxVI_Context *ctx, const char *path)
{
    int result = -1;
    char *tmp = NULL;
    char *saveptr = NULL;
    char *previousItem = NULL;
    char *item = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ManagedObjectReference *root = NULL;
    esxVI_Folder *folder = NULL;

    tmp = strdup(path);

    if (tmp == NULL) {
        virReportOOMError();
        goto cleanup;
    }

    /* Lookup Datacenter */
    item = strtok_r(tmp, "/", &saveptr);

    if (item == NULL) {
        ESX_VI_ERROR(VIR_ERR_INVALID_ARG,
                     _("Path '%s' does not specify a datacenter"), path);
        goto cleanup;
    }

    root = ctx->service->rootFolder;

    while (ctx->datacenter == NULL && item != NULL) {
        esxVI_Folder_Free(&folder);

        /* Try to lookup item as a folder */
        if (esxVI_LookupFolder(ctx, item, root, NULL, &folder,
                               esxVI_Occurrence_OptionalItem) < 0) {
            goto cleanup;
        }

        if (folder != NULL) {
            /* It's a folder, use it as new lookup root */
            if (root != ctx->service->rootFolder) {
                esxVI_ManagedObjectReference_Free(&root);
            }

            root = folder->_reference;
            folder->_reference = NULL;
        } else {
            /* Try to lookup item as a datacenter */
            if (esxVI_LookupDatacenter(ctx, item, root, NULL, &ctx->datacenter,
                                       esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
        }

        /* Build datacenter path */
        if (virBufferUse(&buffer) > 0) {
            virBufferAddChar(&buffer, '/');
        }

        virBufferAdd(&buffer, item, -1);

        previousItem = item;
        item = strtok_r(NULL, "/", &saveptr);
    }

    if (ctx->datacenter == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find datacenter specified in '%s'"), path);
        goto cleanup;
    }

    if (virBufferError(&buffer)) {
        virReportOOMError();
        goto cleanup;
    }

    ctx->datacenterPath = virBufferContentAndReset(&buffer);

    /* Lookup (Cluster)ComputeResource */
    if (item == NULL) {
        ESX_VI_ERROR(VIR_ERR_INVALID_ARG,
                     _("Path '%s' does not specify a compute resource"), path);
        goto cleanup;
    }

    if (root != ctx->service->rootFolder) {
        esxVI_ManagedObjectReference_Free(&root);
    }

    root = ctx->datacenter->hostFolder;

    while (ctx->computeResource == NULL && item != NULL) {
        esxVI_Folder_Free(&folder);

        /* Try to lookup item as a folder */
        if (esxVI_LookupFolder(ctx, item, root, NULL, &folder,
                               esxVI_Occurrence_OptionalItem) < 0) {
            goto cleanup;
        }

        if (folder != NULL) {
            /* It's a folder, use it as new lookup root */
            if (root != ctx->datacenter->hostFolder) {
                esxVI_ManagedObjectReference_Free(&root);
            }

            root = folder->_reference;
            folder->_reference = NULL;
957
        } else {
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
            /* Try to lookup item as a compute resource */
            if (esxVI_LookupComputeResource(ctx, item, root, NULL,
                                            &ctx->computeResource,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
        }

        /* Build compute resource path */
        if (virBufferUse(&buffer) > 0) {
            virBufferAddChar(&buffer, '/');
        }

        virBufferAdd(&buffer, item, -1);

        previousItem = item;
        item = strtok_r(NULL, "/", &saveptr);
    }

    if (ctx->computeResource == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find compute resource specified in '%s'"),
                     path);
        goto cleanup;
    }

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

    if (virBufferError(&buffer)) {
        virReportOOMError();
        goto cleanup;
    }

    ctx->computeResourcePath = virBufferContentAndReset(&buffer);

    /* Lookup HostSystem */
    if (STREQ(ctx->computeResource->_reference->type,
              "ClusterComputeResource")) {
        if (item == NULL) {
            ESX_VI_ERROR(VIR_ERR_INVALID_ARG,
                         _("Path '%s' does not specify a host system"), path);
            goto cleanup;
1004
        }
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

        /* The path specified a cluster, it has to specify a host system too */
        previousItem = item;
        item = strtok_r(NULL, "/", &saveptr);
    }

    if (item != NULL) {
        ESX_VI_ERROR(VIR_ERR_INVALID_ARG,
                     _("Path '%s' ends with an excess item"), path);
        goto cleanup;
1015 1016
    }

1017 1018 1019 1020 1021 1022 1023 1024
    ctx->hostSystemName = strdup(previousItem);

    if (ctx->hostSystemName == NULL) {
        virReportOOMError();
        goto cleanup;
    }

    if (esxVI_LookupHostSystem(ctx, ctx->hostSystemName,
1025 1026
                               ctx->computeResource->_reference, NULL,
                               &ctx->hostSystem,
1027 1028
                               esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
1029 1030
    }

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    if (ctx->hostSystem == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find host system specified in '%s'"), path);
        goto cleanup;
    }

    result = 0;

  cleanup:
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

    if (root != ctx->service->rootFolder &&
        (ctx->datacenter == NULL || root != ctx->datacenter->hostFolder)) {
        esxVI_ManagedObjectReference_Free(&root);
    }

    VIR_FREE(tmp);
    esxVI_Folder_Free(&folder);

    return result;
1053 1054 1055
}

int
1056 1057
esxVI_Context_LookupManagedObjectsByHostSystemIp(esxVI_Context *ctx,
                                                 const char *hostSystemIpAddress)
1058 1059 1060 1061 1062
{
    int result = -1;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;

    /* Lookup HostSystem */
1063
    if (esxVI_FindByIp(ctx, NULL, hostSystemIpAddress, esxVI_Boolean_False,
1064
                       &managedObjectReference) < 0 ||
1065 1066 1067
        esxVI_LookupHostSystem(ctx, NULL, managedObjectReference, NULL,
                               &ctx->hostSystem,
                               esxVI_Occurrence_RequiredItem) < 0) {
1068 1069 1070
        goto cleanup;
    }

1071
    /* Lookup (Cluster)ComputeResource */
1072 1073 1074 1075 1076
    if (esxVI_LookupComputeResource(ctx, NULL, ctx->hostSystem->_reference,
                                    NULL, &ctx->computeResource,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }
1077

1078 1079 1080
    if (ctx->computeResource->resourcePool == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve resource pool"));
1081 1082 1083 1084
        goto cleanup;
    }

    /* Lookup Datacenter */
1085 1086 1087
    if (esxVI_LookupDatacenter(ctx, NULL, ctx->computeResource->_reference,
                               NULL, &ctx->datacenter,
                               esxVI_Occurrence_RequiredItem) < 0) {
1088 1089 1090 1091 1092 1093 1094
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
1095 1096 1097 1098 1099

    return result;
}

int
1100 1101 1102
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
1103
{
M
Matthias Bolte 已提交
1104
    int result = -1;
1105 1106
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
1107 1108 1109
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
1110

1111
    if (request == NULL || response == NULL || *response != NULL) {
1112
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1113
        return -1;
1114 1115
    }

1116
    if (esxVI_Response_Alloc(response) < 0) {
M
Matthias Bolte 已提交
1117
        return -1;
1118 1119
    }

1120
    virMutexLock(&ctx->curl->lock);
1121

1122 1123 1124 1125 1126
    curl_easy_setopt(ctx->curl->handle, CURLOPT_URL, ctx->url);
    curl_easy_setopt(ctx->curl->handle, CURLOPT_WRITEDATA, &buffer);
    curl_easy_setopt(ctx->curl->handle, CURLOPT_UPLOAD, 0);
    curl_easy_setopt(ctx->curl->handle, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(ctx->curl->handle, CURLOPT_POSTFIELDSIZE, strlen(request));
1127

1128
    (*response)->responseCode = esxVI_CURL_Perform(ctx->curl, ctx->url);
1129

1130
    virMutexUnlock(&ctx->curl->lock);
1131

1132
    if ((*response)->responseCode < 0) {
M
Matthias Bolte 已提交
1133
        goto cleanup;
1134 1135 1136
    }

    if (virBufferError(&buffer)) {
1137
        virReportOOMError();
M
Matthias Bolte 已提交
1138
        goto cleanup;
1139 1140
    }

1141
    (*response)->content = virBufferContentAndReset(&buffer);
1142

1143
    if ((*response)->responseCode == 500 || (*response)->responseCode == 200) {
1144
        (*response)->document = virXMLParseStringCtxt((*response)->content,
1145
                                                      _("(esx execute response)"),
1146
                                                      &xpathContext);
1147

1148
        if ((*response)->document == NULL) {
M
Matthias Bolte 已提交
1149
            goto cleanup;
1150 1151
        }

1152
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
1153
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
1154
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
1155

1156 1157
        if ((*response)->responseCode == 500) {
            (*response)->node =
1158
              virXPathNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault",
1159
                           xpathContext);
1160

1161
            if ((*response)->node == NULL) {
1162
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1163 1164
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, XPath evaluation failed"),
1165
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1166
                goto cleanup;
1167 1168
            }

1169 1170
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1171 1172
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, deserialization failed"),
1173
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1174
                goto cleanup;
1175 1176
            }

1177
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1178 1179
                         _("HTTP response code %d for call to '%s'. "
                           "Fault: %s - %s"), (*response)->responseCode,
1180
                         methodName, fault->faultcode, fault->faultstring);
1181 1182 1183 1184 1185 1186

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

M
Matthias Bolte 已提交
1187
            goto cleanup;
1188 1189 1190 1191
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
                            methodName) < 0) {
1192
                virReportOOMError();
M
Matthias Bolte 已提交
1193
                goto cleanup;
1194
            }
1195

1196
            responseNode = virXPathNode(xpathExpression, xpathContext);
1197

1198
            if (responseNode == NULL) {
1199
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1200 1201
                             _("XPath evaluation of response for call to '%s' "
                               "failed"), methodName);
M
Matthias Bolte 已提交
1202
                goto cleanup;
1203 1204
            }

1205
            xpathContext->node = responseNode;
1206
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
1207

1208 1209
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
1210 1211
                if ((*response)->node == NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1212 1213
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
1214
                    goto cleanup;
1215 1216
                } else if ((*response)->node->next != NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1217 1218
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
1219
                    goto cleanup;
1220 1221 1222 1223 1224
                }

                break;

              case esxVI_Occurrence_RequiredList:
1225
                if ((*response)->node == NULL) {
1226
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1227 1228
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
1229
                    goto cleanup;
1230 1231 1232 1233 1234 1235 1236
                }

                break;

              case esxVI_Occurrence_OptionalItem:
                if ((*response)->node != NULL &&
                    (*response)->node->next != NULL) {
1237
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1238 1239
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
1240
                    goto cleanup;
1241 1242 1243 1244
                }

                break;

1245
              case esxVI_Occurrence_OptionalList:
1246 1247 1248 1249 1250
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
                if ((*response)->node != NULL) {
1251
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1252 1253
                                 _("Call to '%s' returned something, expecting "
                                   "an empty result"), methodName);
M
Matthias Bolte 已提交
1254
                    goto cleanup;
1255 1256 1257 1258 1259
                }

                break;

              default:
1260 1261
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Invalid argument (occurrence)"));
M
Matthias Bolte 已提交
1262
                goto cleanup;
1263
            }
1264
        }
1265
    } else {
1266
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1267
                     _("HTTP response code %d for call to '%s'"),
1268
                     (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1269
        goto cleanup;
1270 1271
    }

M
Matthias Bolte 已提交
1272 1273
    result = 0;

1274
  cleanup:
M
Matthias Bolte 已提交
1275 1276 1277 1278 1279 1280
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
        esxVI_Response_Free(response);
        esxVI_Fault_Free(&fault);
    }

1281 1282 1283 1284
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
1285 1286 1287 1288 1289
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1290
 * Response
1291 1292
 */

1293
/* esxVI_Response_Alloc */
1294
ESX_VI__TEMPLATE__ALLOC(Response)
1295

1296 1297
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
1298
{
1299
    VIR_FREE(item->content);
1300

1301
    xmlFreeDoc(item->document);
1302
})
1303 1304 1305 1306 1307 1308 1309 1310



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

int
1311
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
1312 1313 1314 1315 1316
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
1317
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1318 1319 1320 1321 1322
        return -1;
    }

    *value = 0; /* undefined */

1323
    if (anyType->type != enumeration->type) {
1324
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1325
                     _("Expecting type '%s' but found '%s'"),
1326 1327
                     esxVI_Type_ToString(enumeration->type),
                     esxVI_Type_ToString(anyType->type));
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
        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;
        }
    }

1338
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1339
                 _("Unknown value '%s' for %s"), anyType->value,
1340
                 esxVI_Type_ToString(enumeration->type));
1341 1342 1343 1344 1345

    return -1;
}

int
1346
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
1347
                            int value, const char *element, virBufferPtr output)
1348 1349 1350 1351 1352
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
1353
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1354 1355 1356 1357
        return -1;
    }

    if (value == 0) { /* undefined */
1358
        return 0;
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    }

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

    if (name == NULL) {
1369
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1370 1371 1372
        return -1;
    }

1373 1374
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
1375 1376 1377 1378 1379 1380 1381 1382 1383

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
1384
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
1385 1386 1387
                              xmlNodePtr node, int *value)
{
    int i;
M
Matthias Bolte 已提交
1388
    int result = -1;
1389 1390 1391
    char *name = NULL;

    if (value == NULL) {
1392
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1393
        return -1;
1394 1395 1396 1397
    }

    *value = 0; /* undefined */

1398
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
M
Matthias Bolte 已提交
1399
        return -1;
1400 1401 1402 1403 1404
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(name, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
M
Matthias Bolte 已提交
1405 1406
            result = 0;
            break;
1407 1408 1409
        }
    }

M
Matthias Bolte 已提交
1410 1411 1412 1413
    if (result < 0) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, _("Unknown value '%s' for %s"),
                     name, esxVI_Type_ToString(enumeration->type));
    }
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

    VIR_FREE(name);

    return result;
}



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

int
1427
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
1428 1429 1430 1431
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
1432
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
        return -1;
    }

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

    next = *list;

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

    next->_next = item;

    return 0;
}

int
1453
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
1454 1455 1456 1457 1458 1459 1460
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
1461
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1462
        return -1;
1463 1464 1465
    }

    for (src = srcList; src != NULL; src = src->_next) {
1466 1467
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
            goto failure;
        }

        dest = NULL;
    }

    return 0;

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

    return -1;
}

1483
int
1484
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
1485 1486 1487
                           esxVI_List_CastFromAnyTypeFunc castFromAnyTypeFunc,
                           esxVI_List_FreeFunc freeFunc)
{
M
Matthias Bolte 已提交
1488
    int result = -1;
1489 1490 1491 1492 1493 1494
    xmlNodePtr childNode = NULL;
    esxVI_AnyType *childAnyType = NULL;
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        castFromAnyTypeFunc == NULL || freeFunc == NULL) {
1495
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1496
        return -1;
1497 1498 1499 1500 1501 1502 1503
    }

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

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
1504
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1505
                     _("Expecting type to begin with 'ArrayOf' but found '%s'"),
1506
                     anyType->other);
1507
        return -1;
1508 1509
    }

1510
    for (childNode = anyType->node->children; childNode != NULL;
1511 1512
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1513
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1514
                         _("Wrong XML element type %d"), childNode->type);
M
Matthias Bolte 已提交
1515
            goto cleanup;
1516 1517 1518 1519
        }

        esxVI_AnyType_Free(&childAnyType);

1520 1521 1522
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
M
Matthias Bolte 已提交
1523
            goto cleanup;
1524 1525 1526 1527 1528
        }

        item = NULL;
    }

M
Matthias Bolte 已提交
1529 1530
    result = 0;

1531
  cleanup:
M
Matthias Bolte 已提交
1532 1533 1534 1535 1536
    if (result < 0) {
        freeFunc(&item);
        freeFunc(list);
    }

1537 1538 1539 1540 1541
    esxVI_AnyType_Free(&childAnyType);

    return result;
}

1542
int
1543
esxVI_List_Serialize(esxVI_List *list, const char *element,
1544
                     virBufferPtr output,
1545 1546 1547 1548 1549
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
1550
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1551 1552 1553 1554
        return -1;
    }

    if (list == NULL) {
1555
        return 0;
1556 1557 1558
    }

    for (item = list; item != NULL; item = item->_next) {
1559
        if (serializeFunc(item, element, output) < 0) {
1560 1561 1562 1563 1564 1565 1566 1567
            return -1;
        }
    }

    return 0;
}

int
1568
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1569 1570 1571 1572 1573 1574 1575
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
1576
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1577 1578 1579 1580 1581 1582 1583 1584 1585
        return -1;
    }

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

    for (; node != NULL; node = node->next) {
        if (node->type != XML_ELEMENT_NODE) {
1586
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1587
                         _("Wrong XML element type %d"), node->type);
1588 1589 1590
            goto failure;
        }

1591 1592
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1593 1594 1595
            goto failure;
        }

1596
        item = NULL;
1597 1598 1599 1600 1601
    }

    return 0;

  failure:
1602
    freeFunc(&item);
1603 1604 1605 1606 1607 1608 1609 1610 1611
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1612 1613 1614 1615
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1616 1617 1618
 */

int
1619
esxVI_Alloc(void **ptrptr, size_t size)
1620 1621
{
    if (ptrptr == NULL || *ptrptr != NULL) {
1622
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1623 1624 1625 1626
        return -1;
    }

    if (virAllocN(ptrptr, size, 1) < 0) {
1627
        virReportOOMError();
1628 1629 1630 1631 1632 1633
        return -1;
    }

    return 0;
}

1634 1635


1636
int
1637 1638 1639
esxVI_BuildSelectSet(esxVI_SelectionSpec **selectSet,
                     const char *name, const char *type,
                     const char *path, const char *selectSetNames)
1640 1641 1642 1643 1644
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

1645 1646 1647 1648 1649
    if (selectSet == NULL) {
        /*
         * Don't check for *selectSet != NULL here because selectSet is a list
         * and might contain items already. This function appends to selectSet.
         */
1650
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1651 1652 1653
        return -1;
    }

1654
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1655
        esxVI_String_DeepCopyValue(&traversalSpec->name, name) < 0 ||
1656 1657
        esxVI_String_DeepCopyValue(&traversalSpec->type, type) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->path, path) < 0) {
1658 1659 1660 1661 1662 1663 1664 1665 1666
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

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

        while (currentSelectSetName != NULL && *currentSelectSetName != '\0') {
1667 1668
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
                esxVI_String_DeepCopyValue(&selectionSpec->name,
1669
                                           currentSelectSetName) < 0 ||
1670
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1671 1672 1673 1674
                                                 selectionSpec) < 0) {
                goto failure;
            }

1675
            selectionSpec = NULL;
1676 1677 1678 1679
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1680
    if (esxVI_SelectionSpec_AppendToList(selectSet,
1681 1682
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1683 1684 1685 1686 1687 1688 1689
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);
1690
    esxVI_SelectionSpec_Free(&selectionSpec);
1691 1692 1693 1694 1695

    return -1;
}


1696

1697
int
1698
esxVI_BuildSelectSetCollection(esxVI_Context *ctx)
1699
{
1700
    /* Folder -> childEntity (ManagedEntity) */
1701 1702
    if (esxVI_BuildSelectSet(&ctx->selectSet_folderToChildEntity,
                             "folderToChildEntity",
1703
                             "Folder", "childEntity", NULL) < 0) {
1704
        return -1;
1705 1706
    }

1707
    /* ComputeResource -> host (HostSystem) */
1708 1709 1710 1711
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToHost,
                             "computeResourceToHost",
                             "ComputeResource", "host", NULL) < 0) {
        return -1;
1712 1713
    }

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    /* ComputeResource -> datastore (Datastore) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToDatastore,
                             "computeResourceToDatastore",
                             "ComputeResource", "datastore", NULL) < 0) {
        return -1;
    }*/

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

1730 1731 1732 1733 1734 1735
    /* ResourcePool -> vm (VirtualMachine) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_resourcePoolToVm,
                             "resourcePoolToVm",
                             "ResourcePool", "vm", NULL) < 0) {
        return -1;
    }*/
1736

1737
    /* HostSystem -> parent (ComputeResource) */
1738 1739 1740 1741
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToParent,
                             "hostSystemToParent",
                             "HostSystem", "parent", NULL) < 0) {
        return -1;
1742 1743
    }

1744
    /* HostSystem -> vm (VirtualMachine) */
1745 1746 1747 1748
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToVm,
                             "hostSystemToVm",
                             "HostSystem", "vm", NULL) < 0) {
        return -1;
1749 1750
    }

1751
    /* HostSystem -> datastore (Datastore) */
1752 1753 1754 1755
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToDatastore,
                             "hostSystemToDatastore",
                             "HostSystem", "datastore", NULL) < 0) {
        return -1;
1756 1757
    }

1758 1759 1760 1761 1762 1763
    /* Folder -> parent (Folder, Datacenter) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "managedEntityToParent",
                             "ManagedEntity", "parent", NULL) < 0) {
        return -1;
    }
1764

1765 1766 1767 1768 1769 1770 1771
    /* ComputeResource -> parent (Folder) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "computeResourceToParent",
                             "ComputeResource", "parent",
                             "managedEntityToParent\0") < 0) {
        return -1;
    }
1772

1773
    return 0;
1774 1775 1776 1777 1778
}



int
1779
esxVI_EnsureSession(esxVI_Context *ctx)
1780
{
M
Matthias Bolte 已提交
1781
    int result = -1;
1782
    esxVI_Boolean active = esxVI_Boolean_Undefined;
1783 1784 1785 1786 1787
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;

1788 1789
    if (ctx->sessionLock == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no mutex"));
1790 1791 1792
        return -1;
    }

1793 1794 1795 1796 1797 1798 1799
    virMutexLock(ctx->sessionLock);

    if (ctx->session == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no session"));
        goto cleanup;
    }

1800 1801 1802
    if (ctx->hasSessionIsActive) {
        /*
         * Use SessionIsActive to check if there is an active session for this
E
Eric Blake 已提交
1803
         * connection, and re-login if there isn't.
1804 1805 1806
         */
        if (esxVI_SessionIsActive(ctx, ctx->session->key,
                                  ctx->session->userName, &active) < 0) {
1807
            goto cleanup;
1808
        }
1809

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

1813 1814
            if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                            &ctx->session) < 0) {
1815
                goto cleanup;
1816
            }
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
        }
    } else {
        /*
         * Query the session manager for the current session of this connection
         * and re-login if there is no current session for this connection.
         */
        if (esxVI_String_AppendValueToList(&propertyNameList,
                                           "currentSession") < 0 ||
            esxVI_LookupObjectContentByType(ctx, ctx->service->sessionManager,
                                            "SessionManager", propertyNameList,
1827 1828
                                            &sessionManager,
                                            esxVI_Occurrence_RequiredItem) < 0) {
1829
            goto cleanup;
1830 1831
        }

1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
        for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "currentSession")) {
                if (esxVI_UserSession_CastFromAnyType(dynamicProperty->val,
                                                      &currentSession) < 0) {
                    goto cleanup;
                }

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

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
        if (currentSession == NULL) {
            esxVI_UserSession_Free(&ctx->session);

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

1861
    result = 0;
M
Matthias Bolte 已提交
1862

1863
  cleanup:
1864
    virMutexUnlock(ctx->sessionLock);
1865

1866 1867 1868 1869 1870
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);

    return result;
1871 1872 1873 1874 1875
}



int
1876
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
1877 1878 1879
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
1880 1881
                                esxVI_ObjectContent **objectContentList,
                                esxVI_Occurrence occurrence)
1882
{
M
Matthias Bolte 已提交
1883
    int result = -1;
1884
    esxVI_ObjectSpec *objectSpec = NULL;
1885
    bool objectSpec_isAppended = false;
1886
    esxVI_PropertySpec *propertySpec = NULL;
1887
    bool propertySpec_isAppended = false;
1888 1889
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

1890 1891 1892 1893 1894
    if (objectContentList == NULL || *objectContentList != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

1895
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
1896
        return -1;
1897 1898 1899 1900 1901
    }

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

1902
    if (STRNEQ(root->type, type) || STREQ(root->type, "Folder")) {
1903
        if (STREQ(root->type, "Folder")) {
1904 1905
            if (STREQ(type, "Folder") || STREQ(type, "Datacenter") ||
                STREQ(type, "ComputeResource") ||
1906
                STREQ(type, "ClusterComputeResource")) {
1907 1908 1909 1910 1911 1912 1913
                objectSpec->selectSet = ctx->selectSet_folderToChildEntity;
            } else {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("Invalid lookup of '%s' from '%s'"),
                             type, root->type);
                goto cleanup;
            }
1914 1915
        } else if (STREQ(root->type, "ComputeResource") ||
                   STREQ(root->type, "ClusterComputeResource")) {
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
            if (STREQ(type, "HostSystem")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToHost;
            } else if (STREQ(type, "Datacenter")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToParentToParent;
            } else {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("Invalid lookup of '%s' from '%s'"),
                             type, root->type);
                goto cleanup;
            }
        } else if (STREQ(root->type, "HostSystem")) {
1927 1928
            if (STREQ(type, "ComputeResource") ||
                STREQ(type, "ClusterComputeResource")) {
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
                objectSpec->selectSet = ctx->selectSet_hostSystemToParent;
            } else if (STREQ(type, "VirtualMachine")) {
                objectSpec->selectSet = ctx->selectSet_hostSystemToVm;
            } else if (STREQ(type, "Datastore")) {
                objectSpec->selectSet = ctx->selectSet_hostSystemToDatastore;
            } else {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("Invalid lookup of '%s' from '%s'"),
                             type, root->type);
                goto cleanup;
            }
        } else {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("Invalid lookup from '%s'"), root->type);
            goto cleanup;
        }
1945 1946
    }

1947
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
1948
        goto cleanup;
1949 1950 1951 1952 1953
    }

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

1954 1955
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
                                        propertySpec) < 0) {
        goto cleanup;
    }

    propertySpec_isAppended = true;

    if (esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
                                      objectSpec) < 0) {
        goto cleanup;
    }

    objectSpec_isAppended = true;

    if (esxVI_RetrieveProperties(ctx, propertyFilterSpec,
1970 1971 1972 1973
                                 objectContentList) < 0) {
        goto cleanup;
    }

E
Eric Blake 已提交
1974
    if (*objectContentList == NULL) {
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
        switch (occurrence) {
          case esxVI_Occurrence_OptionalItem:
          case esxVI_Occurrence_OptionalList:
            result = 0;
            break;

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

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

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

M
Matthias Bolte 已提交
1999
        goto cleanup;
2000 2001
    }

2002
    result = 0;
2003 2004 2005 2006 2007 2008

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

2014 2015 2016 2017 2018
    if (propertySpec != NULL) {
        propertySpec->type = NULL;
        propertySpec->pathSet = NULL;
    }

2019 2020 2021 2022 2023 2024 2025 2026
    if (!objectSpec_isAppended) {
        esxVI_ObjectSpec_Free(&objectSpec);
    }

    if (!propertySpec_isAppended) {
        esxVI_PropertySpec_Free(&propertySpec);
    }

2027 2028 2029 2030 2031 2032 2033
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);

    return result;
}



2034
int
2035
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
2036 2037 2038 2039 2040 2041 2042 2043 2044
                             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
2045
                     (dynamicProperty->val, managedEntityStatus);
2046 2047 2048
        }
    }

2049
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2050 2051
                 _("Missing '%s' property while looking for "
                   "ManagedEntityStatus"), propertyName);
2052 2053 2054 2055 2056 2057

    return -1;
}



2058
int
2059
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
2060 2061 2062 2063 2064 2065 2066 2067
                                  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
2068
                     (dynamicProperty->val, powerState);
2069 2070 2071
        }
    }

2072 2073
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("Missing 'runtime.powerState' property"));
2074 2075 2076 2077 2078 2079

    return -1;
}



2080 2081
int
esxVI_GetVirtualMachineQuestionInfo
2082
  (esxVI_ObjectContent *virtualMachine,
2083 2084 2085 2086 2087
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (questionInfo == NULL || *questionInfo != NULL) {
2088
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2089 2090 2091 2092 2093 2094 2095
        return -1;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
2096
                  (dynamicProperty->val, questionInfo) < 0) {
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
                return -1;
            }
        }
    }

    return 0;
}



2107 2108
int
esxVI_GetBoolean(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2109
                 esxVI_Boolean *value, esxVI_Occurrence occurrence)
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
{
    esxVI_DynamicProperty *dynamicProperty;

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

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

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

    if (*value == esxVI_Boolean_Undefined &&
M
Matthias Bolte 已提交
2132
        occurrence == esxVI_Occurrence_RequiredItem) {
2133 2134 2135 2136 2137 2138 2139 2140
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}

M
Matthias Bolte 已提交
2141 2142


2143 2144
int
esxVI_GetLong(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2145
              esxVI_Long **value, esxVI_Occurrence occurrence)
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
{
    esxVI_DynamicProperty *dynamicProperty;

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

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

            break;
        }
    }

M
Matthias Bolte 已提交
2165
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
2166 2167 2168 2169 2170 2171 2172 2173
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}

2174 2175 2176 2177 2178


int
esxVI_GetStringValue(esxVI_ObjectContent *objectContent,
                     const char *propertyName,
M
Matthias Bolte 已提交
2179
                     char **value, esxVI_Occurrence occurrence)
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
{
    esxVI_DynamicProperty *dynamicProperty;

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

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

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

M
Matthias Bolte 已提交
2201
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



int
esxVI_GetManagedObjectReference(esxVI_ObjectContent *objectContent,
                                const char *propertyName,
                                esxVI_ManagedObjectReference **value,
M
Matthias Bolte 已提交
2216
                                esxVI_Occurrence occurrence)
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
{
    esxVI_DynamicProperty *dynamicProperty;

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

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

            break;
        }
    }

M
Matthias Bolte 已提交
2237
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



2248
int
2249
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
2250
                                        esxVI_VirtualMachinePowerState powerState,
2251
                                        bool inverse)
2252
{
M
Matthias Bolte 已提交
2253
    bool success = false;
2254 2255 2256 2257 2258
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
M
Matthias Bolte 已提交
2259
    int count = 0;
2260

2261
    if (esxVI_String_AppendValueToList(&propertyNameList,
2262
                                       "runtime.powerState") < 0 ||
2263 2264
        esxVI_LookupVirtualMachineList(ctx, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2265
        goto cleanup;
2266 2267 2268 2269 2270 2271 2272 2273 2274
    }

    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
2275
                      (dynamicProperty->val, &powerState_) < 0) {
M
Matthias Bolte 已提交
2276
                    goto cleanup;
2277 2278
                }

2279 2280
                if ((!inverse && powerState_ == powerState) ||
                    ( inverse && powerState_ != powerState)) {
M
Matthias Bolte 已提交
2281
                    count++;
2282 2283 2284 2285 2286 2287 2288
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

M
Matthias Bolte 已提交
2289 2290
    success = true;

2291 2292 2293 2294
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
2295
    return success ? count : -1;
2296 2297 2298 2299 2300
}



int
2301
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
2302 2303 2304 2305
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
2306
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
2307 2308

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
2309 2310
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("ObjectContent does not reference a virtual machine"));
2311 2312 2313 2314 2315 2316
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
2317
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2318
                         _("Could not parse positive integer from '%s'"),
2319 2320 2321 2322 2323 2324 2325
                         virtualMachine->obj->value);
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
2326
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2327 2328 2329 2330 2331 2332 2333
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2334
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2335 2336 2337 2338 2339 2340 2341
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

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

                if (*name == NULL) {
2342
                    virReportOOMError();
2343 2344 2345
                    goto failure;
                }

2346
                if (virVMXUnescapeHexPercent(*name) < 0) {
2347 2348 2349 2350 2351
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                                 _("Domain name contains invalid escape sequence"));
                    goto failure;
                }

2352 2353 2354 2355 2356
                break;
            }
        }

        if (*name == NULL) {
2357 2358
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not get name of virtual machine"));
2359 2360 2361 2362 2363
            goto failure;
        }
    }

    if (uuid != NULL) {
2364
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
2365 2366 2367 2368 2369 2370 2371 2372 2373
                                         &configStatus) < 0) {
            goto failure;
        }

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

                    uuid_string = dynamicProperty->val->string;
                    break;
2381
                }
2382
            }
2383

2384
            if (uuid_string == NULL) {
2385 2386
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Could not get UUID of virtual machine"));
2387
                goto failure;
2388 2389
            }

2390
            if (virUUIDParse(uuid_string, uuid) < 0) {
2391
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2392
                             _("Could not parse UUID from string '%s'"),
2393 2394 2395 2396 2397
                             uuid_string);
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
2398

2399
            VIR_WARN("Cannot access UUID, because 'configStatus' property "
2400
                      "indicates a config problem");
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
        }
    }

    return 0;

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

    return -1;
}



2416 2417
int
esxVI_GetNumberOfSnapshotTrees
2418 2419
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList, bool recurse,
   bool leaves)
2420 2421 2422 2423 2424 2425
{
    int count = 0;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList; snapshotTree != NULL;
         snapshotTree = snapshotTree->_next) {
2426 2427
        if (!(leaves && snapshotTree->childSnapshotList))
            count++;
2428 2429
        if (recurse)
            count += esxVI_GetNumberOfSnapshotTrees
2430
                (snapshotTree->childSnapshotList, true, leaves);
2431 2432 2433 2434 2435 2436 2437 2438 2439
    }

    return count;
}



int
esxVI_GetSnapshotTreeNames(esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
2440 2441
                           char **names, int nameslen, bool recurse,
                           bool leaves)
2442 2443 2444 2445 2446 2447 2448 2449 2450
{
    int count = 0;
    int result;
    int i;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList;
         snapshotTree != NULL && count < nameslen;
         snapshotTree = snapshotTree->_next) {
2451 2452
        if (!(leaves && snapshotTree->childSnapshotList)) {
            names[count] = strdup(snapshotTree->name);
2453

2454 2455 2456 2457
            if (names[count] == NULL) {
                virReportOOMError();
                goto failure;
            }
2458

2459 2460
            count++;
        }
2461 2462 2463 2464 2465

        if (count >= nameslen) {
            break;
        }

2466 2467 2468 2469
        if (recurse) {
            result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
                                                names + count,
                                                nameslen - count,
2470
                                                true, leaves);
2471

2472 2473 2474
            if (result < 0) {
                goto failure;
            }
2475

2476 2477
            count += result;
        }
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
    }

    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 ||
2502
        (snapshotTreeParent && *snapshotTreeParent != NULL)) {
2503 2504 2505 2506 2507 2508 2509 2510
        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;
2511 2512
            if (snapshotTreeParent)
                *snapshotTreeParent = NULL;
2513 2514 2515 2516 2517 2518
            return 1;
        }

        if (esxVI_GetSnapshotTreeByName(candidate->childSnapshotList, name,
                                        snapshotTree, snapshotTreeParent,
                                        occurrence) > 0) {
2519
            if (snapshotTreeParent && *snapshotTreeParent == NULL) {
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
                *snapshotTreeParent = candidate;
            }

            return 1;
        }
    }

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

        return -1;
    }
}



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

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

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

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

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

    return -1;
}



M
Matthias Bolte 已提交
2574 2575 2576 2577
int
esxVI_LookupHostSystemProperties(esxVI_Context *ctx,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **hostSystem)
M
Matthias Bolte 已提交
2578
{
2579 2580
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "HostSystem", propertyNameList,
2581 2582
                                           hostSystem,
                                           esxVI_Occurrence_RequiredItem);
M
Matthias Bolte 已提交
2583 2584 2585 2586
}



2587
int
2588 2589 2590
esxVI_LookupVirtualMachineList(esxVI_Context *ctx,
                               esxVI_String *propertyNameList,
                               esxVI_ObjectContent **virtualMachineList)
2591
{
2592 2593 2594 2595
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource->resourcePool
     *        for cluster support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "VirtualMachine", propertyNameList,
2596 2597
                                           virtualMachineList,
                                           esxVI_Occurrence_OptionalList);
2598 2599 2600 2601 2602
}



int
2603
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
2604
                                 esxVI_String *propertyNameList,
2605
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
2606
                                 esxVI_Occurrence occurrence)
2607
{
M
Matthias Bolte 已提交
2608
    int result = -1;
2609
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
2610
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
2611 2612

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2613
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2614 2615 2616
        return -1;
    }

2617 2618
    virUUIDFormat(uuid, uuid_string);

2619 2620
    if (esxVI_FindByUuid(ctx, ctx->datacenter->_reference, uuid_string,
                         esxVI_Boolean_True, &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2621
        return -1;
2622 2623
    }

2624
    if (managedObjectReference == NULL) {
M
Matthias Bolte 已提交
2625
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2626 2627 2628
            result = 0;

            goto cleanup;
2629
        } else {
2630
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2631 2632
                         _("Could not find domain with UUID '%s'"),
                         uuid_string);
M
Matthias Bolte 已提交
2633
            goto cleanup;
2634 2635 2636
        }
    }

2637
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2638
                                        "VirtualMachine", propertyNameList,
2639 2640
                                        virtualMachine,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2641
        goto cleanup;
2642 2643
    }

M
Matthias Bolte 已提交
2644 2645
    result = 0;

2646 2647 2648 2649
  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
M
Matthias Bolte 已提交
2650 2651 2652 2653
}



2654 2655 2656 2657 2658 2659
int
esxVI_LookupVirtualMachineByName(esxVI_Context *ctx, const char *name,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2660
    int result = -1;
2661 2662 2663 2664 2665 2666
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate = NULL;

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

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
2674 2675
        esxVI_LookupVirtualMachineList(ctx, completePropertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2676
        goto cleanup;
2677 2678 2679 2680 2681 2682 2683 2684
    }

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

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
M
Matthias Bolte 已提交
2685
            goto cleanup;
2686 2687 2688 2689 2690 2691 2692
        }

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

        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0) {
M
Matthias Bolte 已提交
2693
            goto cleanup;
2694 2695 2696 2697 2698 2699 2700
        }

        break;
    }

    if (*virtualMachine == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2701 2702 2703
            result = 0;

            goto cleanup;
2704 2705
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2706
                         _("Could not find domain with name '%s'"), name);
M
Matthias Bolte 已提交
2707
            goto cleanup;
2708 2709 2710
        }
    }

M
Matthias Bolte 已提交
2711 2712
    result = 0;

2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;
}



2723 2724
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2725
  (esxVI_Context *ctx, const unsigned char *uuid,
2726
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
2727
   bool autoAnswer)
2728
{
M
Matthias Bolte 已提交
2729
    int result = -1;
2730 2731 2732
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;
2733
    bool blocked;
2734

2735
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2736
                                  propertyNameList) < 0 ||
2737
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2738 2739
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2740
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2741
                                         virtualMachine,
M
Matthias Bolte 已提交
2742
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2743
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
2744 2745
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
2746
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
M
Matthias Bolte 已提交
2747
        goto cleanup;
2748 2749 2750
    }

    if (questionInfo != NULL &&
2751
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
2752 2753
                                           questionInfo, autoAnswer,
                                           &blocked) < 0) {
M
Matthias Bolte 已提交
2754
        goto cleanup;
2755 2756 2757
    }

    if (pendingTaskInfoList != NULL) {
2758 2759
        ESX_VI_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                     _("Other tasks are pending for this domain"));
M
Matthias Bolte 已提交
2760
        goto cleanup;
2761 2762
    }

M
Matthias Bolte 已提交
2763 2764
    result = 0;

2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;
}



2775 2776 2777 2778 2779 2780 2781 2782
int
esxVI_LookupDatastoreList(esxVI_Context *ctx, esxVI_String *propertyNameList,
                          esxVI_ObjectContent **datastoreList)
{
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource for cluster
     *        support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "Datastore", propertyNameList,
2783 2784
                                           datastoreList,
                                           esxVI_Occurrence_OptionalList);
2785 2786 2787 2788
}



M
Matthias Bolte 已提交
2789
int
2790 2791
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
2792
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
2793
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
2794
{
M
Matthias Bolte 已提交
2795
    int result = -1;
M
Matthias Bolte 已提交
2796 2797 2798
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
2799
    char *name_candidate;
M
Matthias Bolte 已提交
2800 2801

    if (datastore == NULL || *datastore != NULL) {
2802
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
2803 2804 2805 2806
        return -1;
    }

    /* Get all datastores */
2807
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
2808
                                  propertyNameList) < 0 ||
2809 2810
        esxVI_String_AppendValueToList(&completePropertyNameList,
                                       "summary.name") < 0 ||
2811 2812
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
M
Matthias Bolte 已提交
2813
        goto cleanup;
M
Matthias Bolte 已提交
2814 2815
    }

2816 2817 2818 2819 2820 2821 2822
    /* Search for a matching datastore */
    for (candidate = datastoreList; candidate != NULL;
         candidate = candidate->_next) {
        name_candidate = NULL;

        if (esxVI_GetStringValue(candidate, "summary.name", &name_candidate,
                                 esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2823
            goto cleanup;
M
Matthias Bolte 已提交
2824
        }
2825 2826 2827 2828 2829 2830

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

2831 2832 2833 2834
            /* Found datastore with matching name */
            result = 0;

            goto cleanup;
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
        }
    }

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

    result = 0;

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

    return result;
}


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

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

    /* Get all datastores */
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "host") < 0 ||
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
        goto cleanup;
M
Matthias Bolte 已提交
2881 2882 2883 2884 2885
    }

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

M
Matthias Bolte 已提交
2888 2889
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
2890 2891 2892
            if (STREQ(dynamicProperty->name, "host")) {
                if (esxVI_DatastoreHostMount_CastListFromAnyType
                      (dynamicProperty->val, &datastoreHostMountList) < 0) {
M
Matthias Bolte 已提交
2893
                    goto cleanup;
2894 2895 2896 2897 2898 2899
                }

                break;
            }
        }

2900 2901
        if (datastoreHostMountList == NULL) {
            continue;
2902 2903
        }

2904 2905 2906 2907 2908 2909 2910
        for (datastoreHostMount = datastoreHostMountList;
             datastoreHostMount != NULL;
             datastoreHostMount = datastoreHostMount->_next) {
            if (STRNEQ(ctx->hostSystem->_reference->value,
                       datastoreHostMount->key->value)) {
                continue;
            }
2911

2912 2913
            if (STRPREFIX(absolutePath, datastoreHostMount->mountInfo->path)) {
                if (esxVI_ObjectContent_DeepCopy(datastore, candidate) < 0) {
M
Matthias Bolte 已提交
2914
                    goto cleanup;
M
Matthias Bolte 已提交
2915 2916
                }

2917
                /* Found datastore with matching mount path */
2918 2919 2920
                result = 0;

                goto cleanup;
M
Matthias Bolte 已提交
2921 2922 2923 2924
            }
        }
    }

2925 2926 2927 2928
    if (*datastore == NULL && occurrence != esxVI_Occurrence_OptionalItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find datastore containing absolute path '%s'"),
                     absolutePath);
M
Matthias Bolte 已提交
2929
        goto cleanup;
M
Matthias Bolte 已提交
2930 2931
    }

M
Matthias Bolte 已提交
2932 2933
    result = 0;

M
Matthias Bolte 已提交
2934 2935 2936
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
2937
    esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
M
Matthias Bolte 已提交
2938 2939

    return result;
2940 2941 2942 2943
}



2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
int
esxVI_LookupDatastoreHostMount(esxVI_Context *ctx,
                               esxVI_ManagedObjectReference *datastore,
                               esxVI_DatastoreHostMount **hostMount)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_DatastoreHostMount *hostMountList = NULL;
    esxVI_DatastoreHostMount *candidate = NULL;

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

    if (esxVI_String_AppendValueToList(&propertyNameList, "host") < 0 ||
        esxVI_LookupObjectContentByType(ctx, datastore, "Datastore",
2963 2964
                                        propertyNameList, &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
        goto cleanup;
    }

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

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

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

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

        break;
    }

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

    result = 0;

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

    return result;
}


3012 3013 3014 3015
int
esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
                           esxVI_ManagedObjectReference *task,
                           esxVI_TaskInfo **taskInfo)
3016
{
M
Matthias Bolte 已提交
3017
    int result = -1;
3018 3019 3020 3021 3022
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (taskInfo == NULL || *taskInfo != NULL) {
3023
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3024 3025 3026
        return -1;
    }

3027 3028
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
3029 3030
                                        &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3031
        goto cleanup;
3032 3033 3034 3035 3036
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
3037
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
3038
                                               taskInfo) < 0) {
M
Matthias Bolte 已提交
3039
                goto cleanup;
3040 3041 3042 3043 3044 3045 3046 3047
            }

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

M
Matthias Bolte 已提交
3048 3049
    result = 0;

3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);

    return result;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
3061
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
3062 3063
   esxVI_TaskInfo **pendingTaskInfoList)
{
M
Matthias Bolte 已提交
3064
    int result = -1;
3065 3066 3067 3068 3069 3070 3071
    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) {
3072
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3073 3074 3075 3076 3077 3078 3079 3080
        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
3081
                  (dynamicProperty->val, &recentTaskList) < 0) {
M
Matthias Bolte 已提交
3082
                goto cleanup;
3083 3084 3085 3086 3087 3088 3089 3090 3091
            }

            break;
        }
    }

    /* Lookup task info for each task */
    for (recentTask = recentTaskList; recentTask != NULL;
         recentTask = recentTask->_next) {
3092
        if (esxVI_LookupTaskInfoByTask(ctx, recentTask, &taskInfo) < 0) {
M
Matthias Bolte 已提交
3093
            goto cleanup;
3094 3095 3096 3097
        }

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
3098
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
3099
                                            taskInfo) < 0) {
M
Matthias Bolte 已提交
3100
                goto cleanup;
3101 3102 3103 3104 3105 3106 3107 3108
            }

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

M
Matthias Bolte 已提交
3109 3110
    result = 0;

3111
  cleanup:
M
Matthias Bolte 已提交
3112 3113 3114 3115
    if (result < 0) {
        esxVI_TaskInfo_Free(pendingTaskInfoList);
    }

3116 3117 3118 3119 3120 3121 3122 3123 3124 3125
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



int
3126
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
3127
                                            const unsigned char *uuid,
3128
                                            esxVI_Occurrence occurrence,
3129
                                            bool autoAnswer, bool *blocked)
3130
{
M
Matthias Bolte 已提交
3131
    int result = -1;
3132 3133 3134 3135
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

3136
    if (esxVI_String_AppendValueToList(&propertyNameList,
3137
                                       "runtime.question") < 0 ||
3138
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
3139
                                         &virtualMachine, occurrence) < 0) {
M
Matthias Bolte 已提交
3140
        goto cleanup;
3141 3142
    }

3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
    if (virtualMachine != NULL) {
        if (esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
                                                &questionInfo) < 0) {
            goto cleanup;
        }

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

M
Matthias Bolte 已提交
3157 3158
    result = 0;

3159 3160 3161 3162 3163 3164 3165 3166 3167 3168
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);

    return result;
}



3169 3170 3171 3172 3173
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
M
Matthias Bolte 已提交
3174
    int result = -1;
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

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

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "snapshot.rootSnapshotList") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3189
        goto cleanup;
3190 3191 3192 3193 3194 3195 3196
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3197
                goto cleanup;
3198 3199 3200 3201 3202 3203 3204 3205
            }

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

M
Matthias Bolte 已提交
3206 3207
    result = 0;

3208
  cleanup:
M
Matthias Bolte 已提交
3209 3210 3211 3212
    if (result < 0) {
        esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);
    }

3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



int
esxVI_LookupCurrentSnapshotTree
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **currentSnapshotTree,
   esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
3227
    int result = -1;
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *currentSnapshot = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;

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

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "snapshot.currentSnapshot\0"
                                           "snapshot.rootSnapshotList\0") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3246
        goto cleanup;
3247 3248 3249 3250 3251 3252 3253
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.currentSnapshot")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, &currentSnapshot) < 0) {
M
Matthias Bolte 已提交
3254
                goto cleanup;
3255 3256 3257 3258
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3259
                goto cleanup;
3260 3261 3262 3263 3264 3265 3266 3267
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (currentSnapshot == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
3268 3269 3270
            result = 0;

            goto cleanup;
3271 3272 3273
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                         _("Domain has no current snapshot"));
M
Matthias Bolte 已提交
3274
            goto cleanup;
3275 3276 3277 3278 3279 3280
        }
    }

    if (rootSnapshotTreeList == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not lookup root snapshot list"));
M
Matthias Bolte 已提交
3281
        goto cleanup;
3282 3283 3284 3285 3286 3287
    }

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

M
Matthias Bolte 已提交
3291 3292
    result = 0;

3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



3304 3305 3306
int
esxVI_LookupFileInfoByDatastorePath(esxVI_Context *ctx,
                                    const char *datastorePath,
3307
                                    bool lookupFolder,
3308 3309 3310 3311 3312 3313
                                    esxVI_FileInfo **fileInfo,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    char *datastoreName = NULL;
    char *directoryName = NULL;
3314
    char *directoryAndFileName = NULL;
3315
    char *fileName = NULL;
3316
    size_t length;
3317 3318 3319 3320 3321
    char *datastorePathWithoutFileName = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
3322
    esxVI_FolderFileQuery *folderFileQuery = NULL;
3323 3324 3325 3326 3327
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3328
    char *taskInfoErrorMessage = NULL;
3329 3330 3331 3332 3333 3334 3335 3336 3337
    esxVI_TaskInfo *taskInfo = NULL;
    esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL;

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

    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName,
3338
                                   &directoryName, &directoryAndFileName) < 0) {
3339 3340 3341
        goto cleanup;
    }

3342 3343 3344 3345 3346
    if (STREQ(directoryName, directoryAndFileName)) {
        /*
         * The <path> part of the datatore path didn't contain a '/', assume
         * that the <path> part is actually the file name.
         */
3347 3348 3349 3350 3351
        if (virAsprintf(&datastorePathWithoutFileName, "[%s]",
                        datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
3352 3353 3354 3355

        if (esxVI_String_DeepCopyValue(&fileName, directoryAndFileName) < 0) {
            goto cleanup;
        }
3356 3357 3358 3359 3360 3361
    } else {
        if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s",
                        datastoreName, directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376

        length = strlen(directoryName);

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

        if (esxVI_String_DeepCopyValue(&fileName,
                                       directoryAndFileName + length + 1) < 0) {
            goto cleanup;
        }
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399
    }

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

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

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

3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
    if (lookupFolder) {
        if (esxVI_FolderFileQuery_Alloc(&folderFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(folderFileQuery)) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_VmDiskFileQuery_Alloc(&vmDiskFileQuery) < 0 ||
            esxVI_VmDiskFileQueryFlags_Alloc(&vmDiskFileQuery->details) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(vmDiskFileQuery)) < 0) {
            goto cleanup;
        }
3415

3416 3417 3418 3419 3420
        vmDiskFileQuery->details->diskType = esxVI_Boolean_False;
        vmDiskFileQuery->details->capacityKb = esxVI_Boolean_True;
        vmDiskFileQuery->details->hardwareVersion = esxVI_Boolean_False;
        vmDiskFileQuery->details->controllerType = esxVI_Boolean_True;
        vmDiskFileQuery->details->diskExtents = esxVI_Boolean_False;
3421

3422 3423 3424 3425 3426 3427
        if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
            goto cleanup;
        }
3428

3429 3430 3431 3432 3433 3434
        if (esxVI_FloppyImageFileQuery_Alloc(&floppyImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(floppyImageFileQuery)) < 0) {
            goto cleanup;
        }
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
    }

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

    searchSpec->matchPattern->value = fileName;

    /* Search datastore for file */
    if (esxVI_SearchDatastore_Task(ctx, hostDatastoreBrowser,
                                   datastorePathWithoutFileName, searchSpec,
                                   &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3448
                                    false, &taskInfoState,
3449
                                    &taskInfoErrorMessage) < 0) {
3450 3451 3452 3453 3454
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3455 3456
                     _("Could not search in datastore '%s': %s"),
                     datastoreName, taskInfoErrorMessage);
3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
        goto cleanup;
    }

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

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

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

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

    result = 0;

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

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3493
    VIR_FREE(directoryAndFileName);
3494 3495 3496 3497 3498 3499 3500
    VIR_FREE(fileName);
    VIR_FREE(datastorePathWithoutFileName);
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    esxVI_ManagedObjectReference_Free(&task);
3501
    VIR_FREE(taskInfoErrorMessage);
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
    esxVI_TaskInfo_Free(&taskInfo);
    esxVI_HostDatastoreBrowserSearchResults_Free(&searchResults);

    return result;
}



int
esxVI_LookupDatastoreContentByDatastoreName
  (esxVI_Context *ctx, const char *datastoreName,
   esxVI_HostDatastoreBrowserSearchResults **searchResultsList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    char *datastorePath = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3526
    char *taskInfoErrorMessage = NULL;
3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592
    esxVI_TaskInfo *taskInfo = NULL;

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

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

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

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

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

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

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

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

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

    if (esxVI_SearchDatastoreSubFolders_Task(ctx, hostDatastoreBrowser,
                                             datastorePath, searchSpec,
                                             &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3593
                                    false, &taskInfoState,
3594
                                    &taskInfoErrorMessage) < 0) {
3595 3596 3597 3598 3599
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3600 3601
                     _("Could not serach in datastore '%s': %s"),
                     datastoreName, taskInfoErrorMessage);
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619
        goto cleanup;
    }

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

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    VIR_FREE(datastorePath);
    esxVI_ManagedObjectReference_Free(&task);
3620
    VIR_FREE(taskInfoErrorMessage);
3621 3622 3623 3624 3625 3626 3627
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641
int
esxVI_LookupStorageVolumeKeyByDatastorePath(esxVI_Context *ctx,
                                            const char *datastorePath,
                                            char **key)
{
    int result = -1;
    esxVI_FileInfo *fileInfo = NULL;
    char *uuid_string = NULL;

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

3642 3643 3644 3645
    if (ctx->hasQueryVirtualDiskUuid) {
        if (esxVI_LookupFileInfoByDatastorePath
              (ctx, datastorePath, false, &fileInfo,
               esxVI_Occurrence_RequiredItem) < 0) {
3646 3647 3648
            goto cleanup;
        }

3649 3650 3651 3652 3653 3654 3655
        if (esxVI_VmDiskFileInfo_DynamicCast(fileInfo) != NULL) {
            /* VirtualDisks have a UUID, use it as key */
            if (esxVI_QueryVirtualDiskUuid(ctx, datastorePath,
                                           ctx->datacenter->_reference,
                                           &uuid_string) < 0) {
                goto cleanup;
            }
3656

3657 3658 3659 3660 3661 3662 3663 3664
            if (VIR_ALLOC_N(*key, VIR_UUID_STRING_BUFLEN) < 0) {
                virReportOOMError();
                goto cleanup;
            }

            if (esxUtil_ReformatUuid(uuid_string, *key) < 0) {
                goto cleanup;
            }
3665
        }
3666 3667 3668
    }

    if (*key == NULL) {
3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
        /* Other files don't have a UUID, fall back to the path as key */
        if (esxVI_String_DeepCopyValue(key, datastorePath) < 0) {
            goto cleanup;
        }
    }

    result = 0;

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

    return result;
}



3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709
int
esxVI_LookupAutoStartDefaults(esxVI_Context *ctx,
                              esxVI_AutoStartDefaults **defaults)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostAutoStartManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

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

    /*
     * Lookup HostAutoStartManagerConfig from the HostAutoStartManager because
     * for some reason this is much faster than looking up the same info from
     * the HostSystem config.
     */
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.defaults") < 0 ||
        esxVI_LookupObjectContentByType
          (ctx, ctx->hostSystem->configManager->autoStartManager,
           "HostAutoStartManager", propertyNameList,
3710
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766
        goto cleanup;
    }

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

            break;
        }
    }

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

    result = 0;

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

    return result;
}



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

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

    /*
     * Lookup HostAutoStartManagerConfig from the HostAutoStartManager because
     * for some reason this is much faster than looking up the same info from
     * the HostSystem config.
     */
    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.powerInfo") < 0 ||
        esxVI_LookupObjectContentByType
          (ctx, ctx->hostSystem->configManager->autoStartManager,
           "HostAutoStartManager", propertyNameList,
3767
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
        goto cleanup;
    }

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

            break;
        }
    }

    result = 0;

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

    return result;
}



3794 3795
int
esxVI_HandleVirtualMachineQuestion
3796
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
3797 3798
   esxVI_VirtualMachineQuestionInfo *questionInfo, bool autoAnswer,
   bool *blocked)
3799
{
M
Matthias Bolte 已提交
3800
    int result = -1;
3801 3802 3803 3804 3805 3806
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

3807
    if (blocked == NULL) {
3808 3809 3810 3811
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

3812
    *blocked = false;
3813

3814 3815 3816 3817
    if (questionInfo->choice->choiceInfo != NULL) {
        for (elementDescription = questionInfo->choice->choiceInfo;
             elementDescription != NULL;
             elementDescription = elementDescription->_next) {
3818
            virBufferAsprintf(&buffer, "'%s'", elementDescription->label);
3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833

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

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

            ++answerIndex;
        }

        if (virBufferError(&buffer)) {
3834
            virReportOOMError();
M
Matthias Bolte 已提交
3835
            goto cleanup;
3836 3837 3838 3839 3840
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

3841
    if (autoAnswer) {
3842
        if (possibleAnswers == NULL) {
3843
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3844 3845
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
3846
                         questionInfo->text);
3847

3848
            *blocked = true;
M
Matthias Bolte 已提交
3849
            goto cleanup;
3850
        } else if (answerChoice == NULL) {
3851
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3852 3853 3854
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s, but no "
                           "default answer is specified"), questionInfo->text,
3855
                         possibleAnswers);
3856

3857
            *blocked = true;
M
Matthias Bolte 已提交
3858
            goto cleanup;
3859 3860 3861 3862 3863 3864 3865
        }

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

3866
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
3867
                           answerChoice->key) < 0) {
M
Matthias Bolte 已提交
3868
            goto cleanup;
3869 3870 3871
        }
    } else {
        if (possibleAnswers != NULL) {
3872
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3873 3874
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s"),
3875 3876
                         questionInfo->text, possibleAnswers);
        } else {
3877
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
3878 3879
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
3880 3881 3882
                         questionInfo->text);
        }

3883
        *blocked = true;
M
Matthias Bolte 已提交
3884
        goto cleanup;
3885 3886
    }

M
Matthias Bolte 已提交
3887 3888
    result = 0;

3889
  cleanup:
M
Matthias Bolte 已提交
3890 3891 3892 3893
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

3894 3895 3896 3897 3898 3899 3900
    VIR_FREE(possibleAnswers);

    return result;
}



3901
int
3902
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
3903
                            esxVI_ManagedObjectReference *task,
3904
                            const unsigned char *virtualMachineUuid,
3905
                            esxVI_Occurrence virtualMachineOccurrence,
3906
                            bool autoAnswer, esxVI_TaskInfoState *finalState,
3907
                            char **errorMessage)
3908
{
M
Matthias Bolte 已提交
3909
    int result = -1;
3910
    esxVI_ObjectSpec *objectSpec = NULL;
3911
    bool objectSpec_isAppended = false;
3912
    esxVI_PropertySpec *propertySpec = NULL;
3913
    bool propertySpec_isAppended = false;
3914 3915 3916 3917 3918 3919 3920 3921 3922
    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;
3923
    bool blocked;
3924
    esxVI_TaskInfo *taskInfo = NULL;
3925

3926 3927 3928 3929 3930
    if (errorMessage == NULL || *errorMessage != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

3931 3932 3933
    version = strdup("");

    if (version == NULL) {
3934
        virReportOOMError();
M
Matthias Bolte 已提交
3935
        return -1;
3936 3937
    }

3938
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
3939
        goto cleanup;
3940 3941 3942 3943 3944
    }

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

3945
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
3946
        goto cleanup;
3947 3948 3949 3950
    }

    propertySpec->type = task->type;

3951
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
3952
                                       "info.state") < 0 ||
3953 3954
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968
                                        propertySpec) < 0) {
        goto cleanup;
    }

    propertySpec_isAppended = true;

    if (esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
                                      objectSpec) < 0) {
        goto cleanup;
    }

    objectSpec_isAppended = true;

    if (esxVI_CreateFilter(ctx, propertyFilterSpec, esxVI_Boolean_True,
3969
                           &propertyFilter) < 0) {
M
Matthias Bolte 已提交
3970
        goto cleanup;
3971 3972 3973 3974 3975 3976
    }

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

3977 3978
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
3979 3980
                  (ctx, virtualMachineUuid, virtualMachineOccurrence,
                   autoAnswer, &blocked) < 0) {
3981 3982 3983 3984 3985
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
3986
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
M
Matthias Bolte 已提交
3987
                    goto cleanup;
3988 3989 3990
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
3991
                    if (esxVI_CancelTask(ctx, task) < 0 && blocked) {
3992
                        VIR_ERROR(_("Cancelable task is blocked by an "
E
Eric Blake 已提交
3993
                                     "unanswered question but cancellation "
3994
                                     "failed"));
3995
                    }
3996
                } else if (blocked) {
3997
                    VIR_ERROR(_("Non-cancelable task is blocked by an "
3998
                                 "unanswered question"));
3999 4000 4001 4002
                }

                /* FIXME: Enable error reporting here again */

M
Matthias Bolte 已提交
4003
                goto cleanup;
4004 4005 4006
            }
        }

4007
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
M
Matthias Bolte 已提交
4008
            goto cleanup;
4009 4010 4011 4012 4013 4014
        }

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

        if (version == NULL) {
4015
            virReportOOMError();
M
Matthias Bolte 已提交
4016
            goto cleanup;
4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046
        }

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

4047
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
M
Matthias Bolte 已提交
4048
            goto cleanup;
4049 4050 4051
        }
    }

4052
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
4053
        VIR_DEBUG("DestroyPropertyFilter failed");
4054 4055
    }

4056
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
M
Matthias Bolte 已提交
4057
        goto cleanup;
4058 4059
    }

4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088
    if (*finalState != esxVI_TaskInfoState_Success) {
        if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
            goto cleanup;
        }

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

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

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

M
Matthias Bolte 已提交
4089 4090
    result = 0;

4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
  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;
    }

4104 4105 4106 4107 4108 4109 4110 4111
    if (!objectSpec_isAppended) {
        esxVI_ObjectSpec_Free(&objectSpec);
    }

    if (!propertySpec_isAppended) {
        esxVI_PropertySpec_Free(&propertySpec);
    }

4112 4113 4114 4115
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);
    esxVI_ManagedObjectReference_Free(&propertyFilter);
    VIR_FREE(version);
    esxVI_UpdateSet_Free(&updateSet);
4116
    esxVI_TaskInfo_Free(&taskInfo);
4117 4118 4119

    return result;
}
4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134



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;

4135
    memset(parsedHostCpuIdInfo, 0, sizeof(*parsedHostCpuIdInfo));
4136 4137 4138 4139 4140 4141 4142 4143

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

    for (r = 0; r < 4; ++r) {
        if (strlen(input[r]) != expectedLength) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("HostCpuIdInfo register '%s' has an unexpected length"),
                         name[r]);
M
Matthias Bolte 已提交
4144
            return -1;
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
        }

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

            if (i + 4 < expectedLength && input[r][i + 4] != ':') {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("HostCpuIdInfo register '%s' has an unexpected format"),
                             name[r]);
M
Matthias Bolte 已提交
4158
                return -1;
4159 4160 4161 4162 4163 4164
            }
        }
    }

    return 0;
}
4165 4166 4167 4168 4169 4170 4171 4172 4173



int
esxVI_ProductVersionToDefaultVirtualHWVersion(esxVI_ProductVersion productVersion)
{
    /*
     * virtualHW.version compatibility matrix:
     *
P
Patrice LACHANCE 已提交
4174 4175 4176 4177 4178 4179
     *              4 7 8   API
     *   ESX 3.5    +       2.5
     *   ESX 4.0    + +     4.0
     *   ESX 4.1    + +     4.1
     *   ESX 5.0    + + +   5.0
     *   GSX 2.0    + +     2.5
4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
     */
    switch (productVersion) {
      case esxVI_ProductVersion_ESX35:
      case esxVI_ProductVersion_VPX25:
        return 4;

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

      case esxVI_ProductVersion_ESX4x:
      case esxVI_ProductVersion_VPX4x:
        return 7;

P
Patrice LACHANCE 已提交
4197 4198 4199 4200 4201 4202 4203 4204
      case esxVI_ProductVersion_ESX50:
      case esxVI_ProductVersion_VPX50:
        return 8;

      case esxVI_ProductVersion_ESX5x:
      case esxVI_ProductVersion_VPX5x:
        return 8;

4205 4206 4207 4208 4209 4210
      default:
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Unexpected product version"));
        return -1;
    }
}
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258




#define ESX_VI__TEMPLATE__PROPERTY__CAST_FROM_ANY_TYPE_IGNORE(_name)          \
    if (STREQ(dynamicProperty->name, #_name)) {                               \
        continue;                                                             \
    }



#define ESX_VI__TEMPLATE__PROPERTY__CAST_FROM_ANY_TYPE(_type, _name)          \
    if (STREQ(dynamicProperty->name, #_name)) {                               \
        if (esxVI_##_type##_CastFromAnyType(dynamicProperty->val,             \
                                            &(*ptrptr)->_name) < 0) {         \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        continue;                                                             \
    }



#define ESX_VI__TEMPLATE__PROPERTY__CAST_LIST_FROM_ANY_TYPE(_type, _name)     \
    if (STREQ(dynamicProperty->name, #_name)) {                               \
        if (esxVI_##_type##_CastListFromAnyType(dynamicProperty->val,         \
                                                &(*ptrptr)->_name) < 0) {     \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        continue;                                                             \
    }



#define ESX_VI__TEMPLATE__PROPERTY__CAST_VALUE_FROM_ANY_TYPE(_type, _name)    \
    if (STREQ(dynamicProperty->name, #_name)) {                               \
        if (esxVI_##_type##_CastValueFromAnyType(dynamicProperty->val,        \
                                                 &(*ptrptr)->_name) < 0) {    \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        continue;                                                             \
    }



#define ESX_VI__TEMPLATE__LOOKUP(_type, _complete_properties,                 \
4259
                                 _cast_from_anytype)                          \
4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293
    int                                                                       \
    esxVI_Lookup##_type(esxVI_Context *ctx, const char* name /* optional */,  \
                        esxVI_ManagedObjectReference *root,                   \
                        esxVI_String *selectedPropertyNameList /* optional */,\
                        esxVI_##_type **ptrptr, esxVI_Occurrence occurrence)  \
    {                                                                         \
        int result = -1;                                                      \
        const char *completePropertyNameValueList = _complete_properties;     \
        esxVI_String *propertyNameList = NULL;                                \
        esxVI_ObjectContent *objectContent = NULL;                            \
        esxVI_ObjectContent *objectContentList = NULL;                        \
        esxVI_DynamicProperty *dynamicProperty = NULL;                        \
                                                                              \
        if (ptrptr == NULL || *ptrptr != NULL) {                              \
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",                        \
                         _("Invalid argument"));                              \
            return -1;                                                        \
        }                                                                     \
                                                                              \
        propertyNameList = selectedPropertyNameList;                          \
                                                                              \
        if (propertyNameList == NULL &&                                       \
            esxVI_String_AppendValueListToList                                \
              (&propertyNameList, completePropertyNameValueList) < 0) {       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_LookupManagedObjectHelper(ctx, name, root, #_type,          \
                                            propertyNameList, &objectContent, \
                                            &objectContentList,               \
                                            occurrence) < 0) {                \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
4294 4295 4296 4297 4298 4299
        if (objectContent == NULL) {                                          \
            /* not found, exit early */                                       \
            result = 0;                                                       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
        if (esxVI_##_type##_Alloc(ptrptr) < 0) {                              \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_ManagedObjectReference_DeepCopy(&(*ptrptr)->_reference,     \
                                                  objectContent->obj) < 0) {  \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        for (dynamicProperty = objectContent->propSet;                        \
             dynamicProperty != NULL;                                         \
             dynamicProperty = dynamicProperty->_next) {                      \
            _cast_from_anytype                                                \
                                                                              \
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);      \
        }                                                                     \
                                                                              \
        if (esxVI_##_type##_Validate(*ptrptr, selectedPropertyNameList) < 0) {\
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        result = 0;                                                           \
                                                                              \
      cleanup:                                                                \
        if (result < 0) {                                                     \
            esxVI_##_type##_Free(ptrptr);                                     \
        }                                                                     \
                                                                              \
        if (propertyNameList != selectedPropertyNameList) {                   \
            esxVI_String_Free(&propertyNameList);                             \
        }                                                                     \
                                                                              \
        esxVI_ObjectContent_Free(&objectContentList);                         \
                                                                              \
        return result;                                                        \
    }



static int
esxVI_LookupManagedObjectHelper(esxVI_Context *ctx,
                                const char *name /* optional */,
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
                                esxVI_ObjectContent **objectContent,
                                esxVI_ObjectContent **objectContentList,
                                esxVI_Occurrence occurrence)
{
    int result = -1;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate;

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

    if (!esxVI_String_ListContainsValue(propertyNameList, "name")) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing 'name' property in %s lookup"), type);
        goto cleanup;
    }

    if (esxVI_LookupObjectContentByType(ctx, root, type, propertyNameList,
                                        objectContentList,
                                        esxVI_Occurrence_OptionalList) < 0) {
        goto cleanup;
    }

    /* Search for a matching item */
    if (name != NULL) {
        for (candidate = *objectContentList; candidate != NULL;
             candidate = candidate->_next) {
            name_candidate = NULL;

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

            if (STREQ(name_candidate, name)) {
                /* Found item with matching name */
                break;
            }
        }
    } else {
        candidate = *objectContentList;
    }

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

        result = 0;

        goto cleanup;
    }

    result = 0;

  cleanup:
    if (result < 0) {
        esxVI_ObjectContent_Free(objectContentList);
    } else {
        *objectContent = candidate;
    }

    return result;
}



#include "esx_vi.generated.c"