esx_vi.c 166.3 KB
Newer Older
1 2 3
/*
 * esx_vi.c: client for the VMware VI API 2.5 to manage ESX hosts
 *
4
 * Copyright (C) 2010-2012 Red Hat, Inc.
5
 * Copyright (C) 2009-2012, 2014 Matthias Bolte <matthias.bolte@googlemail.com>
6 7 8 9 10 11 12 13 14 15 16 17
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24
 *
 */

#include <config.h>

25
#include <poll.h>
26 27 28
#include <libxml/parser.h>
#include <libxml/xpathInternals.h>

29
#include "virbuffer.h"
30
#include "viralloc.h"
31
#include "virlog.h"
32
#include "viruuid.h"
33
#include "vmx.h"
34
#include "virxml.h"
35 36 37
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
38
#include "virstring.h"
39 40 41

#define VIR_FROM_THIS VIR_FROM_ESX

42
VIR_LOG_INIT("esx.esx_vi");
43 44 45 46 47 48 49 50 51

#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
        if (!ptrptr || *ptrptr) {                                             \
55 56 57 58 59 60 61
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument")); \
            return -1;                                                  \
        }                                                               \
                                                                        \
        if (VIR_ALLOC(*ptrptr) < 0)                                     \
            return -1;                                                  \
        return 0;                                                       \
62 63
    }

64 65


66 67 68 69
#define ESX_VI__TEMPLATE__FREE(_type, _body)                                  \
    void                                                                      \
    esxVI_##_type##_Free(esxVI_##_type **ptrptr)                              \
    {                                                                         \
70
        esxVI_##_type *item ATTRIBUTE_UNUSED;                                 \
71
                                                                              \
72
        if (!ptrptr || !(*ptrptr)) {                                          \
73 74 75 76 77 78 79 80 81 82 83 84 85
            return;                                                           \
        }                                                                     \
                                                                              \
        item = *ptrptr;                                                       \
                                                                              \
        _body                                                                 \
                                                                              \
        VIR_FREE(*ptrptr);                                                    \
    }



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
86
 * CURL
87 88
 */

89 90
/* esxVI_CURL_Alloc */
ESX_VI__TEMPLATE__ALLOC(CURL)
91

92 93
/* esxVI_CURL_Free */
ESX_VI__TEMPLATE__FREE(CURL,
94
{
95
    esxVI_SharedCURL *shared = item->shared;
M
Matthias Bolte 已提交
96
    esxVI_MultiCURL *multi = item->multi;
97

98
    if (shared) {
99 100
        esxVI_SharedCURL_Remove(shared, item);

101
        if (shared->count == 0)
102 103 104
            esxVI_SharedCURL_Free(&shared);
    }

105
    if (multi) {
M
Matthias Bolte 已提交
106 107
        esxVI_MultiCURL_Remove(multi, item);

108
        if (multi->count == 0)
M
Matthias Bolte 已提交
109 110 111
            esxVI_MultiCURL_Free(&multi);
    }

112
    if (item->handle)
113
        curl_easy_cleanup(item->handle);
114

115
    if (item->headers)
116
        curl_slist_free_all(item->headers);
117

118 119
    virMutexDestroy(&item->lock);
})
120 121

static size_t
122
esxVI_CURL_ReadString(char *data, size_t size, size_t nmemb, void *userdata)
M
Matthias Bolte 已提交
123
{
124
    const char *content = *(const char **)userdata;
M
Matthias Bolte 已提交
125 126 127
    size_t available = 0;
    size_t requested = size * nmemb;

128
    if (!content)
M
Matthias Bolte 已提交
129 130 131 132
        return 0;

    available = strlen(content);

133
    if (available == 0)
M
Matthias Bolte 已提交
134 135
        return 0;

136
    if (requested > available)
M
Matthias Bolte 已提交
137 138 139 140
        requested = available;

    memcpy(data, content, requested);

141
    *(const char **)userdata = content + requested;
M
Matthias Bolte 已提交
142 143 144 145 146

    return requested;
}

static size_t
147
esxVI_CURL_WriteBuffer(char *data, size_t size, size_t nmemb, void *userdata)
148
{
149 150
    virBufferPtr buffer = userdata;

151
    if (buffer) {
152 153 154 155 156 157
        /*
         * Using a virBuffer to store the download data limits the downloadable
         * size. This is no problem as esxVI_CURL_Download and esxVI_CURL_Perform
         * are meant to download small things such as VMX files, VMDK metadata
         * files and SOAP responses.
         */
158
        if (size * nmemb > INT32_MAX / 2 - virBufferUse(buffer))
159 160 161
            return 0;

        virBufferAdd(buffer, data, size * nmemb);
162 163 164 165 166 167 168 169 170 171 172

        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 已提交
173
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
174
                 char *info, size_t size, void *userdata ATTRIBUTE_UNUSED)
175
{
176 177 178 179 180 181 182 183 184 185 186 187
    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.
     */
188
    if (VIR_ALLOC_N(buffer, size + 1) < 0)
189 190
        return 0;

191
    if (!virStrncpy(buffer, info, size, size + 1)) {
192 193 194 195
        VIR_FREE(buffer);
        return 0;
    }

196 197
    switch (type) {
      case CURLINFO_TEXT:
198
        if (size > 0 && buffer[size - 1] == '\n')
199 200 201
            buffer[size - 1] = '\0';

        VIR_DEBUG("CURLINFO_TEXT [[[[%s]]]]", buffer);
202 203 204
        break;

      case CURLINFO_HEADER_IN:
205
        VIR_DEBUG("CURLINFO_HEADER_IN [[[[%s]]]]", buffer);
206 207 208
        break;

      case CURLINFO_HEADER_OUT:
209
        VIR_DEBUG("CURLINFO_HEADER_OUT [[[[%s]]]]", buffer);
210 211 212
        break;

      case CURLINFO_DATA_IN:
213
        VIR_DEBUG("CURLINFO_DATA_IN [[[[%s]]]]", buffer);
214 215 216
        break;

      case CURLINFO_DATA_OUT:
217
        VIR_DEBUG("CURLINFO_DATA_OUT [[[[%s]]]]", buffer);
218 219 220
        break;

      default:
221
        VIR_DEBUG("unknown");
222 223 224
        break;
    }

225 226
    VIR_FREE(buffer);

227 228 229 230
    return 0;
}
#endif

231
static int
232
esxVI_CURL_Perform(esxVI_CURL *curl, const char *url)
233 234 235 236 237 238 239
{
    CURLcode errorCode;
    long responseCode = 0;
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
    const char *redirectUrl = NULL;
#endif

240
    errorCode = curl_easy_perform(curl->handle);
241 242

    if (errorCode != CURLE_OK) {
243 244 245
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("curl_easy_perform() returned an error: %s (%d) : %s"),
                       curl_easy_strerror(errorCode), errorCode, curl->error);
246 247 248
        return -1;
    }

249
    errorCode = curl_easy_getinfo(curl->handle, CURLINFO_RESPONSE_CODE,
250 251 252
                                  &responseCode);

    if (errorCode != CURLE_OK) {
253 254 255 256
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned an "
                         "error: %s (%d) : %s"), curl_easy_strerror(errorCode),
                       errorCode, curl->error);
257 258 259 260
        return -1;
    }

    if (responseCode < 0) {
261 262 263
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned a "
                         "negative response code"));
264 265 266 267 268
        return -1;
    }

    if (responseCode == 301) {
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
269
        errorCode = curl_easy_getinfo(curl->handle, CURLINFO_REDIRECT_URL,
270 271 272
                                      &redirectUrl);

        if (errorCode != CURLE_OK) {
273 274 275 276 277
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
                             "an error: %s (%d) : %s"),
                           curl_easy_strerror(errorCode),
                           errorCode, curl->error);
278
        } else {
279 280 281
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("The server redirects from '%s' to '%s'"), url,
                           redirectUrl);
282 283
        }
#else
284 285
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("The server redirects from '%s'"), url);
286 287 288 289 290 291 292 293
#endif

        return -1;
    }

    return responseCode;
}

294
int
295
esxVI_CURL_Connect(esxVI_CURL *curl, esxUtil_ParsedUri *parsedUri)
296
{
297
    if (curl->handle) {
298
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
M
Matthias Bolte 已提交
299
        return -1;
300 301
    }

302
    curl->handle = curl_easy_init();
303

304
    if (!curl->handle) {
305 306
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize CURL"));
307
        return -1;
308 309
    }

310 311
    curl->headers = curl_slist_append(curl->headers,
                                      "Content-Type: text/xml; charset=UTF-8");
312 313

    /*
314
     * Add an empty expect header to stop CURL from waiting for a response code
315 316 317 318 319 320
     * 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.
     */
321
    curl->headers = curl_slist_append(curl->headers, "Expect:");
322

323
    if (!curl->headers) {
324 325
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not build CURL header list"));
326
        return -1;
327 328
    }

329
    curl_easy_setopt(curl->handle, CURLOPT_USERAGENT, "libvirt-esx");
330
    curl_easy_setopt(curl->handle, CURLOPT_NOSIGNAL, 1);
331 332 333
    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 已提交
334
                     parsedUri->noVerify ? 0 : 1);
335
    curl_easy_setopt(curl->handle, CURLOPT_SSL_VERIFYHOST,
M
Matthias Bolte 已提交
336
                     parsedUri->noVerify ? 0 : 2);
337 338 339
    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 已提交
340
                     esxVI_CURL_ReadString);
341
    curl_easy_setopt(curl->handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
342
                     esxVI_CURL_WriteBuffer);
343
    curl_easy_setopt(curl->handle, CURLOPT_ERRORBUFFER, curl->error);
344
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
345 346
    curl_easy_setopt(curl->handle, CURLOPT_DEBUGFUNCTION, esxVI_CURL_Debug);
    curl_easy_setopt(curl->handle, CURLOPT_VERBOSE, 1);
347 348
#endif

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

358
    if (virMutexInit(&curl->lock) < 0) {
359 360
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize CURL mutex"));
361
        return -1;
362 363
    }

364 365
    return 0;
}
366

367
int
368 369
esxVI_CURL_Download(esxVI_CURL *curl, const char *url, char **content,
                    unsigned long long offset, unsigned long long *length)
370
{
371
    char *range = NULL;
372 373 374
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    int responseCode = 0;

375
    if (!content || *content) {
376
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
377 378 379
        return -1;
    }

380
    if (length && *length > 0) {
381 382 383 384 385 386
        /*
         * Using a virBuffer to store the download data limits the downloadable
         * size. This is no problem as esxVI_CURL_Download is meant to download
         * small things such as VMX of VMDK metadata files.
         */
        if (*length > INT32_MAX / 2) {
387 388
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Download length it too large"));
389 390 391
            return -1;
        }

392
        if (virAsprintf(&range, "%llu-%llu", offset, offset + *length - 1) < 0)
393 394
            goto cleanup;
    } else if (offset > 0) {
395
        if (virAsprintf(&range, "%llu-", offset) < 0)
396 397 398
            goto cleanup;
    }

399 400 401
    virMutexLock(&curl->lock);

    curl_easy_setopt(curl->handle, CURLOPT_URL, url);
402
    curl_easy_setopt(curl->handle, CURLOPT_RANGE, range);
403 404 405 406 407 408 409 410 411 412
    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;
413
    } else if (responseCode != 200 && responseCode != 206) {
414 415 416
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("HTTP response code %d for download from '%s'"),
                       responseCode, url);
417 418 419
        goto cleanup;
    }

420
    if (virBufferCheckError(&buffer) < 0)
421 422
        goto cleanup;

423
    if (length)
424 425
        *length = virBufferUse(&buffer);

426 427
    *content = virBufferContentAndReset(&buffer);

428
 cleanup:
429 430
    VIR_FREE(range);

431
    if (!(*content)) {
432 433 434 435 436 437 438 439 440 441 442 443
        virBufferFreeAndReset(&buffer);
        return -1;
    }

    return 0;
}

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

444
    if (!content) {
445
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
446 447 448 449 450 451
        return -1;
    }

    virMutexLock(&curl->lock);

    curl_easy_setopt(curl->handle, CURLOPT_URL, url);
452
    curl_easy_setopt(curl->handle, CURLOPT_RANGE, NULL);
453 454 455 456 457 458 459 460 461 462 463
    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) {
464 465 466
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("HTTP response code %d for upload to '%s'"),
                       responseCode, url);
467 468 469 470 471 472 473 474
        return -1;
    }

    return 0;
}



475 476 477 478 479 480 481 482
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * SharedCURL
 */

static void
esxVI_SharedCURL_Lock(CURL *handle ATTRIBUTE_UNUSED, curl_lock_data data,
                      curl_lock_access access_ ATTRIBUTE_UNUSED, void *userptr)
{
483
    size_t i;
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    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)
{
511
    size_t i;
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
    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,
{
541
    size_t i;
542 543 544

    if (item->count > 0) {
        /* Better leak than crash */
545
        VIR_ERROR(_("Trying to free SharedCURL object that is still in use"));
546 547 548
        return;
    }

549
    if (item->handle)
550 551
        curl_share_cleanup(item->handle);

552
    for (i = 0; i < ARRAY_CARDINALITY(item->locks); ++i)
553 554 555 556 557 558
        virMutexDestroy(&item->locks[i]);
})

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

561
    if (!curl->handle) {
562 563
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot share uninitialized CURL handle"));
564 565 566
        return -1;
    }

567
    if (curl->shared) {
568 569
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot share CURL handle that is already shared"));
570 571 572
        return -1;
    }

573
    if (!shared->handle) {
574 575
        shared->handle = curl_share_init();

576
        if (!shared->handle) {
577 578
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not initialize CURL (share)"));
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
            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) {
594 595
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Could not initialize a CURL (share) mutex"));
596 597 598 599 600
                return -1;
            }
        }
    }

M
Matthias Bolte 已提交
601 602
    virMutexLock(&curl->lock);

603 604 605 606 607
    curl_easy_setopt(curl->handle, CURLOPT_SHARE, shared->handle);

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

M
Matthias Bolte 已提交
608 609
    virMutexUnlock(&curl->lock);

610 611 612 613 614 615
    return 0;
}

int
esxVI_SharedCURL_Remove(esxVI_SharedCURL *shared, esxVI_CURL *curl)
{
616
    if (!curl->handle) {
617 618
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot unshare uninitialized CURL handle"));
619 620 621
        return -1;
    }

622
    if (!curl->shared) {
623 624
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot unshare CURL handle that is not shared"));
625 626 627 628
        return -1;
    }

    if (curl->shared != shared) {
629
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("CURL (share) mismatch"));
630 631 632
        return -1;
    }

M
Matthias Bolte 已提交
633 634
    virMutexLock(&curl->lock);

635 636 637 638 639
    curl_easy_setopt(curl->handle, CURLOPT_SHARE, NULL);

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

M
Matthias Bolte 已提交
640 641 642 643 644 645 646 647 648 649 650
    virMutexUnlock(&curl->lock);

    return 0;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * MultiCURL
 */

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
#if ESX_EMULATE_CURL_MULTI_WAIT

static int
esxVI_MultiCURL_SocketCallback(CURL *handle ATTRIBUTE_UNUSED,
                               curl_socket_t fd, int action,
                               void *callback_opaque,
                               void *socket_opaque ATTRIBUTE_UNUSED)
{
    esxVI_MultiCURL *multi = callback_opaque;
    size_t i;
    struct pollfd *pollfd = NULL;
    struct pollfd dummy;

    if (action & CURL_POLL_REMOVE) {
        for (i = 0; i < multi->npollfds; ++i) {
            if (multi->pollfds[i].fd == fd) {
                VIR_DELETE_ELEMENT(multi->pollfds, i, multi->npollfds);
                break;
            }
        }
    } else {
        for (i = 0; i < multi->npollfds; ++i) {
            if (multi->pollfds[i].fd == fd) {
                pollfd = &multi->pollfds[i];
                break;
            }
        }

        if (pollfd == NULL) {
            if (VIR_APPEND_ELEMENT(multi->pollfds, multi->npollfds, dummy) < 0)
                return 0; /* curl_multi_socket() doc says "The callback MUST return 0." */

            pollfd = &multi->pollfds[multi->npollfds - 1];
        }

        pollfd->fd = fd;
        pollfd->events = 0;

        if (action & CURL_POLL_IN)
            pollfd->events |= POLLIN;

        if (action & CURL_POLL_OUT)
            pollfd->events |= POLLOUT;
    }

    return 0;
}

static int
esxVI_MultiCURL_TimerCallback(CURLM *handle ATTRIBUTE_UNUSED,
J
Ján Tomko 已提交
701 702
                              long timeout_ms ATTRIBUTE_UNUSED,
                              void *callback_opaque)
703 704 705 706 707 708 709 710 711 712
{
    esxVI_MultiCURL *multi = callback_opaque;

    multi->timeoutPending = true;

    return 0;
}

#endif

M
Matthias Bolte 已提交
713 714 715 716 717 718 719 720 721 722 723 724
/* esxVI_MultiCURL_Alloc */
ESX_VI__TEMPLATE__ALLOC(MultiCURL)

/* esxVI_MultiCURL_Free */
ESX_VI__TEMPLATE__FREE(MultiCURL,
{
    if (item->count > 0) {
        /* Better leak than crash */
        VIR_ERROR(_("Trying to free MultiCURL object that is still in use"));
        return;
    }

725
    if (item->handle)
M
Matthias Bolte 已提交
726
        curl_multi_cleanup(item->handle);
727 728 729 730

#if ESX_EMULATE_CURL_MULTI_WAIT
    VIR_FREE(item->pollfds);
#endif
M
Matthias Bolte 已提交
731 732 733 734 735
})

int
esxVI_MultiCURL_Add(esxVI_MultiCURL *multi, esxVI_CURL *curl)
{
736
    if (!curl->handle) {
737 738
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot add uninitialized CURL handle to a multi handle"));
M
Matthias Bolte 已提交
739 740 741
        return -1;
    }

742
    if (curl->multi) {
743 744
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot add CURL handle to a multi handle twice"));
M
Matthias Bolte 已提交
745 746 747
        return -1;
    }

748
    if (!multi->handle) {
M
Matthias Bolte 已提交
749 750
        multi->handle = curl_multi_init();

751
        if (!multi->handle) {
752 753
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not initialize CURL (multi)"));
M
Matthias Bolte 已提交
754 755
            return -1;
        }
756 757 758 759 760 761 762 763 764

#if ESX_EMULATE_CURL_MULTI_WAIT
        curl_multi_setopt(multi->handle, CURLMOPT_SOCKETFUNCTION,
                          esxVI_MultiCURL_SocketCallback);
        curl_multi_setopt(multi->handle, CURLMOPT_SOCKETDATA, multi);
        curl_multi_setopt(multi->handle, CURLMOPT_TIMERFUNCTION,
                          esxVI_MultiCURL_TimerCallback);
        curl_multi_setopt(multi->handle, CURLMOPT_TIMERDATA, multi);
#endif
M
Matthias Bolte 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    }

    virMutexLock(&curl->lock);

    curl_multi_add_handle(multi->handle, curl->handle);

    curl->multi = multi;
    ++multi->count;

    virMutexUnlock(&curl->lock);

    return 0;
}

int
esxVI_MultiCURL_Remove(esxVI_MultiCURL *multi, esxVI_CURL *curl)
{
782
    if (!curl->handle) {
783 784 785
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot remove uninitialized CURL handle from a "
                         "multi handle"));
M
Matthias Bolte 已提交
786 787 788
        return -1;
    }

789
    if (!curl->multi) {
790 791 792
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot remove CURL handle from a multi handle when it "
                         "wasn't added before"));
M
Matthias Bolte 已提交
793 794 795 796
        return -1;
    }

    if (curl->multi != multi) {
797
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("CURL (multi) mismatch"));
M
Matthias Bolte 已提交
798 799 800 801 802 803 804 805 806 807 808 809
        return -1;
    }

    virMutexLock(&curl->lock);

    curl_multi_remove_handle(multi->handle, curl->handle);

    curl->multi = NULL;
    --multi->count;

    virMutexUnlock(&curl->lock);

810 811 812
    return 0;
}

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
#if ESX_EMULATE_CURL_MULTI_WAIT

int
esxVI_MultiCURL_Wait(esxVI_MultiCURL *multi, int *runningHandles)
{
    long timeout = -1;
    CURLMcode errorCode;
    int rc;
    size_t i;
    int action;

    if (multi->timeoutPending) {
        do {
            errorCode = curl_multi_socket_action(multi->handle, CURL_SOCKET_TIMEOUT,
                                                 0, runningHandles);
        } while (errorCode == CURLM_CALL_MULTI_SOCKET);

        if (errorCode != CURLM_OK) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not trigger socket action: %s (%d)"),
                           curl_multi_strerror(errorCode), errorCode);
            return -1;
        }

        multi->timeoutPending = false;
    }

    if (multi->npollfds == 0)
        return 0;

    curl_multi_timeout(multi->handle, &timeout);

845
    if (timeout < 0)
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
        timeout = 1000; /* default to 1 sec timeout */

    do {
        rc = poll(multi->pollfds, multi->npollfds, timeout);
    } while (rc < 0 && (errno == EAGAIN || errno == EINTR));

    if (rc < 0) {
        virReportSystemError(errno, "%s", _("Could not wait for transfer"));
        return -1;
    }

    for (i = 0; i < multi->npollfds && rc > 0; ++i) {
        if (multi->pollfds[i].revents == 0)
            continue;

        --rc;
        action = 0;

        if (multi->pollfds[i].revents & POLLIN)
            action |= CURL_POLL_IN;

        if (multi->pollfds[i].revents & POLLOUT)
            action |= CURL_POLL_OUT;

        do {
            errorCode = curl_multi_socket_action(multi->handle,
                                                 multi->pollfds[i].fd, action,
                                                 runningHandles);
        } while (errorCode == CURLM_CALL_MULTI_SOCKET);

        if (errorCode != CURLM_OK) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not trigger socket action: %s (%d)"),
                           curl_multi_strerror(errorCode), errorCode);
            return -1;
        }
    }

    return 0;
}

#else

int
esxVI_MultiCURL_Wait(esxVI_MultiCURL *multi, int *runningHandles)
{
    long timeout = -1;
    CURLMcode errorCode;

    curl_multi_timeout(multi->handle, &timeout);

    if (timeout < 0)
        timeout = 1000; /* default to 1 sec timeout */

    errorCode = curl_multi_wait(multi->handle, NULL, 0, timeout, NULL);

    if (errorCode != CURLM_OK) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not wait for transfer: %s (%d)"),
                       curl_multi_strerror(errorCode), errorCode);
        return -1;
    }

    return esxVI_MultiCURL_Perform(multi, runningHandles);
}

#endif

int
esxVI_MultiCURL_Perform(esxVI_MultiCURL *multi, int *runningHandles)
{
    CURLMcode errorCode;

    do {
        errorCode = curl_multi_perform(multi->handle, runningHandles);
    } while (errorCode == CURLM_CALL_MULTI_PERFORM);

    if (errorCode != CURLM_OK) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not transfer data: %s (%d)"),
                       curl_multi_strerror(errorCode), errorCode);
        return -1;
    }

    return 0;
}

/* Returns -1 on error, 0 if there is no DONE message, 1 if there is a DONE message */
int
esxVI_MultiCURL_CheckFirstMessage(esxVI_MultiCURL *multi, long *responseCode,
                                  CURLcode *errorCode)
{
    int messagesInQueue;
    CURLMsg* msg = curl_multi_info_read(multi->handle, &messagesInQueue);

    *responseCode = 0;

    if (!msg || msg->msg != CURLMSG_DONE)
        return 0;

    *errorCode = msg->data.result;

    if (*errorCode != CURLE_OK)
        return -1;

    curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, responseCode);

    return 1;
}

956 957


958 959 960 961 962 963 964 965 966 967
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Context
 */

/* esxVI_Context_Alloc */
ESX_VI__TEMPLATE__ALLOC(Context)

/* esxVI_Context_Free */
ESX_VI__TEMPLATE__FREE(Context,
{
968
    if (item->sessionLock)
969 970
        virMutexDestroy(item->sessionLock);

971 972 973 974 975 976 977
    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);
978
    VIR_FREE(item->sessionLock);
979
    esxVI_Datacenter_Free(&item->datacenter);
980
    VIR_FREE(item->datacenterPath);
981
    esxVI_ComputeResource_Free(&item->computeResource);
982
    VIR_FREE(item->computeResourcePath);
983
    esxVI_HostSystem_Free(&item->hostSystem);
984
    VIR_FREE(item->hostSystemName);
985 986 987 988 989 990
    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);
M
Matthias Bolte 已提交
991
    esxVI_SelectionSpec_Free(&item->selectSet_datacenterToNetwork);
992 993 994 995 996 997 998
})

int
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
                      const char *ipAddress, const char *username,
                      const char *password, esxUtil_ParsedUri *parsedUri)
{
999 1000
    if (!ctx || !url || !ipAddress || !username ||
        !password || ctx->url || ctx->service || ctx->curl) {
1001
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1002 1003 1004 1005 1006
        return -1;
    }

    if (esxVI_CURL_Alloc(&ctx->curl) < 0 ||
        esxVI_CURL_Connect(ctx->curl, parsedUri) < 0 ||
1007 1008 1009 1010
        VIR_STRDUP(ctx->url, url) < 0 ||
        VIR_STRDUP(ctx->ipAddress, ipAddress) < 0 ||
        VIR_STRDUP(ctx->username, username) < 0 ||
        VIR_STRDUP(ctx->password, password) < 0) {
1011
        return -1;
1012 1013
    }

1014
    if (VIR_ALLOC(ctx->sessionLock) < 0)
1015 1016 1017
        return -1;

    if (virMutexInit(ctx->sessionLock) < 0) {
1018 1019
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize session mutex"));
1020 1021 1022
        return -1;
    }

1023
    if (esxVI_RetrieveServiceContent(ctx, &ctx->service) < 0)
1024
        return -1;
1025

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    if (STRNEQ(ctx->service->about->apiType, "HostAgent") &&
        STRNEQ(ctx->service->about->apiType, "VirtualCenter")) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                         "but found '%s'"), ctx->service->about->apiType);
        return -1;
    }

    if (virParseVersionString(ctx->service->about->apiVersion,
                              &ctx->apiVersion, true) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse VI API version '%s'"),
                       ctx->service->about->apiVersion);
        return -1;
    }

    if (ctx->apiVersion < 1000000 * 2 + 1000 * 5 /* 2.5 */) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Minimum supported %s version is %s but found version '%s'"),
                       "VI API", "2.5", ctx->service->about->apiVersion);
        return -1;
    }

    if (virParseVersionString(ctx->service->about->version,
                              &ctx->productVersion, true) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse product version '%s'"),
                       ctx->service->about->version);
        return -1;
    }

    if (STREQ(ctx->service->about->productLineId, "gsx")) {
        if (ctx->productVersion < 1000000 * 2 + 1000 * 0 /* 2.0 */) {
1059
            virReportError(VIR_ERR_INTERNAL_ERROR,
1060 1061 1062
                           _("Minimum supported %s version is %s but found version '%s'"),
                           esxVI_ProductLineToDisplayName(esxVI_ProductLine_GSX),
                           "2.0", ctx->service->about->version);
1063
            return -1;
1064
        }
1065

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        ctx->productLine = esxVI_ProductLine_GSX;
    } else if (STREQ(ctx->service->about->productLineId, "esx") ||
               STREQ(ctx->service->about->productLineId, "embeddedEsx")) {
        if (ctx->productVersion < 1000000 * 3 + 1000 * 5 /* 3.5 */) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Minimum supported %s version is %s but found version '%s'"),
                           esxVI_ProductLineToDisplayName(esxVI_ProductLine_ESX),
                           "3.5", ctx->service->about->version);
            return -1;
        }

        ctx->productLine = esxVI_ProductLine_ESX;
    } else if (STREQ(ctx->service->about->productLineId, "vpx")) {
        if (ctx->productVersion < 1000000 * 2 + 1000 * 5 /* 2.5 */) {
1080
            virReportError(VIR_ERR_INTERNAL_ERROR,
1081 1082 1083
                           _("Minimum supported %s version is %s but found version '%s'"),
                           esxVI_ProductLineToDisplayName(esxVI_ProductLine_VPX),
                           "2.5", ctx->service->about->version);
1084
            return -1;
1085
        }
1086 1087

        ctx->productLine = esxVI_ProductLine_VPX;
1088
    } else {
1089
        virReportError(VIR_ERR_INTERNAL_ERROR,
1090 1091 1092
                       _("Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                         "or 'vpx' but found '%s'"),
                       ctx->service->about->productLineId);
1093
        return -1;
1094 1095
    }

1096
    if (ctx->productLine == esxVI_ProductLine_ESX) {
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
        /*
         * 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;
    }

1107
    if (ctx->productLine == esxVI_ProductLine_VPX)
1108 1109
        ctx->hasSessionIsActive = true;

1110
    if (esxVI_Login(ctx, username, password, NULL, &ctx->session) < 0 ||
1111
        esxVI_BuildSelectSetCollection(ctx) < 0) {
1112
        return -1;
1113 1114
    }

1115 1116 1117 1118
    return 0;
}

int
1119
esxVI_Context_LookupManagedObjects(esxVI_Context *ctx)
1120 1121
{
    /* Lookup Datacenter */
1122 1123
    if (esxVI_LookupDatacenter(ctx, NULL, ctx->service->rootFolder, NULL,
                               &ctx->datacenter,
1124 1125
                               esxVI_Occurrence_RequiredItem) < 0) {
        return -1;
1126 1127
    }

1128
    if (VIR_STRDUP(ctx->datacenterPath, ctx->datacenter->name) < 0)
1129 1130
        return -1;

1131
    /* Lookup (Cluster)ComputeResource */
1132 1133
    if (esxVI_LookupComputeResource(ctx, NULL, ctx->datacenter->hostFolder,
                                    NULL, &ctx->computeResource,
1134 1135
                                    esxVI_Occurrence_RequiredItem) < 0) {
        return -1;
1136 1137
    }

1138
    if (!ctx->computeResource->resourcePool) {
1139 1140
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve resource pool"));
1141
        return -1;
1142 1143
    }

1144
    if (VIR_STRDUP(ctx->computeResourcePath, ctx->computeResource->name) < 0)
1145 1146
        return -1;

1147
    /* Lookup HostSystem */
1148 1149 1150
    if (esxVI_LookupHostSystem(ctx, NULL, ctx->computeResource->_reference,
                               NULL, &ctx->hostSystem,
                               esxVI_Occurrence_RequiredItem) < 0) {
1151
        return -1;
1152 1153
    }

1154
    if (VIR_STRDUP(ctx->hostSystemName, ctx->hostSystem->name) < 0)
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
        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;

1172
    if (VIR_STRDUP(tmp, path) < 0)
1173 1174 1175 1176 1177
        goto cleanup;

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

1178
    if (!item) {
1179 1180
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' does not specify a datacenter"), path);
1181 1182 1183 1184 1185
        goto cleanup;
    }

    root = ctx->service->rootFolder;

1186
    while (!ctx->datacenter && item) {
1187 1188 1189 1190 1191 1192 1193 1194
        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;
        }

1195
        if (folder) {
1196
            /* It's a folder, use it as new lookup root */
1197
            if (root != ctx->service->rootFolder)
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
                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 */
1211
        if (virBufferUse(&buffer) > 0)
1212 1213 1214 1215 1216 1217 1218 1219
            virBufferAddChar(&buffer, '/');

        virBufferAdd(&buffer, item, -1);

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

1220
    if (!ctx->datacenter) {
1221 1222
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datacenter specified in '%s'"), path);
1223 1224 1225
        goto cleanup;
    }

1226
    if (virBufferCheckError(&buffer) < 0)
1227 1228 1229 1230 1231
        goto cleanup;

    ctx->datacenterPath = virBufferContentAndReset(&buffer);

    /* Lookup (Cluster)ComputeResource */
1232
    if (!item) {
1233 1234
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' does not specify a compute resource"), path);
1235 1236 1237
        goto cleanup;
    }

1238
    if (root != ctx->service->rootFolder)
1239 1240 1241 1242
        esxVI_ManagedObjectReference_Free(&root);

    root = ctx->datacenter->hostFolder;

1243
    while (!ctx->computeResource && item) {
1244 1245 1246 1247 1248 1249 1250 1251
        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;
        }

1252
        if (folder) {
1253
            /* It's a folder, use it as new lookup root */
1254
            if (root != ctx->datacenter->hostFolder)
1255 1256 1257 1258
                esxVI_ManagedObjectReference_Free(&root);

            root = folder->_reference;
            folder->_reference = NULL;
1259
        } else {
1260 1261 1262 1263 1264 1265 1266 1267 1268
            /* 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 */
1269
        if (virBufferUse(&buffer) > 0)
1270 1271 1272 1273 1274 1275 1276 1277
            virBufferAddChar(&buffer, '/');

        virBufferAdd(&buffer, item, -1);

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

1278
    if (!ctx->computeResource) {
1279 1280 1281
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find compute resource specified in '%s'"),
                       path);
1282 1283 1284
        goto cleanup;
    }

1285
    if (!ctx->computeResource->resourcePool) {
1286 1287
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve resource pool"));
1288 1289 1290
        goto cleanup;
    }

1291
    if (virBufferCheckError(&buffer) < 0)
1292 1293 1294 1295 1296 1297 1298
        goto cleanup;

    ctx->computeResourcePath = virBufferContentAndReset(&buffer);

    /* Lookup HostSystem */
    if (STREQ(ctx->computeResource->_reference->type,
              "ClusterComputeResource")) {
1299
        if (!item) {
1300 1301
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Path '%s' does not specify a host system"), path);
1302
            goto cleanup;
1303
        }
1304 1305 1306 1307 1308 1309

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

1310
    if (item) {
1311 1312
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' ends with an excess item"), path);
1313
        goto cleanup;
1314 1315
    }

1316
    if (VIR_STRDUP(ctx->hostSystemName, previousItem) < 0)
1317 1318 1319
        goto cleanup;

    if (esxVI_LookupHostSystem(ctx, ctx->hostSystemName,
1320 1321
                               ctx->computeResource->_reference, NULL,
                               &ctx->hostSystem,
1322 1323
                               esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
1324 1325
    }

1326
    if (!ctx->hostSystem) {
1327 1328
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find host system specified in '%s'"), path);
1329 1330 1331 1332 1333
        goto cleanup;
    }

    result = 0;

1334
 cleanup:
1335
    if (result < 0)
1336 1337 1338
        virBufferFreeAndReset(&buffer);

    if (root != ctx->service->rootFolder &&
1339
        (!ctx->datacenter || root != ctx->datacenter->hostFolder)) {
1340 1341 1342 1343 1344 1345 1346
        esxVI_ManagedObjectReference_Free(&root);
    }

    VIR_FREE(tmp);
    esxVI_Folder_Free(&folder);

    return result;
1347 1348 1349
}

int
1350 1351
esxVI_Context_LookupManagedObjectsByHostSystemIp(esxVI_Context *ctx,
                                                 const char *hostSystemIpAddress)
1352 1353 1354 1355 1356
{
    int result = -1;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;

    /* Lookup HostSystem */
1357
    if (esxVI_FindByIp(ctx, NULL, hostSystemIpAddress, esxVI_Boolean_False,
1358
                       &managedObjectReference) < 0 ||
1359 1360 1361
        esxVI_LookupHostSystem(ctx, NULL, managedObjectReference, NULL,
                               &ctx->hostSystem,
                               esxVI_Occurrence_RequiredItem) < 0) {
1362 1363 1364
        goto cleanup;
    }

1365
    /* Lookup (Cluster)ComputeResource */
1366 1367 1368 1369 1370
    if (esxVI_LookupComputeResource(ctx, NULL, ctx->hostSystem->_reference,
                                    NULL, &ctx->computeResource,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }
1371

1372
    if (!ctx->computeResource->resourcePool) {
1373 1374
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve resource pool"));
1375 1376 1377 1378
        goto cleanup;
    }

    /* Lookup Datacenter */
1379 1380 1381
    if (esxVI_LookupDatacenter(ctx, NULL, ctx->computeResource->_reference,
                               NULL, &ctx->datacenter,
                               esxVI_Occurrence_RequiredItem) < 0) {
1382 1383 1384 1385 1386
        goto cleanup;
    }

    result = 0;

1387
 cleanup:
1388
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
1389 1390 1391 1392 1393

    return result;
}

int
1394 1395 1396
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
1397
{
M
Matthias Bolte 已提交
1398
    int result = -1;
1399 1400
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
1401 1402 1403
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
1404

1405
    if (!request || !response || *response) {
1406
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1407
        return -1;
1408 1409
    }

1410
    if (esxVI_Response_Alloc(response) < 0)
M
Matthias Bolte 已提交
1411
        return -1;
1412

1413
    virMutexLock(&ctx->curl->lock);
1414

1415
    curl_easy_setopt(ctx->curl->handle, CURLOPT_URL, ctx->url);
1416
    curl_easy_setopt(ctx->curl->handle, CURLOPT_RANGE, NULL);
1417 1418 1419 1420
    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));
1421

1422
    (*response)->responseCode = esxVI_CURL_Perform(ctx->curl, ctx->url);
1423

1424
    virMutexUnlock(&ctx->curl->lock);
1425

1426
    if ((*response)->responseCode < 0)
M
Matthias Bolte 已提交
1427
        goto cleanup;
1428

1429
    if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
1430
        goto cleanup;
1431

1432
    (*response)->content = virBufferContentAndReset(&buffer);
1433

1434
    if ((*response)->responseCode == 500 || (*response)->responseCode == 200) {
1435
        (*response)->document = virXMLParseStringCtxt((*response)->content,
1436
                                                      _("(esx execute response)"),
1437
                                                      &xpathContext);
1438

1439
        if (!(*response)->document)
M
Matthias Bolte 已提交
1440
            goto cleanup;
1441

1442
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
1443
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
1444
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
1445

1446 1447
        if ((*response)->responseCode == 500) {
            (*response)->node =
1448
              virXPathNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault",
1449
                           xpathContext);
1450

1451
            if (!(*response)->node) {
1452 1453 1454 1455
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("HTTP response code %d for call to '%s'. "
                                 "Fault is unknown, XPath evaluation failed"),
                               (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1456
                goto cleanup;
1457 1458
            }

1459
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
1460 1461 1462 1463
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("HTTP response code %d for call to '%s'. "
                                 "Fault is unknown, deserialization failed"),
                               (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1464
                goto cleanup;
1465 1466
            }

1467 1468 1469 1470
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("HTTP response code %d for call to '%s'. "
                             "Fault: %s - %s"), (*response)->responseCode,
                           methodName, fault->faultcode, fault->faultstring);
1471 1472 1473 1474 1475 1476

            /* 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 已提交
1477
            goto cleanup;
1478 1479 1480
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
1481
                            methodName) < 0)
M
Matthias Bolte 已提交
1482
                goto cleanup;
1483

1484
            responseNode = virXPathNode(xpathExpression, xpathContext);
1485

1486
            if (!responseNode) {
1487 1488 1489
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("XPath evaluation of response for call to '%s' "
                                 "failed"), methodName);
M
Matthias Bolte 已提交
1490
                goto cleanup;
1491 1492
            }

1493
            xpathContext->node = responseNode;
1494
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
1495

1496 1497
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
1498
                if (!(*response)->node) {
1499 1500 1501
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned an empty result, "
                                     "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
1502
                    goto cleanup;
1503
                } else if ((*response)->node->next) {
1504 1505 1506
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned a list, expecting "
                                     "exactly one item"), methodName);
M
Matthias Bolte 已提交
1507
                    goto cleanup;
1508 1509 1510 1511 1512
                }

                break;

              case esxVI_Occurrence_RequiredList:
1513
                if (!(*response)->node) {
1514 1515 1516
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned an empty result, "
                                     "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
1517
                    goto cleanup;
1518 1519 1520 1521 1522
                }

                break;

              case esxVI_Occurrence_OptionalItem:
1523 1524
                if ((*response)->node &&
                    (*response)->node->next) {
1525 1526 1527
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned a list, expecting "
                                     "exactly one item"), methodName);
M
Matthias Bolte 已提交
1528
                    goto cleanup;
1529 1530 1531 1532
                }

                break;

1533
              case esxVI_Occurrence_OptionalList:
1534 1535 1536 1537
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
1538
                if ((*response)->node) {
1539 1540 1541
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned something, expecting "
                                     "an empty result"), methodName);
M
Matthias Bolte 已提交
1542
                    goto cleanup;
1543 1544 1545 1546 1547
                }

                break;

              default:
1548 1549
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Invalid argument (occurrence)"));
M
Matthias Bolte 已提交
1550
                goto cleanup;
1551
            }
1552
        }
1553
    } else {
1554 1555 1556
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("HTTP response code %d for call to '%s'"),
                       (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1557
        goto cleanup;
1558 1559
    }

M
Matthias Bolte 已提交
1560 1561
    result = 0;

1562
 cleanup:
M
Matthias Bolte 已提交
1563 1564 1565 1566 1567 1568
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
        esxVI_Response_Free(response);
        esxVI_Fault_Free(&fault);
    }

1569 1570 1571 1572
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
1573 1574 1575 1576 1577
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1578
 * Response
1579 1580
 */

1581
/* esxVI_Response_Alloc */
1582
ESX_VI__TEMPLATE__ALLOC(Response)
1583

1584 1585
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
1586
{
1587
    VIR_FREE(item->content);
1588

1589
    xmlFreeDoc(item->document);
1590
})
1591 1592 1593 1594 1595 1596 1597 1598



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

int
1599
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
1600 1601
                                  esxVI_AnyType *anyType, int *value)
{
1602
    size_t i;
1603

1604
    if (!anyType || !value) {
1605
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1606 1607 1608 1609 1610
        return -1;
    }

    *value = 0; /* undefined */

1611
    if (anyType->type != enumeration->type) {
1612 1613 1614
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting type '%s' but found '%s'"),
                       esxVI_Type_ToString(enumeration->type),
1615
                       esxVI_AnyType_TypeToString(anyType));
1616 1617 1618
        return -1;
    }

1619
    for (i = 0; enumeration->values[i].name; ++i) {
1620 1621 1622 1623 1624 1625
        if (STREQ(anyType->value, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
            return 0;
        }
    }

1626 1627 1628
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Unknown value '%s' for %s"), anyType->value,
                   esxVI_Type_ToString(enumeration->type));
1629 1630 1631 1632 1633

    return -1;
}

int
1634
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
1635
                            int value, const char *element, virBufferPtr output)
1636
{
1637
    size_t i;
1638 1639
    const char *name = NULL;

1640
    if (!element || !output) {
1641
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1642 1643 1644 1645
        return -1;
    }

    if (value == 0) { /* undefined */
1646
        return 0;
1647 1648
    }

1649
    for (i = 0; enumeration->values[i].name; ++i) {
1650 1651 1652 1653 1654 1655
        if (value == enumeration->values[i].value) {
            name = enumeration->values[i].name;
            break;
        }
    }

1656
    if (!name) {
1657
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1658 1659 1660
        return -1;
    }

1661 1662
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
1663 1664 1665 1666 1667 1668 1669 1670 1671

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
1672
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
1673 1674
                              xmlNodePtr node, int *value)
{
1675
    size_t i;
M
Matthias Bolte 已提交
1676
    int result = -1;
1677 1678
    char *name = NULL;

1679
    if (!value) {
1680
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1681
        return -1;
1682 1683 1684 1685
    }

    *value = 0; /* undefined */

1686
    if (esxVI_String_DeserializeValue(node, &name) < 0)
M
Matthias Bolte 已提交
1687
        return -1;
1688

1689
    for (i = 0; enumeration->values[i].name; ++i) {
1690 1691
        if (STREQ(name, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
M
Matthias Bolte 已提交
1692 1693
            result = 0;
            break;
1694 1695 1696
        }
    }

M
Matthias Bolte 已提交
1697
    if (result < 0) {
1698 1699
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Unknown value '%s' for %s"),
                       name, esxVI_Type_ToString(enumeration->type));
M
Matthias Bolte 已提交
1700
    }
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

    VIR_FREE(name);

    return result;
}



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

int
1714
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
1715 1716 1717
{
    esxVI_List *next = NULL;

1718
    if (!list || !item) {
1719
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1720 1721 1722
        return -1;
    }

1723
    if (!(*list)) {
1724 1725 1726 1727 1728 1729
        *list = item;
        return 0;
    }

    next = *list;

1730
    while (next->_next)
1731 1732 1733 1734 1735 1736 1737 1738
        next = next->_next;

    next->_next = item;

    return 0;
}

int
1739
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
1740 1741 1742 1743 1744 1745
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

1746
    if (!destList || *destList) {
1747
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1748
        return -1;
1749 1750
    }

1751
    for (src = srcList; src; src = src->_next) {
1752 1753
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
1754 1755 1756 1757 1758 1759 1760 1761
            goto failure;
        }

        dest = NULL;
    }

    return 0;

1762
 failure:
1763 1764 1765 1766 1767 1768
    freeFunc(&dest);
    freeFunc(destList);

    return -1;
}

1769
int
1770
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
1771 1772 1773
                           esxVI_List_CastFromAnyTypeFunc castFromAnyTypeFunc,
                           esxVI_List_FreeFunc freeFunc)
{
M
Matthias Bolte 已提交
1774
    int result = -1;
1775 1776 1777 1778
    xmlNodePtr childNode = NULL;
    esxVI_AnyType *childAnyType = NULL;
    esxVI_List *item = NULL;

1779
    if (!list || *list || !castFromAnyTypeFunc || !freeFunc) {
1780
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1781
        return -1;
1782 1783
    }

1784
    if (!anyType)
1785 1786 1787
        return 0;

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
1788 1789 1790
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting type to begin with 'ArrayOf' but found '%s'"),
                       anyType->other);
1791
        return -1;
1792 1793
    }

1794
    for (childNode = anyType->node->children; childNode;
1795 1796
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1797 1798
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Wrong XML element type %d"), childNode->type);
M
Matthias Bolte 已提交
1799
            goto cleanup;
1800 1801 1802 1803
        }

        esxVI_AnyType_Free(&childAnyType);

1804 1805 1806
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
M
Matthias Bolte 已提交
1807
            goto cleanup;
1808 1809 1810 1811 1812
        }

        item = NULL;
    }

M
Matthias Bolte 已提交
1813 1814
    result = 0;

1815
 cleanup:
M
Matthias Bolte 已提交
1816 1817 1818 1819 1820
    if (result < 0) {
        freeFunc(&item);
        freeFunc(list);
    }

1821 1822 1823 1824 1825
    esxVI_AnyType_Free(&childAnyType);

    return result;
}

1826
int
1827
esxVI_List_Serialize(esxVI_List *list, const char *element,
1828
                     virBufferPtr output,
1829 1830 1831 1832
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

1833
    if (!element || !output || !serializeFunc) {
1834
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1835 1836 1837
        return -1;
    }

1838
    if (!list)
1839
        return 0;
1840

1841
    for (item = list; item; item = item->_next) {
1842
        if (serializeFunc(item, element, output) < 0)
1843 1844 1845 1846 1847 1848 1849
            return -1;
    }

    return 0;
}

int
1850
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1851 1852 1853 1854 1855
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

1856
    if (!list || *list || !deserializeFunc || !freeFunc) {
1857
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1858 1859 1860
        return -1;
    }

1861
    if (!node)
1862 1863
        return 0;

1864
    for (; node; node = node->next) {
1865
        if (node->type != XML_ELEMENT_NODE) {
1866 1867
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Wrong XML element type %d"), node->type);
1868 1869 1870
            goto failure;
        }

1871 1872
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1873 1874 1875
            goto failure;
        }

1876
        item = NULL;
1877 1878 1879 1880
    }

    return 0;

1881
 failure:
1882
    freeFunc(&item);
1883 1884 1885 1886 1887 1888 1889 1890 1891
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1892 1893 1894 1895
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1896 1897 1898
 */

int
1899 1900 1901
esxVI_BuildSelectSet(esxVI_SelectionSpec **selectSet,
                     const char *name, const char *type,
                     const char *path, const char *selectSetNames)
1902 1903 1904 1905 1906
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

1907
    if (!selectSet) {
1908 1909 1910 1911
        /*
         * Don't check for *selectSet != NULL here because selectSet is a list
         * and might contain items already. This function appends to selectSet.
         */
1912
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1913 1914 1915
        return -1;
    }

1916
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1917 1918 1919
        VIR_STRDUP(traversalSpec->name, name) < 0 ||
        VIR_STRDUP(traversalSpec->type, type) < 0 ||
        VIR_STRDUP(traversalSpec->path, path) < 0) {
1920 1921 1922 1923 1924
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

1925
    if (selectSetNames) {
1926 1927
        currentSelectSetName = selectSetNames;

1928
        while (currentSelectSetName && *currentSelectSetName != '\0') {
1929
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
1930
                VIR_STRDUP(selectionSpec->name, currentSelectSetName) < 0 ||
1931
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1932 1933 1934 1935
                                                 selectionSpec) < 0) {
                goto failure;
            }

1936
            selectionSpec = NULL;
1937 1938 1939 1940
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1941
    if (esxVI_SelectionSpec_AppendToList(selectSet,
1942 1943
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1944 1945 1946 1947 1948
        goto failure;
    }

    return 0;

1949
 failure:
1950
    esxVI_TraversalSpec_Free(&traversalSpec);
1951
    esxVI_SelectionSpec_Free(&selectionSpec);
1952 1953 1954 1955 1956

    return -1;
}


1957

1958
int
1959
esxVI_BuildSelectSetCollection(esxVI_Context *ctx)
1960
{
1961
    /* Folder -> childEntity (ManagedEntity) */
1962 1963
    if (esxVI_BuildSelectSet(&ctx->selectSet_folderToChildEntity,
                             "folderToChildEntity",
1964
                             "Folder", "childEntity", NULL) < 0) {
1965
        return -1;
1966 1967
    }

1968
    /* ComputeResource -> host (HostSystem) */
1969 1970 1971 1972
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToHost,
                             "computeResourceToHost",
                             "ComputeResource", "host", NULL) < 0) {
        return -1;
1973 1974
    }

1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
    /* 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;
    }*/
1990

1991 1992 1993 1994 1995 1996
    /* ResourcePool -> vm (VirtualMachine) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_resourcePoolToVm,
                             "resourcePoolToVm",
                             "ResourcePool", "vm", NULL) < 0) {
        return -1;
    }*/
1997

1998
    /* HostSystem -> parent (ComputeResource) */
1999 2000 2001 2002
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToParent,
                             "hostSystemToParent",
                             "HostSystem", "parent", NULL) < 0) {
        return -1;
2003 2004
    }

2005
    /* HostSystem -> vm (VirtualMachine) */
2006 2007 2008 2009
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToVm,
                             "hostSystemToVm",
                             "HostSystem", "vm", NULL) < 0) {
        return -1;
2010 2011
    }

2012
    /* HostSystem -> datastore (Datastore) */
2013 2014 2015 2016
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToDatastore,
                             "hostSystemToDatastore",
                             "HostSystem", "datastore", NULL) < 0) {
        return -1;
2017 2018
    }

2019 2020 2021 2022 2023 2024
    /* Folder -> parent (Folder, Datacenter) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "managedEntityToParent",
                             "ManagedEntity", "parent", NULL) < 0) {
        return -1;
    }
2025

2026 2027 2028 2029 2030 2031 2032
    /* ComputeResource -> parent (Folder) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "computeResourceToParent",
                             "ComputeResource", "parent",
                             "managedEntityToParent\0") < 0) {
        return -1;
    }
2033

M
Matthias Bolte 已提交
2034 2035 2036 2037 2038 2039 2040
    /* Datacenter -> network (Network) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_datacenterToNetwork,
                             "datacenterToNetwork",
                             "Datacenter", "network", NULL) < 0) {
        return -1;
    }

2041
    return 0;
2042 2043 2044 2045 2046
}



int
2047
esxVI_EnsureSession(esxVI_Context *ctx)
2048
{
M
Matthias Bolte 已提交
2049
    int result = -1;
2050
    esxVI_Boolean active = esxVI_Boolean_Undefined;
2051 2052 2053 2054 2055
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;

2056
    if (!ctx->sessionLock) {
2057
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no mutex"));
2058 2059 2060
        return -1;
    }

2061 2062
    virMutexLock(ctx->sessionLock);

2063
    if (!ctx->session) {
2064
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no session"));
2065 2066 2067
        goto cleanup;
    }

2068 2069 2070
    if (ctx->hasSessionIsActive) {
        /*
         * Use SessionIsActive to check if there is an active session for this
E
Eric Blake 已提交
2071
         * connection, and re-login if there isn't.
2072 2073 2074
         */
        if (esxVI_SessionIsActive(ctx, ctx->session->key,
                                  ctx->session->userName, &active) < 0) {
2075
            goto cleanup;
2076
        }
2077

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

2081 2082
            if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                            &ctx->session) < 0) {
2083
                goto cleanup;
2084
            }
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
        }
    } 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,
2095 2096
                                            &sessionManager,
                                            esxVI_Occurrence_RequiredItem) < 0) {
2097
            goto cleanup;
2098 2099
        }

2100
        for (dynamicProperty = sessionManager->propSet; dynamicProperty;
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
             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);
            }
        }
2113

2114
        if (!currentSession) {
2115 2116 2117 2118 2119 2120 2121
            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)) {
2122 2123 2124
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Key of the current session differs from the key at "
                             "last login"));
M
Matthias Bolte 已提交
2125
            goto cleanup;
2126
        }
2127
    }
2128

2129
    result = 0;
M
Matthias Bolte 已提交
2130

2131
 cleanup:
2132
    virMutexUnlock(ctx->sessionLock);
2133

2134 2135 2136 2137 2138
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);

    return result;
2139 2140 2141 2142 2143
}



int
2144
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
2145 2146 2147
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
2148 2149
                                esxVI_ObjectContent **objectContentList,
                                esxVI_Occurrence occurrence)
2150
{
M
Matthias Bolte 已提交
2151
    int result = -1;
2152
    esxVI_ObjectSpec *objectSpec = NULL;
2153
    bool objectSpec_isAppended = false;
2154
    esxVI_PropertySpec *propertySpec = NULL;
2155
    bool propertySpec_isAppended = false;
2156 2157
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

2158
    if (!objectContentList || *objectContentList) {
2159
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2160 2161 2162
        return -1;
    }

2163
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0)
M
Matthias Bolte 已提交
2164
        return -1;
2165 2166 2167 2168

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

2169
    if (STRNEQ(root->type, type) || STREQ(root->type, "Folder")) {
2170
        if (STREQ(root->type, "Folder")) {
2171 2172
            if (STREQ(type, "Folder") || STREQ(type, "Datacenter") ||
                STREQ(type, "ComputeResource") ||
2173
                STREQ(type, "ClusterComputeResource")) {
2174 2175
                objectSpec->selectSet = ctx->selectSet_folderToChildEntity;
            } else {
2176 2177 2178
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2179 2180
                goto cleanup;
            }
2181 2182
        } else if (STREQ(root->type, "ComputeResource") ||
                   STREQ(root->type, "ClusterComputeResource")) {
2183 2184 2185 2186 2187
            if (STREQ(type, "HostSystem")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToHost;
            } else if (STREQ(type, "Datacenter")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToParentToParent;
            } else {
2188 2189 2190
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2191 2192 2193
                goto cleanup;
            }
        } else if (STREQ(root->type, "HostSystem")) {
2194 2195
            if (STREQ(type, "ComputeResource") ||
                STREQ(type, "ClusterComputeResource")) {
2196 2197 2198 2199 2200 2201
                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 {
2202 2203 2204
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2205 2206
                goto cleanup;
            }
M
Matthias Bolte 已提交
2207 2208 2209 2210 2211 2212 2213 2214 2215
        } else if (STREQ(root->type, "Datacenter")) {
            if (STREQ(type, "Network")) {
                objectSpec->selectSet = ctx->selectSet_datacenterToNetwork;
            } else {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
                goto cleanup;
            }
2216
        } else {
2217 2218
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid lookup from '%s'"), root->type);
2219 2220
            goto cleanup;
        }
2221 2222
    }

2223
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0)
M
Matthias Bolte 已提交
2224
        goto cleanup;
2225 2226 2227 2228

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

2229 2230
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
                                        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,
2245 2246 2247 2248
                                 objectContentList) < 0) {
        goto cleanup;
    }

2249
    if (!(*objectContentList)) {
2250 2251 2252 2253 2254 2255 2256
        switch (occurrence) {
          case esxVI_Occurrence_OptionalItem:
          case esxVI_Occurrence_OptionalList:
            result = 0;
            break;

          case esxVI_Occurrence_RequiredItem:
2257 2258 2259
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not lookup '%s' from '%s'"),
                           type, root->type);
2260 2261 2262
            break;

          case esxVI_Occurrence_RequiredList:
2263 2264 2265
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not lookup '%s' list from '%s'"),
                           type, root->type);
2266 2267 2268
            break;

          default:
2269 2270
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Invalid occurrence value"));
2271 2272 2273
            break;
        }

M
Matthias Bolte 已提交
2274
        goto cleanup;
2275 2276
    }

2277
    result = 0;
2278

2279
 cleanup:
2280 2281 2282
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
2283
     * objectSpec cannot be NULL here.
2284
     */
2285 2286
    objectSpec->obj = NULL;
    objectSpec->selectSet = NULL;
2287

2288
    if (propertySpec) {
2289 2290 2291 2292
        propertySpec->type = NULL;
        propertySpec->pathSet = NULL;
    }

2293
    if (!objectSpec_isAppended)
2294 2295
        esxVI_ObjectSpec_Free(&objectSpec);

2296
    if (!propertySpec_isAppended)
2297 2298
        esxVI_PropertySpec_Free(&propertySpec);

2299 2300 2301 2302 2303 2304 2305
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);

    return result;
}



2306
int
2307
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
2308 2309 2310 2311 2312
                             const char *propertyName,
                             esxVI_ManagedEntityStatus *managedEntityStatus)
{
    esxVI_DynamicProperty *dynamicProperty;

2313
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2314 2315 2316
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            return esxVI_ManagedEntityStatus_CastFromAnyType
2317
                     (dynamicProperty->val, managedEntityStatus);
2318 2319 2320
        }
    }

2321 2322 2323
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Missing '%s' property while looking for "
                     "ManagedEntityStatus"), propertyName);
2324 2325 2326 2327 2328 2329

    return -1;
}



2330
int
2331
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
2332 2333 2334 2335
                                  esxVI_VirtualMachinePowerState *powerState)
{
    esxVI_DynamicProperty *dynamicProperty;

2336
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2337 2338 2339
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            return esxVI_VirtualMachinePowerState_CastFromAnyType
2340
                     (dynamicProperty->val, powerState);
2341 2342 2343
        }
    }

2344 2345
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Missing 'runtime.powerState' property"));
2346 2347 2348 2349 2350 2351

    return -1;
}



2352 2353
int
esxVI_GetVirtualMachineQuestionInfo
2354
  (esxVI_ObjectContent *virtualMachine,
2355 2356 2357 2358
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

2359
    if (!questionInfo || *questionInfo) {
2360
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2361 2362 2363
        return -1;
    }

2364
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2365 2366 2367
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
2368
                  (dynamicProperty->val, questionInfo) < 0) {
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
                return -1;
            }
        }
    }

    return 0;
}



2379 2380
int
esxVI_GetBoolean(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2381
                 esxVI_Boolean *value, esxVI_Occurrence occurrence)
2382 2383 2384
{
    esxVI_DynamicProperty *dynamicProperty;

2385
    if (!value || *value != esxVI_Boolean_Undefined) {
2386
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2387 2388 2389
        return -1;
    }

2390
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
         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 已提交
2404
        occurrence == esxVI_Occurrence_RequiredItem) {
2405 2406
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2407 2408 2409 2410 2411 2412
        return -1;
    }

    return 0;
}

M
Matthias Bolte 已提交
2413 2414


2415 2416
int
esxVI_GetLong(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2417
              esxVI_Long **value, esxVI_Occurrence occurrence)
2418 2419 2420
{
    esxVI_DynamicProperty *dynamicProperty;

2421
    if (!value || *value) {
2422
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2423 2424 2425
        return -1;
    }

2426
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2427 2428
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
2429
            if (esxVI_Long_CastFromAnyType(dynamicProperty->val, value) < 0)
2430 2431 2432 2433 2434 2435
                return -1;

            break;
        }
    }

2436
    if (!(*value) && occurrence == esxVI_Occurrence_RequiredItem) {
2437 2438
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2439 2440 2441 2442 2443 2444
        return -1;
    }

    return 0;
}

2445 2446 2447 2448 2449


int
esxVI_GetStringValue(esxVI_ObjectContent *objectContent,
                     const char *propertyName,
M
Matthias Bolte 已提交
2450
                     char **value, esxVI_Occurrence occurrence)
2451 2452 2453
{
    esxVI_DynamicProperty *dynamicProperty;

2454
    if (!value || *value) {
2455
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2456 2457 2458
        return -1;
    }

2459
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471
         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;
        }
    }

2472
    if (!(*value) && occurrence == esxVI_Occurrence_RequiredItem) {
2473 2474
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
        return -1;
    }

    return 0;
}



int
esxVI_GetManagedObjectReference(esxVI_ObjectContent *objectContent,
                                const char *propertyName,
                                esxVI_ManagedObjectReference **value,
M
Matthias Bolte 已提交
2487
                                esxVI_Occurrence occurrence)
2488 2489 2490
{
    esxVI_DynamicProperty *dynamicProperty;

2491
    if (!value || *value) {
2492
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2493 2494 2495
        return -1;
    }

2496
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, value) < 0) {
                return -1;
            }

            break;
        }
    }

2508
    if (!(*value) && occurrence == esxVI_Occurrence_RequiredItem) {
2509 2510
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2511 2512 2513 2514 2515 2516 2517 2518
        return -1;
    }

    return 0;
}



2519
int
2520
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
2521
                                        esxVI_VirtualMachinePowerState powerState,
2522
                                        bool inverse)
2523
{
M
Matthias Bolte 已提交
2524
    bool success = false;
2525 2526 2527 2528 2529
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
M
Matthias Bolte 已提交
2530
    int count = 0;
2531

2532
    if (esxVI_String_AppendValueToList(&propertyNameList,
2533
                                       "runtime.powerState") < 0 ||
2534 2535
        esxVI_LookupVirtualMachineList(ctx, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2536
        goto cleanup;
2537 2538
    }

2539
    for (virtualMachine = virtualMachineList; virtualMachine;
2540 2541
         virtualMachine = virtualMachine->_next) {
        for (dynamicProperty = virtualMachine->propSet;
2542
             dynamicProperty;
2543 2544 2545
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "runtime.powerState")) {
                if (esxVI_VirtualMachinePowerState_CastFromAnyType
2546
                      (dynamicProperty->val, &powerState_) < 0) {
M
Matthias Bolte 已提交
2547
                    goto cleanup;
2548 2549
                }

2550
                if ((!inverse && powerState_ == powerState) ||
2551
                    (inverse && powerState_ != powerState)) {
M
Matthias Bolte 已提交
2552
                    count++;
2553 2554 2555 2556 2557 2558 2559
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

M
Matthias Bolte 已提交
2560 2561
    success = true;

2562
 cleanup:
2563 2564 2565
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
2566
    return success ? count : -1;
2567 2568 2569 2570 2571
}



int
2572
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
2573 2574 2575 2576
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
2577
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
2578 2579

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
2580 2581
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("ObjectContent does not reference a virtual machine"));
2582 2583 2584
        return -1;
    }

2585
    if (id) {
2586 2587
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
2588 2589 2590
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse positive integer from '%s'"),
                           virtualMachine->obj->value);
2591 2592 2593 2594
            goto failure;
        }
    }

2595 2596
    if (name) {
        if (*name) {
2597
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2598 2599 2600 2601
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
2602
             dynamicProperty;
2603 2604
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2605
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2606 2607 2608 2609
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

2610
                if (VIR_STRDUP(*name, dynamicProperty->val->string) < 0)
2611 2612
                    goto failure;

2613
                if (virVMXUnescapeHexPercent(*name) < 0) {
2614 2615
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Domain name contains invalid escape sequence"));
2616 2617 2618
                    goto failure;
                }

2619 2620 2621 2622
                break;
            }
        }

2623
        if (!(*name)) {
2624 2625
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not get name of virtual machine"));
2626 2627 2628 2629
            goto failure;
        }
    }

2630
    if (uuid) {
2631
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
2632 2633 2634 2635 2636 2637
                                         &configStatus) < 0) {
            goto failure;
        }

        if (configStatus == esxVI_ManagedEntityStatus_Green) {
            for (dynamicProperty = virtualMachine->propSet;
2638
                 dynamicProperty;
2639 2640
                 dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "config.uuid")) {
2641
                    if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2642 2643 2644 2645 2646 2647
                                                 esxVI_Type_String) < 0) {
                        goto failure;
                    }

                    uuid_string = dynamicProperty->val->string;
                    break;
2648
                }
2649
            }
2650

2651
            if (!uuid_string) {
2652 2653
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Could not get UUID of virtual machine"));
2654
                goto failure;
2655 2656
            }

2657
            if (virUUIDParse(uuid_string, uuid) < 0) {
2658 2659 2660
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not parse UUID from string '%s'"),
                               uuid_string);
2661 2662 2663 2664
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
2665

2666
            VIR_WARN("Cannot access UUID, because 'configStatus' property "
2667
                      "indicates a config problem");
2668 2669 2670 2671 2672
        }
    }

    return 0;

2673
 failure:
2674
    if (name)
2675 2676 2677 2678 2679 2680 2681
        VIR_FREE(*name);

    return -1;
}



2682 2683
int
esxVI_GetNumberOfSnapshotTrees
2684 2685
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList, bool recurse,
   bool leaves)
2686 2687 2688 2689
{
    int count = 0;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

2690
    for (snapshotTree = snapshotTreeList; snapshotTree;
2691
         snapshotTree = snapshotTree->_next) {
2692 2693
        if (!(leaves && snapshotTree->childSnapshotList))
            count++;
2694 2695
        if (recurse)
            count += esxVI_GetNumberOfSnapshotTrees
2696
                (snapshotTree->childSnapshotList, true, leaves);
2697 2698 2699 2700 2701 2702 2703 2704 2705
    }

    return count;
}



int
esxVI_GetSnapshotTreeNames(esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
2706 2707
                           char **names, int nameslen, bool recurse,
                           bool leaves)
2708 2709 2710
{
    int count = 0;
    int result;
2711
    size_t i;
2712 2713 2714
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList;
2715
         snapshotTree && count < nameslen;
2716
         snapshotTree = snapshotTree->_next) {
2717
        if (!(leaves && snapshotTree->childSnapshotList)) {
2718
            if (VIR_STRDUP(names[count], snapshotTree->name) < 0)
2719
                goto failure;
2720

2721 2722
            count++;
        }
2723

2724
        if (count >= nameslen)
2725 2726
            break;

2727 2728 2729 2730
        if (recurse) {
            result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
                                                names + count,
                                                nameslen - count,
2731
                                                true, leaves);
2732

2733
            if (result < 0)
2734
                goto failure;
2735

2736 2737
            count += result;
        }
2738 2739 2740 2741
    }

    return count;

2742
 failure:
2743
    for (i = 0; i < count; ++i)
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
        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;

2760 2761
    if (!snapshotTree || *snapshotTree ||
        (snapshotTreeParent && *snapshotTreeParent)) {
2762
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2763 2764 2765
        return -1;
    }

2766
    for (candidate = snapshotTreeList; candidate;
2767 2768 2769
         candidate = candidate->_next) {
        if (STREQ(candidate->name, name)) {
            *snapshotTree = candidate;
2770 2771
            if (snapshotTreeParent)
                *snapshotTreeParent = NULL;
2772 2773 2774 2775 2776 2777
            return 1;
        }

        if (esxVI_GetSnapshotTreeByName(candidate->childSnapshotList, name,
                                        snapshotTree, snapshotTreeParent,
                                        occurrence) > 0) {
2778
            if (snapshotTreeParent && !(*snapshotTreeParent))
2779 2780 2781 2782 2783 2784 2785 2786 2787
                *snapshotTreeParent = candidate;

            return 1;
        }
    }

    if (occurrence == esxVI_Occurrence_OptionalItem) {
        return 0;
    } else {
2788 2789
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("Could not find snapshot with name '%s'"), name);
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804

        return -1;
    }
}



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

2805
    if (!snapshotTree || *snapshotTree) {
2806
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2807 2808 2809
        return -1;
    }

2810
    for (candidate = snapshotTreeList; candidate;
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
         candidate = candidate->_next) {
        if (STREQ(candidate->snapshot->value, snapshot->value)) {
            *snapshotTree = candidate;
            return 0;
        }

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

2823 2824 2825
    virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                   _("Could not find domain snapshot with internal name '%s'"),
                   snapshot->value);
2826 2827 2828 2829 2830 2831

    return -1;
}



M
Matthias Bolte 已提交
2832 2833 2834 2835
int
esxVI_LookupHostSystemProperties(esxVI_Context *ctx,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **hostSystem)
M
Matthias Bolte 已提交
2836
{
2837 2838
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "HostSystem", propertyNameList,
2839 2840
                                           hostSystem,
                                           esxVI_Occurrence_RequiredItem);
M
Matthias Bolte 已提交
2841 2842 2843 2844
}



2845
int
2846 2847 2848
esxVI_LookupVirtualMachineList(esxVI_Context *ctx,
                               esxVI_String *propertyNameList,
                               esxVI_ObjectContent **virtualMachineList)
2849
{
2850 2851 2852 2853
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource->resourcePool
     *        for cluster support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "VirtualMachine", propertyNameList,
2854 2855
                                           virtualMachineList,
                                           esxVI_Occurrence_OptionalList);
2856 2857 2858 2859 2860
}



int
2861
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
2862
                                 esxVI_String *propertyNameList,
2863
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
2864
                                 esxVI_Occurrence occurrence)
2865
{
M
Matthias Bolte 已提交
2866
    int result = -1;
2867
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
2868
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
2869

2870
    if (!virtualMachine || *virtualMachine) {
2871
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2872 2873 2874
        return -1;
    }

2875 2876
    virUUIDFormat(uuid, uuid_string);

2877
    if (esxVI_FindByUuid(ctx, ctx->datacenter->_reference, uuid_string,
2878 2879
                         esxVI_Boolean_True, esxVI_Boolean_Undefined,
                         &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2880
        return -1;
2881 2882
    }

2883
    if (!managedObjectReference) {
M
Matthias Bolte 已提交
2884
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2885 2886 2887
            result = 0;

            goto cleanup;
2888
        } else {
2889 2890 2891
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("Could not find domain with UUID '%s'"),
                           uuid_string);
M
Matthias Bolte 已提交
2892
            goto cleanup;
2893 2894 2895
        }
    }

2896
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2897
                                        "VirtualMachine", propertyNameList,
2898 2899
                                        virtualMachine,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2900
        goto cleanup;
2901 2902
    }

M
Matthias Bolte 已提交
2903 2904
    result = 0;

2905
 cleanup:
2906 2907 2908
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
M
Matthias Bolte 已提交
2909 2910 2911 2912
}



2913 2914 2915 2916 2917 2918
int
esxVI_LookupVirtualMachineByName(esxVI_Context *ctx, const char *name,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2919
    int result = -1;
2920 2921 2922 2923 2924
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate = NULL;

2925
    if (!virtualMachine || *virtualMachine) {
2926
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2927 2928 2929 2930 2931 2932
        return -1;
    }

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
2933 2934
        esxVI_LookupVirtualMachineList(ctx, completePropertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2935
        goto cleanup;
2936 2937
    }

2938
    for (candidate = virtualMachineList; candidate;
2939 2940 2941 2942 2943
         candidate = candidate->_next) {
        VIR_FREE(name_candidate);

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
M
Matthias Bolte 已提交
2944
            goto cleanup;
2945 2946
        }

2947
        if (STRNEQ(name, name_candidate))
2948 2949
            continue;

2950
        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0)
M
Matthias Bolte 已提交
2951
            goto cleanup;
2952 2953 2954 2955

        break;
    }

2956
    if (!(*virtualMachine)) {
2957
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2958 2959 2960
            result = 0;

            goto cleanup;
2961
        } else {
2962 2963
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("Could not find domain with name '%s'"), name);
M
Matthias Bolte 已提交
2964
            goto cleanup;
2965 2966 2967
        }
    }

M
Matthias Bolte 已提交
2968 2969
    result = 0;

2970
 cleanup:
2971 2972 2973 2974 2975 2976 2977 2978 2979
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;
}



2980 2981
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2982
  (esxVI_Context *ctx, const unsigned char *uuid,
2983
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
2984
   bool autoAnswer)
2985
{
M
Matthias Bolte 已提交
2986
    int result = -1;
2987 2988 2989
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;
2990
    bool blocked;
2991

2992
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2993
                                  propertyNameList) < 0 ||
2994
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2995 2996
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2997
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2998
                                         virtualMachine,
M
Matthias Bolte 已提交
2999
                                         esxVI_Occurrence_RequiredItem) < 0 ||
3000
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
3001 3002
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
3003
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
M
Matthias Bolte 已提交
3004
        goto cleanup;
3005 3006
    }

3007
    if (questionInfo &&
3008
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
3009 3010
                                           questionInfo, autoAnswer,
                                           &blocked) < 0) {
M
Matthias Bolte 已提交
3011
        goto cleanup;
3012 3013
    }

3014
    if (pendingTaskInfoList) {
3015 3016
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Other tasks are pending for this domain"));
M
Matthias Bolte 已提交
3017
        goto cleanup;
3018 3019
    }

M
Matthias Bolte 已提交
3020 3021
    result = 0;

3022
 cleanup:
3023 3024 3025 3026 3027 3028 3029 3030 3031
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;
}



3032 3033 3034 3035 3036 3037 3038 3039
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,
3040 3041
                                           datastoreList,
                                           esxVI_Occurrence_OptionalList);
3042 3043 3044 3045
}



M
Matthias Bolte 已提交
3046
int
3047 3048
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
3049
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
3050
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
3051
{
M
Matthias Bolte 已提交
3052
    int result = -1;
M
Matthias Bolte 已提交
3053 3054 3055
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
3056
    char *name_candidate;
M
Matthias Bolte 已提交
3057

3058
    if (!datastore || *datastore) {
3059
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
3060 3061 3062 3063
        return -1;
    }

    /* Get all datastores */
3064
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
3065
                                  propertyNameList) < 0 ||
3066 3067
        esxVI_String_AppendValueToList(&completePropertyNameList,
                                       "summary.name") < 0 ||
3068 3069
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
M
Matthias Bolte 已提交
3070
        goto cleanup;
M
Matthias Bolte 已提交
3071 3072
    }

3073
    /* Search for a matching datastore */
3074
    for (candidate = datastoreList; candidate;
3075 3076 3077 3078 3079
         candidate = candidate->_next) {
        name_candidate = NULL;

        if (esxVI_GetStringValue(candidate, "summary.name", &name_candidate,
                                 esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3080
            goto cleanup;
M
Matthias Bolte 已提交
3081
        }
3082 3083

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

3087 3088 3089 3090
            /* Found datastore with matching name */
            result = 0;

            goto cleanup;
3091 3092 3093
        }
    }

3094
    if (!(*datastore) && occurrence != esxVI_Occurrence_OptionalItem) {
3095 3096
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datastore with name '%s'"), name);
3097 3098 3099 3100 3101
        goto cleanup;
    }

    result = 0;

3102
 cleanup:
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
    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;

3125
    if (!datastore || *datastore) {
3126
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136
        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 已提交
3137 3138 3139
    }

    /* Search for a matching datastore */
3140
    for (candidate = datastoreList; candidate;
M
Matthias Bolte 已提交
3141
         candidate = candidate->_next) {
3142
        esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
3143

3144
        for (dynamicProperty = candidate->propSet; dynamicProperty;
M
Matthias Bolte 已提交
3145
             dynamicProperty = dynamicProperty->_next) {
3146 3147 3148
            if (STREQ(dynamicProperty->name, "host")) {
                if (esxVI_DatastoreHostMount_CastListFromAnyType
                      (dynamicProperty->val, &datastoreHostMountList) < 0) {
M
Matthias Bolte 已提交
3149
                    goto cleanup;
3150 3151 3152 3153 3154 3155
                }

                break;
            }
        }

3156
        if (!datastoreHostMountList)
3157
            continue;
3158

3159
        for (datastoreHostMount = datastoreHostMountList;
3160
             datastoreHostMount;
3161 3162 3163 3164 3165
             datastoreHostMount = datastoreHostMount->_next) {
            if (STRNEQ(ctx->hostSystem->_reference->value,
                       datastoreHostMount->key->value)) {
                continue;
            }
3166

3167
            if (STRPREFIX(absolutePath, datastoreHostMount->mountInfo->path)) {
3168
                if (esxVI_ObjectContent_DeepCopy(datastore, candidate) < 0)
M
Matthias Bolte 已提交
3169
                    goto cleanup;
M
Matthias Bolte 已提交
3170

3171
                /* Found datastore with matching mount path */
3172 3173 3174
                result = 0;

                goto cleanup;
M
Matthias Bolte 已提交
3175 3176 3177 3178
            }
        }
    }

3179
    if (!(*datastore) && occurrence != esxVI_Occurrence_OptionalItem) {
3180 3181 3182
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datastore containing absolute path '%s'"),
                       absolutePath);
M
Matthias Bolte 已提交
3183
        goto cleanup;
M
Matthias Bolte 已提交
3184 3185
    }

M
Matthias Bolte 已提交
3186 3187
    result = 0;

3188
 cleanup:
M
Matthias Bolte 已提交
3189 3190
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
3191
    esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
M
Matthias Bolte 已提交
3192 3193

    return result;
3194 3195 3196 3197
}



3198 3199 3200
int
esxVI_LookupDatastoreHostMount(esxVI_Context *ctx,
                               esxVI_ManagedObjectReference *datastore,
3201 3202
                               esxVI_DatastoreHostMount **hostMount,
                               esxVI_Occurrence occurrence)
3203 3204 3205 3206 3207 3208 3209 3210
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_DatastoreHostMount *hostMountList = NULL;
    esxVI_DatastoreHostMount *candidate = NULL;

3211
    if (!hostMount || *hostMount) {
3212
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3213 3214 3215 3216 3217
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList, "host") < 0 ||
        esxVI_LookupObjectContentByType(ctx, datastore, "Datastore",
3218 3219
                                        propertyNameList, &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
3220 3221 3222
        goto cleanup;
    }

3223
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
         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);
        }
    }

3237
    for (candidate = hostMountList; candidate;
3238
         candidate = candidate->_next) {
3239
        if (STRNEQ(ctx->hostSystem->_reference->value, candidate->key->value))
3240 3241
            continue;

3242
        if (esxVI_DatastoreHostMount_DeepCopy(hostMount, candidate) < 0)
3243 3244 3245 3246 3247
            goto cleanup;

        break;
    }

3248
    if (!(*hostMount) && occurrence == esxVI_Occurrence_RequiredItem) {
3249 3250
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not lookup datastore host mount"));
3251 3252 3253 3254 3255
        goto cleanup;
    }

    result = 0;

3256
 cleanup:
3257 3258 3259 3260 3261 3262 3263 3264
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);
    esxVI_DatastoreHostMount_Free(&hostMountList);

    return result;
}


3265 3266 3267 3268
int
esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
                           esxVI_ManagedObjectReference *task,
                           esxVI_TaskInfo **taskInfo)
3269
{
M
Matthias Bolte 已提交
3270
    int result = -1;
3271 3272 3273 3274
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

3275
    if (!taskInfo || *taskInfo) {
3276
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3277 3278 3279
        return -1;
    }

3280 3281
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
3282 3283
                                        &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3284
        goto cleanup;
3285 3286
    }

3287
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
3288 3289
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
3290
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
3291
                                               taskInfo) < 0) {
M
Matthias Bolte 已提交
3292
                goto cleanup;
3293 3294 3295 3296 3297 3298 3299 3300
            }

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

M
Matthias Bolte 已提交
3301 3302
    result = 0;

3303
 cleanup:
3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);

    return result;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
3314
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
3315 3316
   esxVI_TaskInfo **pendingTaskInfoList)
{
M
Matthias Bolte 已提交
3317
    int result = -1;
3318 3319 3320 3321 3322 3323
    esxVI_String *propertyNameList = NULL;
    esxVI_ManagedObjectReference *recentTaskList = NULL;
    esxVI_ManagedObjectReference *recentTask = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_TaskInfo *taskInfo = NULL;

3324
    if (!pendingTaskInfoList || *pendingTaskInfoList) {
3325
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3326 3327 3328 3329
        return -1;
    }

    /* Get list of recent tasks */
3330
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
3331 3332 3333
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "recentTask")) {
            if (esxVI_ManagedObjectReference_CastListFromAnyType
3334
                  (dynamicProperty->val, &recentTaskList) < 0) {
M
Matthias Bolte 已提交
3335
                goto cleanup;
3336 3337 3338 3339 3340 3341 3342
            }

            break;
        }
    }

    /* Lookup task info for each task */
3343
    for (recentTask = recentTaskList; recentTask;
3344
         recentTask = recentTask->_next) {
3345
        if (esxVI_LookupTaskInfoByTask(ctx, recentTask, &taskInfo) < 0)
M
Matthias Bolte 已提交
3346
            goto cleanup;
3347 3348 3349

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
3350
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
3351
                                            taskInfo) < 0) {
M
Matthias Bolte 已提交
3352
                goto cleanup;
3353 3354 3355 3356 3357 3358 3359 3360
            }

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

M
Matthias Bolte 已提交
3361 3362
    result = 0;

3363
 cleanup:
3364
    if (result < 0)
M
Matthias Bolte 已提交
3365 3366
        esxVI_TaskInfo_Free(pendingTaskInfoList);

3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



int
3377
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
3378
                                            const unsigned char *uuid,
3379
                                            esxVI_Occurrence occurrence,
3380
                                            bool autoAnswer, bool *blocked)
3381
{
M
Matthias Bolte 已提交
3382
    int result = -1;
3383 3384 3385 3386
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

3387
    if (esxVI_String_AppendValueToList(&propertyNameList,
3388
                                       "runtime.question") < 0 ||
3389
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
3390
                                         &virtualMachine, occurrence) < 0) {
M
Matthias Bolte 已提交
3391
        goto cleanup;
3392 3393
    }

3394
    if (virtualMachine) {
3395 3396 3397 3398 3399
        if (esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
                                                &questionInfo) < 0) {
            goto cleanup;
        }

3400
        if (questionInfo &&
3401 3402 3403 3404 3405
            esxVI_HandleVirtualMachineQuestion(ctx, virtualMachine->obj,
                                               questionInfo, autoAnswer,
                                               blocked) < 0) {
            goto cleanup;
        }
3406 3407
    }

M
Matthias Bolte 已提交
3408 3409
    result = 0;

3410
 cleanup:
3411 3412 3413 3414 3415 3416 3417 3418 3419
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);

    return result;
}



3420 3421 3422 3423 3424
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
M
Matthias Bolte 已提交
3425
    int result = -1;
3426 3427 3428 3429
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

3430
    if (!rootSnapshotTreeList || *rootSnapshotTreeList) {
3431
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3432 3433 3434 3435 3436 3437 3438 3439
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "snapshot.rootSnapshotList") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3440
        goto cleanup;
3441 3442
    }

3443
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
3444 3445 3446 3447
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3448
                goto cleanup;
3449 3450 3451 3452 3453 3454 3455 3456
            }

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

M
Matthias Bolte 已提交
3457 3458
    result = 0;

3459
 cleanup:
3460
    if (result < 0)
M
Matthias Bolte 已提交
3461 3462
        esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);

3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476
    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 已提交
3477
    int result = -1;
3478 3479 3480 3481 3482 3483 3484
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *currentSnapshot = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;

3485
    if (!currentSnapshotTree || *currentSnapshotTree) {
3486
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3487 3488 3489 3490 3491 3492 3493 3494 3495
        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 已提交
3496
        goto cleanup;
3497 3498
    }

3499
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
3500 3501 3502 3503
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.currentSnapshot")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, &currentSnapshot) < 0) {
M
Matthias Bolte 已提交
3504
                goto cleanup;
3505 3506 3507 3508
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3509
                goto cleanup;
3510 3511 3512 3513 3514 3515
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

3516
    if (!currentSnapshot) {
3517
        if (occurrence == esxVI_Occurrence_OptionalItem) {
3518 3519 3520
            result = 0;

            goto cleanup;
3521
        } else {
3522 3523
            virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                           _("Domain has no current snapshot"));
M
Matthias Bolte 已提交
3524
            goto cleanup;
3525 3526 3527
        }
    }

3528
    if (!rootSnapshotTreeList) {
3529 3530
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not lookup root snapshot list"));
M
Matthias Bolte 已提交
3531
        goto cleanup;
3532 3533 3534 3535 3536 3537
    }

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

M
Matthias Bolte 已提交
3541 3542
    result = 0;

3543
 cleanup:
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



3554 3555 3556
int
esxVI_LookupFileInfoByDatastorePath(esxVI_Context *ctx,
                                    const char *datastorePath,
3557
                                    bool lookupFolder,
3558 3559 3560 3561 3562 3563
                                    esxVI_FileInfo **fileInfo,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    char *datastoreName = NULL;
    char *directoryName = NULL;
3564
    char *directoryAndFileName = NULL;
3565
    char *fileName = NULL;
3566
    size_t length;
3567 3568 3569 3570 3571
    char *datastorePathWithoutFileName = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
3572
    esxVI_FolderFileQuery *folderFileQuery = NULL;
3573 3574 3575 3576 3577
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3578
    char *taskInfoErrorMessage = NULL;
3579 3580 3581
    esxVI_TaskInfo *taskInfo = NULL;
    esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL;

3582
    if (!fileInfo || *fileInfo) {
3583
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3584 3585 3586 3587
        return -1;
    }

    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName,
3588
                                   &directoryName, &directoryAndFileName) < 0) {
3589 3590 3591
        goto cleanup;
    }

3592 3593 3594 3595 3596
    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.
         */
3597
        if (virAsprintf(&datastorePathWithoutFileName, "[%s]",
3598
                        datastoreName) < 0)
3599
            goto cleanup;
3600

3601
        if (VIR_STRDUP(fileName, directoryAndFileName) < 0)
3602
            goto cleanup;
3603 3604
    } else {
        if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s",
3605
                        datastoreName, directoryName) < 0)
3606
            goto cleanup;
3607 3608 3609 3610 3611

        length = strlen(directoryName);

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

3618
        if (VIR_STRDUP(fileName, directoryAndFileName + length + 1) < 0)
3619
            goto cleanup;
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
    }

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

3643 3644 3645 3646 3647 3648 3649
    if (lookupFolder) {
        if (esxVI_FolderFileQuery_Alloc(&folderFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(folderFileQuery)) < 0) {
            goto cleanup;
        }
3650
        folderFileQuery = NULL;
3651 3652 3653 3654 3655 3656 3657 3658
    } 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;
        }
3659

3660 3661 3662 3663 3664
        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;
3665
        vmDiskFileQuery = NULL;
3666

3667 3668 3669 3670 3671 3672
        if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
            goto cleanup;
        }
3673
        isoImageFileQuery = NULL;
3674

3675 3676 3677 3678 3679 3680
        if (esxVI_FloppyImageFileQuery_Alloc(&floppyImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(floppyImageFileQuery)) < 0) {
            goto cleanup;
        }
3681
        floppyImageFileQuery = NULL;
3682 3683
    }

3684
    if (esxVI_String_Alloc(&searchSpec->matchPattern) < 0)
3685 3686 3687 3688 3689 3690 3691 3692 3693
        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,
3694
                                    false, &taskInfoState,
3695
                                    &taskInfoErrorMessage) < 0) {
3696 3697 3698 3699
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3700 3701 3702
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not search in datastore '%s': %s"),
                       datastoreName, taskInfoErrorMessage);
3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
        goto cleanup;
    }

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

    /* Interpret search result */
3713
    if (!searchResults->file) {
3714 3715 3716 3717 3718
        if (occurrence == esxVI_Occurrence_OptionalItem) {
            result = 0;

            goto cleanup;
        } else {
3719 3720 3721
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("No storage volume with key or path '%s'"),
                           datastorePath);
3722 3723 3724 3725 3726 3727 3728 3729 3730
            goto cleanup;
        }
    }

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

    result = 0;

3731
 cleanup:
3732
    /* Don't double free fileName */
3733
    if (searchSpec && searchSpec->matchPattern)
3734 3735 3736 3737
        searchSpec->matchPattern->value = NULL;

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3738
    VIR_FREE(directoryAndFileName);
3739 3740 3741 3742 3743 3744 3745
    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);
3746
    VIR_FREE(taskInfoErrorMessage);
3747 3748
    esxVI_TaskInfo_Free(&taskInfo);
    esxVI_HostDatastoreBrowserSearchResults_Free(&searchResults);
3749 3750 3751 3752
    esxVI_FolderFileQuery_Free(&folderFileQuery);
    esxVI_VmDiskFileQuery_Free(&vmDiskFileQuery);
    esxVI_IsoImageFileQuery_Free(&isoImageFileQuery);
    esxVI_FloppyImageFileQuery_Free(&floppyImageFileQuery);
3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774

    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;
3775
    char *taskInfoErrorMessage = NULL;
3776 3777
    esxVI_TaskInfo *taskInfo = NULL;

3778
    if (!searchResultsList || *searchResultsList) {
3779
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
        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;
3817
    vmDiskFileQuery = NULL;
3818 3819 3820 3821 3822 3823 3824

    if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
        esxVI_FileQuery_AppendToList
          (&searchSpec->query,
           esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
        goto cleanup;
    }
3825
    isoImageFileQuery = NULL;
3826 3827 3828 3829 3830 3831 3832

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

    /* Search datastore for files */
3836
    if (virAsprintf(&datastorePath, "[%s]", datastoreName) < 0)
3837 3838 3839 3840 3841 3842
        goto cleanup;

    if (esxVI_SearchDatastoreSubFolders_Task(ctx, hostDatastoreBrowser,
                                             datastorePath, searchSpec,
                                             &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3843
                                    false, &taskInfoState,
3844
                                    &taskInfoErrorMessage) < 0) {
3845 3846 3847 3848
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3849
        virReportError(VIR_ERR_INTERNAL_ERROR,
3850
                       _("Could not search in datastore '%s': %s"),
3851
                       datastoreName, taskInfoErrorMessage);
3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862
        goto cleanup;
    }

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

    result = 0;

3863
 cleanup:
3864 3865 3866 3867 3868 3869
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    VIR_FREE(datastorePath);
    esxVI_ManagedObjectReference_Free(&task);
3870
    VIR_FREE(taskInfoErrorMessage);
3871
    esxVI_TaskInfo_Free(&taskInfo);
3872 3873 3874
    esxVI_VmDiskFileQuery_Free(&vmDiskFileQuery);
    esxVI_IsoImageFileQuery_Free(&isoImageFileQuery);
    esxVI_FloppyImageFileQuery_Free(&floppyImageFileQuery);
3875 3876 3877 3878 3879 3880

    return result;
}



3881 3882 3883 3884 3885 3886 3887 3888 3889
int
esxVI_LookupStorageVolumeKeyByDatastorePath(esxVI_Context *ctx,
                                            const char *datastorePath,
                                            char **key)
{
    int result = -1;
    esxVI_FileInfo *fileInfo = NULL;
    char *uuid_string = NULL;

3890
    if (!key || *key) {
3891
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3892 3893 3894
        return -1;
    }

3895 3896 3897 3898
    if (ctx->hasQueryVirtualDiskUuid) {
        if (esxVI_LookupFileInfoByDatastorePath
              (ctx, datastorePath, false, &fileInfo,
               esxVI_Occurrence_RequiredItem) < 0) {
3899 3900 3901
            goto cleanup;
        }

3902
        if (esxVI_VmDiskFileInfo_DynamicCast(fileInfo)) {
3903 3904 3905 3906 3907 3908
            /* VirtualDisks have a UUID, use it as key */
            if (esxVI_QueryVirtualDiskUuid(ctx, datastorePath,
                                           ctx->datacenter->_reference,
                                           &uuid_string) < 0) {
                goto cleanup;
            }
3909

3910
            if (VIR_ALLOC_N(*key, VIR_UUID_STRING_BUFLEN) < 0)
3911 3912
                goto cleanup;

3913
            if (esxUtil_ReformatUuid(uuid_string, *key) < 0)
3914
                goto cleanup;
3915
        }
3916 3917
    }

3918
    if (!(*key)) {
3919
        /* Other files don't have a UUID, fall back to the path as key */
3920
        if (VIR_STRDUP(*key, datastorePath) < 0)
3921 3922 3923 3924 3925
            goto cleanup;
    }

    result = 0;

3926
 cleanup:
3927 3928 3929 3930 3931 3932 3933 3934
    esxVI_FileInfo_Free(&fileInfo);
    VIR_FREE(uuid_string);

    return result;
}



3935 3936 3937 3938 3939 3940 3941 3942 3943
int
esxVI_LookupAutoStartDefaults(esxVI_Context *ctx,
                              esxVI_AutoStartDefaults **defaults)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostAutoStartManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

3944
    if (!defaults || *defaults) {
3945
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958
        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,
3959
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3960 3961 3962 3963
        goto cleanup;
    }

    for (dynamicProperty = hostAutoStartManager->propSet;
3964
         dynamicProperty; dynamicProperty = dynamicProperty->_next) {
3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
        if (STREQ(dynamicProperty->name, "config.defaults")) {
            if (esxVI_AutoStartDefaults_CastFromAnyType(dynamicProperty->val,
                                                        defaults) < 0) {
                goto cleanup;
            }

            break;
        }
    }

3975
    if (!(*defaults)) {
3976 3977
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve the AutoStartDefaults object"));
3978 3979 3980 3981 3982
        goto cleanup;
    }

    result = 0;

3983
 cleanup:
3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
    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;

4001
    if (!powerInfoList || *powerInfoList) {
4002
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
        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,
4016
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
4017 4018 4019 4020
        goto cleanup;
    }

    for (dynamicProperty = hostAutoStartManager->propSet;
4021
         dynamicProperty; dynamicProperty = dynamicProperty->_next) {
4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033
        if (STREQ(dynamicProperty->name, "config.powerInfo")) {
            if (esxVI_AutoStartPowerInfo_CastListFromAnyType
                  (dynamicProperty->val, powerInfoList) < 0) {
                goto cleanup;
            }

            break;
        }
    }

    result = 0;

4034
 cleanup:
4035 4036 4037 4038 4039 4040 4041 4042
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostAutoStartManager);

    return result;
}



M
Matthias Bolte 已提交
4043 4044 4045 4046 4047 4048 4049 4050 4051
int
esxVI_LookupPhysicalNicList(esxVI_Context *ctx,
                            esxVI_PhysicalNic **physicalNicList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

4052
    if (!physicalNicList || *physicalNicList) {
M
Matthias Bolte 已提交
4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.network.pnic") < 0 ||
        esxVI_LookupHostSystemProperties(ctx, propertyNameList,
                                         &hostSystem) < 0) {
        goto cleanup;
    }

4064
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.network.pnic")) {
            if (esxVI_PhysicalNic_CastListFromAnyType(dynamicProperty->val,
                                                      physicalNicList) < 0) {
                goto cleanup;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    result = 0;

4078
 cleanup:
M
Matthias Bolte 已提交
4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



int
esxVI_LookupPhysicalNicByName(esxVI_Context *ctx, const char *name,
                              esxVI_PhysicalNic **physicalNic,
                              esxVI_Occurrence occurrence)
{
    int result = -1;
    esxVI_PhysicalNic *physicalNicList = NULL;
    esxVI_PhysicalNic *candidate = NULL;

4096
    if (!physicalNic || *physicalNic) {
M
Matthias Bolte 已提交
4097 4098 4099 4100
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

4101
    if (esxVI_LookupPhysicalNicList(ctx, &physicalNicList) < 0)
M
Matthias Bolte 已提交
4102 4103 4104
        goto cleanup;

    /* Search for a matching physical NIC */
4105
    for (candidate = physicalNicList; candidate;
M
Matthias Bolte 已提交
4106 4107
         candidate = candidate->_next) {
        if (STRCASEEQ(candidate->device, name)) {
4108
            if (esxVI_PhysicalNic_DeepCopy(physicalNic, candidate) < 0)
M
Matthias Bolte 已提交
4109 4110 4111 4112 4113 4114 4115 4116 4117
                goto cleanup;

            /* Found physical NIC with matching name */
            result = 0;

            goto cleanup;
        }
    }

4118
    if (!(*physicalNic) && occurrence != esxVI_Occurrence_OptionalItem) {
M
Matthias Bolte 已提交
4119 4120 4121 4122 4123 4124 4125
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("Could not find physical NIC with name '%s'"), name);
        goto cleanup;
    }

    result = 0;

4126
 cleanup:
M
Matthias Bolte 已提交
4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142
    esxVI_PhysicalNic_Free(&physicalNicList);

    return result;
}



int
esxVI_LookupPhysicalNicByMACAddress(esxVI_Context *ctx, const char *mac,
                                    esxVI_PhysicalNic **physicalNic,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    esxVI_PhysicalNic *physicalNicList = NULL;
    esxVI_PhysicalNic *candidate = NULL;

4143
    if (!physicalNic || *physicalNic) {
M
Matthias Bolte 已提交
4144 4145 4146 4147
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

4148
    if (esxVI_LookupPhysicalNicList(ctx, &physicalNicList) < 0)
M
Matthias Bolte 已提交
4149 4150 4151
        goto cleanup;

    /* Search for a matching physical NIC */
4152
    for (candidate = physicalNicList; candidate;
M
Matthias Bolte 已提交
4153 4154
         candidate = candidate->_next) {
        if (STRCASEEQ(candidate->mac, mac)) {
4155
            if (esxVI_PhysicalNic_DeepCopy(physicalNic, candidate) < 0)
M
Matthias Bolte 已提交
4156 4157 4158 4159 4160 4161 4162 4163 4164
                goto cleanup;

            /* Found physical NIC with matching MAC address */
            result = 0;

            goto cleanup;
        }
    }

4165
    if (!(*physicalNic) && occurrence != esxVI_Occurrence_OptionalItem) {
M
Matthias Bolte 已提交
4166 4167 4168 4169 4170 4171 4172
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("Could not find physical NIC with MAC address '%s'"), mac);
        goto cleanup;
    }

    result = 0;

4173
 cleanup:
M
Matthias Bolte 已提交
4174 4175 4176 4177 4178 4179 4180
    esxVI_PhysicalNic_Free(&physicalNicList);

    return result;
}



M
Matthias Bolte 已提交
4181 4182 4183 4184 4185 4186 4187 4188 4189
int
esxVI_LookupHostVirtualSwitchList(esxVI_Context *ctx,
                                  esxVI_HostVirtualSwitch **hostVirtualSwitchList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

4190
    if (!hostVirtualSwitchList || *hostVirtualSwitchList) {
M
Matthias Bolte 已提交
4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.network.vswitch") < 0 ||
        esxVI_LookupHostSystemProperties(ctx, propertyNameList,
                                         &hostSystem) < 0) {
        goto cleanup;
    }

4202
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.network.vswitch")) {
            if (esxVI_HostVirtualSwitch_CastListFromAnyType
                 (dynamicProperty->val, hostVirtualSwitchList) < 0) {
                goto cleanup;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    result = 0;

4216
 cleanup:
M
Matthias Bolte 已提交
4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



int
esxVI_LookupHostVirtualSwitchByName(esxVI_Context *ctx, const char *name,
                                    esxVI_HostVirtualSwitch **hostVirtualSwitch,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    esxVI_HostVirtualSwitch *hostVirtualSwitchList = NULL;
    esxVI_HostVirtualSwitch *candidate = NULL;

4234
    if (!hostVirtualSwitch || *hostVirtualSwitch) {
M
Matthias Bolte 已提交
4235 4236 4237 4238
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

4239
    if (esxVI_LookupHostVirtualSwitchList(ctx, &hostVirtualSwitchList) < 0)
M
Matthias Bolte 已提交
4240 4241 4242
        goto cleanup;

    /* Search for a matching HostVirtualSwitch */
4243
    for (candidate = hostVirtualSwitchList; candidate;
M
Matthias Bolte 已提交
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
         candidate = candidate->_next) {
        if (STREQ(candidate->name, name)) {
            if (esxVI_HostVirtualSwitch_DeepCopy(hostVirtualSwitch,
                                                 candidate) < 0) {
                goto cleanup;
            }

            /* Found HostVirtualSwitch with matching name */
            result = 0;

            goto cleanup;
        }
    }

4258
    if (!(*hostVirtualSwitch) &&
M
Matthias Bolte 已提交
4259 4260 4261 4262 4263 4264 4265 4266 4267
        occurrence != esxVI_Occurrence_OptionalItem) {
        virReportError(VIR_ERR_NO_NETWORK,
                       _("Could not find HostVirtualSwitch with name '%s'"),
                       name);
        goto cleanup;
    }

    result = 0;

4268
 cleanup:
M
Matthias Bolte 已提交
4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284
    esxVI_HostVirtualSwitch_Free(&hostVirtualSwitchList);

    return result;
}



int
esxVI_LookupHostPortGroupList(esxVI_Context *ctx,
                              esxVI_HostPortGroup **hostPortGroupList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

4285
    if (!hostPortGroupList || *hostPortGroupList) {
M
Matthias Bolte 已提交
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.network.portgroup") < 0 ||
        esxVI_LookupHostSystemProperties(ctx, propertyNameList,
                                         &hostSystem) < 0) {
        goto cleanup;
    }

4297
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.network.portgroup")) {
            if (esxVI_HostPortGroup_CastListFromAnyType
                  (dynamicProperty->val, hostPortGroupList) < 0) {
                goto cleanup;
            }

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

    result = 0;

4313
 cleanup:
M
Matthias Bolte 已提交
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



int
esxVI_LookupNetworkList(esxVI_Context *ctx, esxVI_String *propertyNameList,
                        esxVI_ObjectContent **networkList)
{
    return esxVI_LookupObjectContentByType(ctx, ctx->datacenter->_reference,
                                           "Network", propertyNameList,
                                           networkList,
                                           esxVI_Occurrence_OptionalList);
}



4334 4335
int
esxVI_HandleVirtualMachineQuestion
4336
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
4337 4338
   esxVI_VirtualMachineQuestionInfo *questionInfo, bool autoAnswer,
   bool *blocked)
4339
{
M
Matthias Bolte 已提交
4340
    int result = -1;
4341 4342 4343 4344 4345 4346
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

4347
    if (!blocked) {
4348
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
4349 4350 4351
        return -1;
    }

4352
    *blocked = false;
4353

4354
    if (questionInfo->choice->choiceInfo) {
4355
        for (elementDescription = questionInfo->choice->choiceInfo;
4356
             elementDescription;
4357
             elementDescription = elementDescription->_next) {
4358
            virBufferAsprintf(&buffer, "'%s'", elementDescription->label);
4359

4360
            if (elementDescription->_next)
4361 4362
                virBufferAddLit(&buffer, ", ");

4363 4364
            if (!answerChoice &&
                questionInfo->choice->defaultIndex &&
4365 4366 4367 4368 4369 4370 4371
                questionInfo->choice->defaultIndex->value == answerIndex) {
                answerChoice = elementDescription;
            }

            ++answerIndex;
        }

4372
        if (virBufferCheckError(&buffer) < 0)
M
Matthias Bolte 已提交
4373
            goto cleanup;
4374 4375 4376 4377

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

4378
    if (autoAnswer) {
4379
        if (!possibleAnswers) {
4380 4381 4382 4383
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', no possible answers"),
                           questionInfo->text);
4384

4385
            *blocked = true;
M
Matthias Bolte 已提交
4386
            goto cleanup;
4387
        } else if (!answerChoice) {
4388 4389 4390 4391 4392
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', possible answers are %s, but no "
                             "default answer is specified"), questionInfo->text,
                           possibleAnswers);
4393

4394
            *blocked = true;
M
Matthias Bolte 已提交
4395
            goto cleanup;
4396 4397 4398 4399 4400 4401 4402
        }

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

4403
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
4404
                           answerChoice->key) < 0) {
M
Matthias Bolte 已提交
4405
            goto cleanup;
4406 4407
        }
    } else {
4408
        if (possibleAnswers) {
4409 4410 4411 4412
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', possible answers are %s"),
                           questionInfo->text, possibleAnswers);
4413
        } else {
4414 4415 4416 4417
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', no possible answers"),
                           questionInfo->text);
4418 4419
        }

4420
        *blocked = true;
M
Matthias Bolte 已提交
4421
        goto cleanup;
4422 4423
    }

M
Matthias Bolte 已提交
4424 4425
    result = 0;

4426
 cleanup:
4427
    if (result < 0)
M
Matthias Bolte 已提交
4428 4429
        virBufferFreeAndReset(&buffer);

4430 4431 4432 4433 4434 4435 4436
    VIR_FREE(possibleAnswers);

    return result;
}



4437
int
4438
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
4439
                            esxVI_ManagedObjectReference *task,
4440
                            const unsigned char *virtualMachineUuid,
4441
                            esxVI_Occurrence virtualMachineOccurrence,
4442
                            bool autoAnswer, esxVI_TaskInfoState *finalState,
4443
                            char **errorMessage)
4444
{
M
Matthias Bolte 已提交
4445
    int result = -1;
4446
    esxVI_ObjectSpec *objectSpec = NULL;
4447
    bool objectSpec_isAppended = false;
4448
    esxVI_PropertySpec *propertySpec = NULL;
4449
    bool propertySpec_isAppended = false;
4450 4451 4452 4453 4454 4455 4456 4457 4458
    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;
4459
    bool blocked;
4460
    esxVI_TaskInfo *taskInfo = NULL;
4461

4462
    if (!errorMessage || *errorMessage) {
4463
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
4464 4465 4466
        return -1;
    }

4467
    if (VIR_STRDUP(version, "") < 0)
M
Matthias Bolte 已提交
4468
        return -1;
4469

4470
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0)
M
Matthias Bolte 已提交
4471
        goto cleanup;
4472 4473 4474 4475

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

4476
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0)
M
Matthias Bolte 已提交
4477
        goto cleanup;
4478 4479 4480

    propertySpec->type = task->type;

4481
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
4482
                                       "info.state") < 0 ||
4483 4484
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498
                                        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,
4499
                           &propertyFilter) < 0) {
M
Matthias Bolte 已提交
4500
        goto cleanup;
4501 4502 4503 4504 4505 4506
    }

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

4507
        if (virtualMachineUuid) {
4508
            if (esxVI_LookupAndHandleVirtualMachineQuestion
4509 4510
                  (ctx, virtualMachineUuid, virtualMachineOccurrence,
                   autoAnswer, &blocked) < 0) {
4511 4512 4513 4514 4515
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
4516
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo))
M
Matthias Bolte 已提交
4517
                    goto cleanup;
4518 4519

                if (taskInfo->cancelable == esxVI_Boolean_True) {
4520
                    if (esxVI_CancelTask(ctx, task) < 0 && blocked) {
4521
                        VIR_ERROR(_("Cancelable task is blocked by an "
E
Eric Blake 已提交
4522
                                     "unanswered question but cancellation "
4523
                                     "failed"));
4524
                    }
4525
                } else if (blocked) {
4526
                    VIR_ERROR(_("Non-cancelable task is blocked by an "
4527
                                 "unanswered question"));
4528 4529 4530 4531
                }

                /* FIXME: Enable error reporting here again */

M
Matthias Bolte 已提交
4532
                goto cleanup;
4533 4534 4535
            }
        }

4536
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0)
M
Matthias Bolte 已提交
4537
            goto cleanup;
4538 4539

        VIR_FREE(version);
4540
        if (VIR_STRDUP(version, updateSet->version) < 0)
M
Matthias Bolte 已提交
4541
            goto cleanup;
4542

4543
        if (!updateSet->filterSet)
4544 4545 4546
            continue;

        for (propertyFilterUpdate = updateSet->filterSet;
4547
             propertyFilterUpdate;
4548 4549
             propertyFilterUpdate = propertyFilterUpdate->_next) {
            for (objectUpdate = propertyFilterUpdate->objectSet;
4550
                 objectUpdate; objectUpdate = objectUpdate->_next) {
4551
                for (propertyChange = objectUpdate->changeSet;
4552
                     propertyChange;
4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565
                     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;
                        }
                    }
                }
            }
        }

4566
        if (!propertyValue)
4567 4568
            continue;

4569
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0)
M
Matthias Bolte 已提交
4570
            goto cleanup;
4571 4572
    }

4573
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0)
4574
        VIR_DEBUG("DestroyPropertyFilter failed");
4575

4576
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0)
M
Matthias Bolte 已提交
4577
        goto cleanup;
4578

4579
    if (*finalState != esxVI_TaskInfoState_Success) {
4580
        if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo))
4581 4582
            goto cleanup;

4583
        if (!taskInfo->error) {
4584
            if (VIR_STRDUP(*errorMessage, _("Unknown error")) < 0)
4585
                goto cleanup;
4586
        } else if (!taskInfo->error->localizedMessage) {
4587
            if (VIR_STRDUP(*errorMessage, taskInfo->error->fault->_actualType) < 0)
4588 4589 4590 4591
                goto cleanup;
        } else {
            if (virAsprintf(errorMessage, "%s - %s",
                            taskInfo->error->fault->_actualType,
4592
                            taskInfo->error->localizedMessage) < 0)
4593 4594 4595 4596
                goto cleanup;
        }
    }

M
Matthias Bolte 已提交
4597 4598
    result = 0;

4599
 cleanup:
4600 4601 4602 4603
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
     */
4604
    if (objectSpec)
4605 4606
        objectSpec->obj = NULL;

4607
    if (propertySpec)
4608 4609
        propertySpec->type = NULL;

4610
    if (!objectSpec_isAppended)
4611 4612
        esxVI_ObjectSpec_Free(&objectSpec);

4613
    if (!propertySpec_isAppended)
4614 4615
        esxVI_PropertySpec_Free(&propertySpec);

4616 4617 4618 4619
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);
    esxVI_ManagedObjectReference_Free(&propertyFilter);
    VIR_FREE(version);
    esxVI_UpdateSet_Free(&updateSet);
4620
    esxVI_TaskInfo_Free(&taskInfo);
4621 4622 4623

    return result;
}
4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636



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" };
4637
    size_t r, i, o;
4638

4639
    memset(parsedHostCpuIdInfo, 0, sizeof(*parsedHostCpuIdInfo));
4640 4641 4642 4643 4644

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

    for (r = 0; r < 4; ++r) {
        if (strlen(input[r]) != expectedLength) {
4645 4646 4647
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("HostCpuIdInfo register '%s' has an unexpected length"),
                           name[r]);
M
Matthias Bolte 已提交
4648
            return -1;
4649 4650 4651 4652 4653 4654 4655 4656 4657 4658
        }

        /* 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] != ':') {
4659 4660 4661
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("HostCpuIdInfo register '%s' has an unexpected format"),
                               name[r]);
M
Matthias Bolte 已提交
4662
                return -1;
4663 4664 4665 4666 4667 4668
            }
        }
    }

    return 0;
}
4669 4670 4671



4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691
const char *
esxVI_ProductLineToDisplayName(esxVI_ProductLine productLine)
{
    switch (productLine) {
      case esxVI_ProductLine_GSX:
        return "Server/GSX";

      case esxVI_ProductLine_ESX:
        return "ESX(i)";

      case esxVI_ProductLine_VPX:
        return "vCenter/VPX";

      default:
        return "<unknown>";
    }
}



4692
int
4693 4694
esxVI_ProductVersionToDefaultVirtualHWVersion(esxVI_ProductLine productLine,
                                              unsigned long productVersion)
4695
{
4696 4697 4698
    /* product version == 1000000 * major + 1000 * minor + micro */
    int major = productVersion / 1000000;

4699 4700 4701
    /*
     * virtualHW.version compatibility matrix:
     *
4702 4703 4704 4705 4706 4707 4708 4709
     *              4 7 8 9 10   API
     *   ESX 3.5    +            2.5
     *   ESX 4.0    + +          4.0
     *   ESX 4.1    + +          4.1
     *   ESX 5.0    + + +        5.0
     *   ESX 5.1    + + + +      5.1
     *   ESX 5.5    + + + + +    5.5
     *   GSX 2.0    + +          2.5
4710
     */
4711 4712
    switch (productLine) {
      case esxVI_ProductLine_GSX:
4713 4714
        return 7;

4715 4716 4717 4718
      case esxVI_ProductLine_ESX:
        switch (major) {
          case 3:
            return 4;
4719

4720 4721
          case 4:
            return 7;
P
Patrice LACHANCE 已提交
4722

4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739
          case 5:
          default:
            return 8;
        }

      case esxVI_ProductLine_VPX:
        switch (major) {
          case 2:
            return 4;

          case 4:
            return 7;

          case 5:
          default:
            return 8;
        }
P
Patrice LACHANCE 已提交
4740

4741
      default:
4742
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4743
                       _("Unexpected product line"));
4744 4745 4746
        return -1;
    }
}
4747 4748 4749



4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764
int
esxVI_LookupHostInternetScsiHbaStaticTargetByName
  (esxVI_Context *ctx, const char *name,
   esxVI_HostInternetScsiHbaStaticTarget **target, esxVI_Occurrence occurrence)
{
    int result = -1;
    esxVI_HostInternetScsiHba *hostInternetScsiHba = NULL;
    esxVI_HostInternetScsiHbaStaticTarget *candidate = NULL;

    if (esxVI_LookupHostInternetScsiHba(ctx, &hostInternetScsiHba) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to obtain hostInternetScsiHba"));
        goto cleanup;
    }

4765
    if (!hostInternetScsiHba) {
4766 4767 4768 4769 4770
        /* iSCSI adapter may not be enabled for this host */
        return 0;
    }

    for (candidate = hostInternetScsiHba->configuredStaticTarget;
4771
         candidate; candidate = candidate->_next) {
4772
        if (STREQ(candidate->iScsiName, name))
4773 4774 4775
            break;
    }

4776
    if (!candidate) {
4777 4778 4779 4780 4781 4782 4783 4784
        if (occurrence == esxVI_Occurrence_RequiredItem) {
            virReportError(VIR_ERR_NO_STORAGE_POOL,
                           _("Could not find storage pool with name: %s"), name);
        }

        goto cleanup;
    }

4785
    if (esxVI_HostInternetScsiHbaStaticTarget_DeepCopy(target, candidate) < 0)
4786 4787 4788 4789
        goto cleanup;

    result = 0;

4790
 cleanup:
4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815
    esxVI_HostInternetScsiHba_Free(&hostInternetScsiHba);

    return result;
}



int
esxVI_LookupHostInternetScsiHba(esxVI_Context *ctx,
                                esxVI_HostInternetScsiHba **hostInternetScsiHba)
{
    int result = -1;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_HostHostBusAdapter *hostHostBusAdapterList = NULL;
    esxVI_HostHostBusAdapter *hostHostBusAdapter = NULL;

    if (esxVI_String_AppendValueToList
          (&propertyNameList, "config.storageDevice.hostBusAdapter") < 0 ||
        esxVI_LookupHostSystemProperties(ctx, propertyNameList,
                                         &hostSystem) < 0) {
        goto cleanup;
    }

4816
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
4817 4818 4819 4820
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.storageDevice.hostBusAdapter")) {
            if (esxVI_HostHostBusAdapter_CastListFromAnyType
4821 4822
                (dynamicProperty->val, &hostHostBusAdapterList) < 0 ||
                !hostHostBusAdapterList) {
4823 4824 4825 4826 4827 4828 4829 4830 4831
                goto cleanup;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    /* See vSphere API documentation about HostInternetScsiHba for details */
    for (hostHostBusAdapter = hostHostBusAdapterList;
4832
         hostHostBusAdapter;
4833
         hostHostBusAdapter = hostHostBusAdapter->_next) {
4834
        esxVI_HostInternetScsiHba *candidate =
4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847
            esxVI_HostInternetScsiHba_DynamicCast(hostHostBusAdapter);

        if (candidate) {
            if (esxVI_HostInternetScsiHba_DeepCopy(hostInternetScsiHba,
                  candidate) < 0) {
                goto cleanup;
            }
            break;
        }
    }

    result = 0;

4848
 cleanup:
4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostHostBusAdapter_Free(&hostHostBusAdapterList);

    return result;
}



int
esxVI_LookupScsiLunList(esxVI_Context *ctx, esxVI_ScsiLun **scsiLunList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty;

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "config.storageDevice.scsiLun") < 0 ||
        esxVI_LookupHostSystemProperties(ctx, propertyNameList,
                                         &hostSystem) < 0) {
        goto cleanup;
    }

4873
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "config.storageDevice.scsiLun")) {
            if (esxVI_ScsiLun_CastListFromAnyType(dynamicProperty->val,
                                                  scsiLunList) < 0) {
                goto cleanup;
            }

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

    result = 0;

4889
 cleanup:
4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);

    return result;
}



int
esxVI_LookupHostScsiTopologyLunListByTargetName
  (esxVI_Context *ctx, const char *name,
   esxVI_HostScsiTopologyLun **hostScsiTopologyLunList)
{
    int result = -1;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_HostScsiTopologyInterface *hostScsiInterfaceList = NULL;
    esxVI_HostScsiTopologyInterface *hostScsiInterface = NULL;
    esxVI_HostScsiTopologyTarget *hostScsiTopologyTarget = NULL;
    bool found = false;
    esxVI_HostInternetScsiTargetTransport *candidate = NULL;

4913
    if (!hostScsiTopologyLunList || *hostScsiTopologyLunList) {
4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList
          (&propertyNameList,
           "config.storageDevice.scsiTopology.adapter") < 0 ||
        esxVI_LookupHostSystemProperties(ctx, propertyNameList,
                                         &hostSystem) < 0) {
        goto cleanup;
    }

4926
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.storageDevice.scsiTopology.adapter")) {
            esxVI_HostScsiTopologyInterface_Free(&hostScsiInterfaceList);

            if (esxVI_HostScsiTopologyInterface_CastListFromAnyType
                  (dynamicProperty->val, &hostScsiInterfaceList) < 0) {
                goto cleanup;
            }

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

    if (hostScsiInterfaceList == NULL) {
        /* iSCSI adapter may not be enabled */
        return 0;
    }

    /* See vSphere API documentation about HostScsiTopologyInterface */
    for (hostScsiInterface = hostScsiInterfaceList;
4950
         hostScsiInterface && !found;
4951 4952
         hostScsiInterface = hostScsiInterface->_next) {
        for (hostScsiTopologyTarget = hostScsiInterface->target;
4953
             hostScsiTopologyTarget;
4954 4955 4956 4957
             hostScsiTopologyTarget = hostScsiTopologyTarget->_next) {
            candidate = esxVI_HostInternetScsiTargetTransport_DynamicCast
                          (hostScsiTopologyTarget->transport);

4958
            if (candidate && STREQ(candidate->iScsiName, name)) {
4959 4960 4961 4962 4963 4964
                found = true;
                break;
            }
        }
    }

4965
    if (!found || !hostScsiTopologyTarget)
4966 4967
        goto cleanup;

4968
    if (!hostScsiTopologyTarget->lun) {
4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Target not found"));
        goto cleanup;
    }

    if (esxVI_HostScsiTopologyLun_DeepCopyList(hostScsiTopologyLunList,
                                               hostScsiTopologyTarget->lun) < 0) {
        goto cleanup;
    }

    result = 0;

4981
 cleanup:
4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_HostScsiTopologyInterface_Free(&hostScsiInterfaceList);

    return result;
}



int
esxVI_LookupStoragePoolNameByScsiLunKey(esxVI_Context *ctx,
                                        const char *key,
                                        char **poolName)
{
    int result = -1;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_HostScsiTopologyInterface *hostScsiInterfaceList = NULL;
    esxVI_HostScsiTopologyInterface *hostScsiInterface = NULL;
    esxVI_HostScsiTopologyTarget *hostScsiTopologyTarget = NULL;
    esxVI_HostInternetScsiTargetTransport *candidate;
    esxVI_HostScsiTopologyLun *hostScsiTopologyLun;
    bool found = false;

5007
    if (!poolName || *poolName) {
5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList
          (&propertyNameList,
           "config.storageDevice.scsiTopology.adapter") < 0 ||
        esxVI_LookupHostSystemProperties(ctx, propertyNameList,
                                         &hostSystem) < 0) {
        goto cleanup;
    }

5020
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.storageDevice.scsiTopology.adapter")) {
            esxVI_HostScsiTopologyInterface_Free(&hostScsiInterfaceList);

            if (esxVI_HostScsiTopologyInterface_CastListFromAnyType
                  (dynamicProperty->val, &hostScsiInterfaceList) < 0) {
                goto cleanup;
            }

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

5037
    if (!hostScsiInterfaceList) {
5038 5039 5040 5041 5042 5043
        /* iSCSI adapter may not be enabled */
        return 0;
    }

    /* See vSphere API documentation about HostScsiTopologyInterface */
    for (hostScsiInterface = hostScsiInterfaceList;
5044
         hostScsiInterface && !found;
5045 5046
         hostScsiInterface = hostScsiInterface->_next) {
        for (hostScsiTopologyTarget = hostScsiInterface->target;
5047
             hostScsiTopologyTarget;
5048 5049
             hostScsiTopologyTarget = hostScsiTopologyTarget->_next) {
            candidate = esxVI_HostInternetScsiTargetTransport_DynamicCast
5050
                (hostScsiTopologyTarget->transport);
5051

5052
            if (candidate) {
5053 5054
                /* iterate hostScsiTopologyLun list to find matching key */
                for (hostScsiTopologyLun = hostScsiTopologyTarget->lun;
5055
                     hostScsiTopologyLun;
5056
                     hostScsiTopologyLun = hostScsiTopologyLun->_next) {
5057 5058 5059
                    if (STREQ(hostScsiTopologyLun->scsiLun, key) &&
                        VIR_STRDUP(*poolName, candidate->iScsiName) < 0)
                        goto cleanup;
5060 5061 5062 5063 5064 5065 5066 5067 5068 5069
                }

                /* hostScsiTopologyLun iteration done, terminate loop */
                break;
            }
        }
    }

    result = 0;

5070
 cleanup:
5071 5072 5073 5074 5075 5076 5077 5078
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_String_Free(&propertyNameList);
    esxVI_HostScsiTopologyInterface_Free(&hostScsiInterfaceList);

    return result;
}


5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123

#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,                 \
5124
                                 _cast_from_anytype)                          \
5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137
    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;                        \
                                                                              \
5138
        if (!ptrptr || *ptrptr) {                                             \
5139 5140
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",                      \
                           _("Invalid argument"));                            \
5141 5142 5143 5144 5145
            return -1;                                                        \
        }                                                                     \
                                                                              \
        propertyNameList = selectedPropertyNameList;                          \
                                                                              \
5146
        if (!propertyNameList &&                                              \
5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158
            esxVI_String_AppendValueListToList                                \
              (&propertyNameList, completePropertyNameValueList) < 0) {       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_LookupManagedObjectHelper(ctx, name, root, #_type,          \
                                            propertyNameList, &objectContent, \
                                            &objectContentList,               \
                                            occurrence) < 0) {                \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
5159
        if (!objectContent) {                                                 \
5160 5161 5162 5163 5164
            /* not found, exit early */                                       \
            result = 0;                                                       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
5165 5166 5167 5168 5169 5170 5171 5172 5173 5174
        if (esxVI_##_type##_Alloc(ptrptr) < 0) {                              \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_ManagedObjectReference_DeepCopy(&(*ptrptr)->_reference,     \
                                                  objectContent->obj) < 0) {  \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        for (dynamicProperty = objectContent->propSet;                        \
5175
             dynamicProperty;                                                 \
5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217
             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;

5218 5219
    if (!objectContent || *objectContent ||
        !objectContentList || *objectContentList) {
5220
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
5221 5222 5223 5224
        return -1;
    }

    if (!esxVI_String_ListContainsValue(propertyNameList, "name")) {
5225 5226
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing 'name' property in %s lookup"), type);
5227 5228 5229 5230 5231 5232 5233 5234 5235 5236
        goto cleanup;
    }

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

    /* Search for a matching item */
5237 5238
    if (name) {
        for (candidate = *objectContentList; candidate;
5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255
             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;
    }

5256
    if (!candidate) {
5257
        if (occurrence != esxVI_Occurrence_OptionalItem) {
5258
            if (name) {
5259 5260 5261 5262 5263 5264 5265
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not find %s with name '%s'"), type, name);
            } else {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not find %s"), type);
            }

5266 5267 5268 5269 5270 5271 5272 5273 5274 5275
            goto cleanup;
        }

        result = 0;

        goto cleanup;
    }

    result = 0;

5276
 cleanup:
5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288
    if (result < 0) {
        esxVI_ObjectContent_Free(objectContentList);
    } else {
        *objectContent = candidate;
    }

    return result;
}



#include "esx_vi.generated.c"