You need to sign in or sign up before continuing.
esx_vi.c 162.9 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.
M
Matthias Bolte 已提交
5
 * Copyright (C) 2009-2012 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 25 26 27
 *
 */

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_ESX

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

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



#define ESX_VI__TEMPLATE__ALLOC(_type)                                        \
    int                                                                       \
51
    esxVI_##_type##_Alloc(esxVI_##_type **ptrptr)                             \
52
    {                                                                         \
53
        if (!ptrptr || *ptrptr) {                                             \
54 55 56 57 58 59 60
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument")); \
            return -1;                                                  \
        }                                                               \
                                                                        \
        if (VIR_ALLOC(*ptrptr) < 0)                                     \
            return -1;                                                  \
        return 0;                                                       \
61 62
    }

63 64


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



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
85
 * CURL
86 87
 */

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

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

97
    if (shared) {
98 99 100 101 102 103 104
        esxVI_SharedCURL_Remove(shared, item);

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

105
    if (multi) {
M
Matthias Bolte 已提交
106 107 108 109 110 111 112
        esxVI_MultiCURL_Remove(multi, item);

        if (multi->count == 0) {
            esxVI_MultiCURL_Free(&multi);
        }
    }

113
    if (item->handle) {
114
        curl_easy_cleanup(item->handle);
115 116
    }

117
    if (item->headers) {
118
        curl_slist_free_all(item->headers);
119 120
    }

121 122
    virMutexDestroy(&item->lock);
})
123 124

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

131
    if (!content) {
M
Matthias Bolte 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        return 0;
    }

    available = strlen(content);

    if (available == 0) {
        return 0;
    }

    if (requested > available) {
        requested = available;
    }

    memcpy(data, content, requested);

147
    *(const char **)userdata = content + requested;
M
Matthias Bolte 已提交
148 149 150 151 152

    return requested;
}

static size_t
153
esxVI_CURL_WriteBuffer(char *data, size_t size, size_t nmemb, void *userdata)
154
{
155 156
    virBufferPtr buffer = userdata;

157
    if (buffer) {
158 159 160 161 162 163 164 165 166 167 168
        /*
         * 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.
         */
        if (size * nmemb > INT32_MAX / 2 - virBufferUse(buffer)) {
            return 0;
        }

        virBufferAdd(buffer, data, size * nmemb);
169 170 171 172 173 174 175 176 177 178 179

        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 已提交
180
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
181
                 char *info, size_t size, void *userdata ATTRIBUTE_UNUSED)
182
{
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    char *buffer = NULL;

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

199
    if (!virStrncpy(buffer, info, size, size + 1)) {
200 201 202 203
        VIR_FREE(buffer);
        return 0;
    }

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

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

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

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

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

      case CURLINFO_DATA_OUT:
226
        VIR_DEBUG("CURLINFO_DATA_OUT [[[[%s]]]]", buffer);
227 228 229
        break;

      default:
230
        VIR_DEBUG("unknown");
231 232 233
        break;
    }

234 235
    VIR_FREE(buffer);

236 237 238 239
    return 0;
}
#endif

240
static int
241
esxVI_CURL_Perform(esxVI_CURL *curl, const char *url)
242 243 244 245 246 247 248
{
    CURLcode errorCode;
    long responseCode = 0;
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
    const char *redirectUrl = NULL;
#endif

249
    errorCode = curl_easy_perform(curl->handle);
250 251

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

258
    errorCode = curl_easy_getinfo(curl->handle, CURLINFO_RESPONSE_CODE,
259 260 261
                                  &responseCode);

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

    if (responseCode < 0) {
270 271 272
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned a "
                         "negative response code"));
273 274 275 276 277
        return -1;
    }

    if (responseCode == 301) {
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
278
        errorCode = curl_easy_getinfo(curl->handle, CURLINFO_REDIRECT_URL,
279 280 281
                                      &redirectUrl);

        if (errorCode != CURLE_OK) {
282 283 284 285 286
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
                             "an error: %s (%d) : %s"),
                           curl_easy_strerror(errorCode),
                           errorCode, curl->error);
287
        } else {
288 289 290
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("The server redirects from '%s' to '%s'"), url,
                           redirectUrl);
291 292
        }
#else
293 294
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("The server redirects from '%s'"), url);
295 296 297 298 299 300 301 302
#endif

        return -1;
    }

    return responseCode;
}

303
int
304
esxVI_CURL_Connect(esxVI_CURL *curl, esxUtil_ParsedUri *parsedUri)
305
{
306
    if (curl->handle) {
307
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
M
Matthias Bolte 已提交
308
        return -1;
309 310
    }

311
    curl->handle = curl_easy_init();
312

313
    if (!curl->handle) {
314 315
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize CURL"));
316
        return -1;
317 318
    }

319 320
    curl->headers = curl_slist_append(curl->headers,
                                      "Content-Type: text/xml; charset=UTF-8");
321 322

    /*
323
     * Add an empty expect header to stop CURL from waiting for a response code
324 325 326 327 328 329
     * 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.
     */
330
    curl->headers = curl_slist_append(curl->headers, "Expect:");
331

332
    if (!curl->headers) {
333 334
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not build CURL header list"));
335
        return -1;
336 337
    }

338
    curl_easy_setopt(curl->handle, CURLOPT_USERAGENT, "libvirt-esx");
339
    curl_easy_setopt(curl->handle, CURLOPT_NOSIGNAL, 1);
340 341 342
    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 已提交
343
                     parsedUri->noVerify ? 0 : 1);
344
    curl_easy_setopt(curl->handle, CURLOPT_SSL_VERIFYHOST,
M
Matthias Bolte 已提交
345
                     parsedUri->noVerify ? 0 : 2);
346 347 348
    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 已提交
349
                     esxVI_CURL_ReadString);
350
    curl_easy_setopt(curl->handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
351
                     esxVI_CURL_WriteBuffer);
352
    curl_easy_setopt(curl->handle, CURLOPT_ERRORBUFFER, curl->error);
353
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
354 355
    curl_easy_setopt(curl->handle, CURLOPT_DEBUGFUNCTION, esxVI_CURL_Debug);
    curl_easy_setopt(curl->handle, CURLOPT_VERBOSE, 1);
356 357
#endif

M
Matthias Bolte 已提交
358
    if (parsedUri->proxy) {
359
        curl_easy_setopt(curl->handle, CURLOPT_PROXY,
M
Matthias Bolte 已提交
360
                         parsedUri->proxy_hostname);
361
        curl_easy_setopt(curl->handle, CURLOPT_PROXYTYPE,
M
Matthias Bolte 已提交
362
                         parsedUri->proxy_type);
363
        curl_easy_setopt(curl->handle, CURLOPT_PROXYPORT,
M
Matthias Bolte 已提交
364
                         parsedUri->proxy_port);
M
Matthias Bolte 已提交
365 366
    }

367
    if (virMutexInit(&curl->lock) < 0) {
368 369
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize CURL mutex"));
370
        return -1;
371 372
    }

373 374
    return 0;
}
375

376
int
377 378
esxVI_CURL_Download(esxVI_CURL *curl, const char *url, char **content,
                    unsigned long long offset, unsigned long long *length)
379
{
380
    char *range = NULL;
381 382 383
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    int responseCode = 0;

384
    if (!content || *content) {
385
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
386 387 388
        return -1;
    }

389
    if (length && *length > 0) {
390 391 392 393 394 395
        /*
         * 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) {
396 397
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Download length it too large"));
398 399 400
            return -1;
        }

401
        if (virAsprintf(&range, "%llu-%llu", offset, offset + *length - 1) < 0)
402 403
            goto cleanup;
    } else if (offset > 0) {
404
        if (virAsprintf(&range, "%llu-", offset) < 0)
405 406 407
            goto cleanup;
    }

408 409 410
    virMutexLock(&curl->lock);

    curl_easy_setopt(curl->handle, CURLOPT_URL, url);
411
    curl_easy_setopt(curl->handle, CURLOPT_RANGE, range);
412 413 414 415 416 417 418 419 420 421
    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;
422
    } else if (responseCode != 200 && responseCode != 206) {
423 424 425
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("HTTP response code %d for download from '%s'"),
                       responseCode, url);
426 427 428 429
        goto cleanup;
    }

    if (virBufferError(&buffer)) {
430
        virReportOOMError();
431 432 433
        goto cleanup;
    }

434
    if (length) {
435 436 437
        *length = virBufferUse(&buffer);
    }

438 439
    *content = virBufferContentAndReset(&buffer);

440
 cleanup:
441 442
    VIR_FREE(range);

443
    if (!(*content)) {
444 445 446 447 448 449 450 451 452 453 454 455
        virBufferFreeAndReset(&buffer);
        return -1;
    }

    return 0;
}

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

456
    if (!content) {
457
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
458 459 460 461 462 463
        return -1;
    }

    virMutexLock(&curl->lock);

    curl_easy_setopt(curl->handle, CURLOPT_URL, url);
464
    curl_easy_setopt(curl->handle, CURLOPT_RANGE, NULL);
465 466 467 468 469 470 471 472 473 474 475
    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) {
476 477 478
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("HTTP response code %d for upload to '%s'"),
                       responseCode, url);
479 480 481 482 483 484 485 486
        return -1;
    }

    return 0;
}



487 488 489 490 491 492 493 494
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * SharedCURL
 */

static void
esxVI_SharedCURL_Lock(CURL *handle ATTRIBUTE_UNUSED, curl_lock_data data,
                      curl_lock_access access_ ATTRIBUTE_UNUSED, void *userptr)
{
495
    size_t i;
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    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)
{
523
    size_t i;
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    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,
{
553
    size_t i;
554 555 556

    if (item->count > 0) {
        /* Better leak than crash */
557
        VIR_ERROR(_("Trying to free SharedCURL object that is still in use"));
558 559 560
        return;
    }

561
    if (item->handle) {
562 563 564 565 566 567 568 569 570 571 572
        curl_share_cleanup(item->handle);
    }

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

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

575
    if (!curl->handle) {
576 577
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot share uninitialized CURL handle"));
578 579 580
        return -1;
    }

581
    if (curl->shared) {
582 583
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot share CURL handle that is already shared"));
584 585 586
        return -1;
    }

587
    if (!shared->handle) {
588 589
        shared->handle = curl_share_init();

590
        if (!shared->handle) {
591 592
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not initialize CURL (share)"));
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
            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) {
608 609
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Could not initialize a CURL (share) mutex"));
610 611 612 613 614
                return -1;
            }
        }
    }

M
Matthias Bolte 已提交
615 616
    virMutexLock(&curl->lock);

617 618 619 620 621
    curl_easy_setopt(curl->handle, CURLOPT_SHARE, shared->handle);

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

M
Matthias Bolte 已提交
622 623
    virMutexUnlock(&curl->lock);

624 625 626 627 628 629
    return 0;
}

int
esxVI_SharedCURL_Remove(esxVI_SharedCURL *shared, esxVI_CURL *curl)
{
630
    if (!curl->handle) {
631 632
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot unshare uninitialized CURL handle"));
633 634 635
        return -1;
    }

636
    if (!curl->shared) {
637 638
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot unshare CURL handle that is not shared"));
639 640 641 642
        return -1;
    }

    if (curl->shared != shared) {
643
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("CURL (share) mismatch"));
644 645 646
        return -1;
    }

M
Matthias Bolte 已提交
647 648
    virMutexLock(&curl->lock);

649 650 651 652 653
    curl_easy_setopt(curl->handle, CURLOPT_SHARE, NULL);

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

M
Matthias Bolte 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    virMutexUnlock(&curl->lock);

    return 0;
}



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

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

677
    if (item->handle) {
M
Matthias Bolte 已提交
678 679 680 681 682 683 684
        curl_multi_cleanup(item->handle);
    }
})

int
esxVI_MultiCURL_Add(esxVI_MultiCURL *multi, esxVI_CURL *curl)
{
685
    if (!curl->handle) {
686 687
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot add uninitialized CURL handle to a multi handle"));
M
Matthias Bolte 已提交
688 689 690
        return -1;
    }

691
    if (curl->multi) {
692 693
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot add CURL handle to a multi handle twice"));
M
Matthias Bolte 已提交
694 695 696
        return -1;
    }

697
    if (!multi->handle) {
M
Matthias Bolte 已提交
698 699
        multi->handle = curl_multi_init();

700
        if (!multi->handle) {
701 702
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not initialize CURL (multi)"));
M
Matthias Bolte 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
            return -1;
        }
    }

    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)
{
722
    if (!curl->handle) {
723 724 725
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot remove uninitialized CURL handle from a "
                         "multi handle"));
M
Matthias Bolte 已提交
726 727 728
        return -1;
    }

729
    if (!curl->multi) {
730 731 732
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot remove CURL handle from a multi handle when it "
                         "wasn't added before"));
M
Matthias Bolte 已提交
733 734 735 736
        return -1;
    }

    if (curl->multi != multi) {
737
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("CURL (multi) mismatch"));
M
Matthias Bolte 已提交
738 739 740 741 742 743 744 745 746 747 748 749
        return -1;
    }

    virMutexLock(&curl->lock);

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

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

    virMutexUnlock(&curl->lock);

750 751 752 753 754
    return 0;
}



755 756 757 758 759 760 761 762 763 764
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Context
 */

/* esxVI_Context_Alloc */
ESX_VI__TEMPLATE__ALLOC(Context)

/* esxVI_Context_Free */
ESX_VI__TEMPLATE__FREE(Context,
{
765
    if (item->sessionLock) {
766 767 768
        virMutexDestroy(item->sessionLock);
    }

769 770 771 772 773 774 775
    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);
776
    VIR_FREE(item->sessionLock);
777
    esxVI_Datacenter_Free(&item->datacenter);
778
    VIR_FREE(item->datacenterPath);
779
    esxVI_ComputeResource_Free(&item->computeResource);
780
    VIR_FREE(item->computeResourcePath);
781
    esxVI_HostSystem_Free(&item->hostSystem);
782
    VIR_FREE(item->hostSystemName);
783 784 785 786 787 788
    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 已提交
789
    esxVI_SelectionSpec_Free(&item->selectSet_datacenterToNetwork);
790 791 792 793 794 795 796
})

int
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
                      const char *ipAddress, const char *username,
                      const char *password, esxUtil_ParsedUri *parsedUri)
{
797 798
    if (!ctx || !url || !ipAddress || !username ||
        !password || ctx->url || ctx->service || ctx->curl) {
799
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
800 801 802 803 804
        return -1;
    }

    if (esxVI_CURL_Alloc(&ctx->curl) < 0 ||
        esxVI_CURL_Connect(ctx->curl, parsedUri) < 0 ||
805 806 807 808
        VIR_STRDUP(ctx->url, url) < 0 ||
        VIR_STRDUP(ctx->ipAddress, ipAddress) < 0 ||
        VIR_STRDUP(ctx->username, username) < 0 ||
        VIR_STRDUP(ctx->password, password) < 0) {
809
        return -1;
810 811
    }

812
    if (VIR_ALLOC(ctx->sessionLock) < 0)
813 814 815
        return -1;

    if (virMutexInit(ctx->sessionLock) < 0) {
816 817
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize session mutex"));
818 819 820
        return -1;
    }

821
    if (esxVI_RetrieveServiceContent(ctx, &ctx->service) < 0) {
822
        return -1;
823 824
    }

825 826 827
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
828
            ctx->apiVersion = esxVI_APIVersion_25;
829
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
830
            ctx->apiVersion = esxVI_APIVersion_40;
M
Matthias Bolte 已提交
831 832 833 834
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.1")) {
            ctx->apiVersion = esxVI_APIVersion_41;
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.")) {
            ctx->apiVersion = esxVI_APIVersion_4x;
P
Patrice LACHANCE 已提交
835 836
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.0")) {
            ctx->apiVersion = esxVI_APIVersion_50;
837 838
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.1")) {
            ctx->apiVersion = esxVI_APIVersion_51;
P
Patrice LACHANCE 已提交
839 840
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.")) {
            ctx->apiVersion = esxVI_APIVersion_5x;
841
        } else {
842 843 844
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Expecting VI API major/minor version '2.5', '4.x' or "
                             "'5.x' but found '%s'"), ctx->service->about->apiVersion);
845
            return -1;
846
        }
847

848 849 850 851
        if (STREQ(ctx->service->about->productLineId, "gsx")) {
            if (STRPREFIX(ctx->service->about->version, "2.0")) {
                ctx->productVersion = esxVI_ProductVersion_GSX20;
            } else {
852 853 854
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Expecting GSX major/minor version '2.0' but "
                                 "found '%s'"), ctx->service->about->version);
855
                return -1;
856 857 858 859 860 861 862
            }
        } else if (STREQ(ctx->service->about->productLineId, "esx") ||
                   STREQ(ctx->service->about->productLineId, "embeddedEsx")) {
            if (STRPREFIX(ctx->service->about->version, "3.5")) {
                ctx->productVersion = esxVI_ProductVersion_ESX35;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_ESX40;
M
Matthias Bolte 已提交
863 864 865 866
            } else if (STRPREFIX(ctx->service->about->version, "4.1")) {
                ctx->productVersion = esxVI_ProductVersion_ESX41;
            } else if (STRPREFIX(ctx->service->about->version, "4.")) {
                ctx->productVersion = esxVI_ProductVersion_ESX4x;
P
Patrice LACHANCE 已提交
867 868
            } else if (STRPREFIX(ctx->service->about->version, "5.0")) {
                ctx->productVersion = esxVI_ProductVersion_ESX50;
869 870
            } else if (STRPREFIX(ctx->service->about->version, "5.1")) {
                ctx->productVersion = esxVI_ProductVersion_ESX51;
P
Patrice LACHANCE 已提交
871 872
            } else if (STRPREFIX(ctx->service->about->version, "5.")) {
                ctx->productVersion = esxVI_ProductVersion_ESX5x;
873
            } else {
874 875 876 877
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Expecting ESX major/minor version '3.5', "
                                 "'4.x' or '5.x' but found '%s'"),
                               ctx->service->about->version);
878
                return -1;
879 880 881 882 883 884
            }
        } else if (STREQ(ctx->service->about->productLineId, "vpx")) {
            if (STRPREFIX(ctx->service->about->version, "2.5")) {
                ctx->productVersion = esxVI_ProductVersion_VPX25;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_VPX40;
M
Matthias Bolte 已提交
885 886 887 888
            } else if (STRPREFIX(ctx->service->about->version, "4.1")) {
                ctx->productVersion = esxVI_ProductVersion_VPX41;
            } else if (STRPREFIX(ctx->service->about->version, "4.")) {
                ctx->productVersion = esxVI_ProductVersion_VPX4x;
P
Patrice LACHANCE 已提交
889 890
            } else if (STRPREFIX(ctx->service->about->version, "5.0")) {
                ctx->productVersion = esxVI_ProductVersion_VPX50;
891 892
            } else if (STRPREFIX(ctx->service->about->version, "5.1")) {
                ctx->productVersion = esxVI_ProductVersion_VPX51;
P
Patrice LACHANCE 已提交
893 894
            } else if (STRPREFIX(ctx->service->about->version, "5.")) {
                ctx->productVersion = esxVI_ProductVersion_VPX5x;
895
            } else {
896 897 898
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Expecting VPX major/minor version '2.5', '4.x' "
                                 "or '5.x' but found '%s'"),
P
Patrice LACHANCE 已提交
899
                               ctx->service->about->version);
900
                return -1;
901
            }
902
        } else {
903 904 905 906
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                             "or 'vpx' but found '%s'"),
                           ctx->service->about->productLineId);
907
            return -1;
908 909
        }
    } else {
910 911 912
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                         "but found '%s'"), ctx->service->about->apiType);
913
        return -1;
914 915
    }

916 917 918 919 920 921 922 923 924 925 926
    if (ctx->productVersion & esxVI_ProductVersion_ESX) {
        /*
         * FIXME: Actually this should be detected by really calling
         * QueryVirtualDiskUuid and checking if a NotImplemented fault is
         * returned. But currently we don't deserialized the details of a
         * possbile fault and therefore we don't know if the fault was a
         * NotImplemented fault or not.
         */
        ctx->hasQueryVirtualDiskUuid = true;
    }

927 928 929 930
    if (ctx->productVersion & esxVI_ProductVersion_VPX) {
        ctx->hasSessionIsActive = true;
    }

931
    if (esxVI_Login(ctx, username, password, NULL, &ctx->session) < 0 ||
932
        esxVI_BuildSelectSetCollection(ctx) < 0) {
933
        return -1;
934 935
    }

936 937 938 939
    return 0;
}

int
940
esxVI_Context_LookupManagedObjects(esxVI_Context *ctx)
941 942
{
    /* Lookup Datacenter */
943 944
    if (esxVI_LookupDatacenter(ctx, NULL, ctx->service->rootFolder, NULL,
                               &ctx->datacenter,
945 946
                               esxVI_Occurrence_RequiredItem) < 0) {
        return -1;
947 948
    }

949
    if (VIR_STRDUP(ctx->datacenterPath, ctx->datacenter->name) < 0)
950 951
        return -1;

952
    /* Lookup (Cluster)ComputeResource */
953 954
    if (esxVI_LookupComputeResource(ctx, NULL, ctx->datacenter->hostFolder,
                                    NULL, &ctx->computeResource,
955 956
                                    esxVI_Occurrence_RequiredItem) < 0) {
        return -1;
957 958
    }

959
    if (!ctx->computeResource->resourcePool) {
960 961
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve resource pool"));
962
        return -1;
963 964
    }

965
    if (VIR_STRDUP(ctx->computeResourcePath, ctx->computeResource->name) < 0)
966 967
        return -1;

968
    /* Lookup HostSystem */
969 970 971
    if (esxVI_LookupHostSystem(ctx, NULL, ctx->computeResource->_reference,
                               NULL, &ctx->hostSystem,
                               esxVI_Occurrence_RequiredItem) < 0) {
972
        return -1;
973 974
    }

975
    if (VIR_STRDUP(ctx->hostSystemName, ctx->hostSystem->name) < 0)
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
        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;

993
    if (VIR_STRDUP(tmp, path) < 0)
994 995 996 997 998
        goto cleanup;

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

999
    if (!item) {
1000 1001
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' does not specify a datacenter"), path);
1002 1003 1004 1005 1006
        goto cleanup;
    }

    root = ctx->service->rootFolder;

1007
    while (!ctx->datacenter && item) {
1008 1009 1010 1011 1012 1013 1014 1015
        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;
        }

1016
        if (folder) {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
            /* It's a folder, use it as new lookup root */
            if (root != ctx->service->rootFolder) {
                esxVI_ManagedObjectReference_Free(&root);
            }

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

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

        virBufferAdd(&buffer, item, -1);

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

1043
    if (!ctx->datacenter) {
1044 1045
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datacenter specified in '%s'"), path);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
        goto cleanup;
    }

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

    ctx->datacenterPath = virBufferContentAndReset(&buffer);

    /* Lookup (Cluster)ComputeResource */
1057
    if (!item) {
1058 1059
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' does not specify a compute resource"), path);
1060 1061 1062 1063 1064 1065 1066 1067 1068
        goto cleanup;
    }

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

    root = ctx->datacenter->hostFolder;

1069
    while (!ctx->computeResource && item) {
1070 1071 1072 1073 1074 1075 1076 1077
        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;
        }

1078
        if (folder) {
1079 1080 1081 1082 1083 1084 1085
            /* It's a folder, use it as new lookup root */
            if (root != ctx->datacenter->hostFolder) {
                esxVI_ManagedObjectReference_Free(&root);
            }

            root = folder->_reference;
            folder->_reference = NULL;
1086
        } else {
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
            /* Try to lookup item as a compute resource */
            if (esxVI_LookupComputeResource(ctx, item, root, NULL,
                                            &ctx->computeResource,
                                            esxVI_Occurrence_OptionalItem) < 0) {
                goto cleanup;
            }
        }

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

        virBufferAdd(&buffer, item, -1);

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

1106
    if (!ctx->computeResource) {
1107 1108 1109
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find compute resource specified in '%s'"),
                       path);
1110 1111 1112
        goto cleanup;
    }

1113
    if (!ctx->computeResource->resourcePool) {
1114 1115
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve resource pool"));
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
        goto cleanup;
    }

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

    ctx->computeResourcePath = virBufferContentAndReset(&buffer);

    /* Lookup HostSystem */
    if (STREQ(ctx->computeResource->_reference->type,
              "ClusterComputeResource")) {
1129
        if (!item) {
1130 1131
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Path '%s' does not specify a host system"), path);
1132
            goto cleanup;
1133
        }
1134 1135 1136 1137 1138 1139

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

1140
    if (item) {
1141 1142
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' ends with an excess item"), path);
1143
        goto cleanup;
1144 1145
    }

1146
    if (VIR_STRDUP(ctx->hostSystemName, previousItem) < 0)
1147 1148 1149
        goto cleanup;

    if (esxVI_LookupHostSystem(ctx, ctx->hostSystemName,
1150 1151
                               ctx->computeResource->_reference, NULL,
                               &ctx->hostSystem,
1152 1153
                               esxVI_Occurrence_OptionalItem) < 0) {
        goto cleanup;
1154 1155
    }

1156
    if (!ctx->hostSystem) {
1157 1158
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find host system specified in '%s'"), path);
1159 1160 1161 1162 1163
        goto cleanup;
    }

    result = 0;

1164
 cleanup:
1165 1166 1167 1168 1169
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

    if (root != ctx->service->rootFolder &&
1170
        (!ctx->datacenter || root != ctx->datacenter->hostFolder)) {
1171 1172 1173 1174 1175 1176 1177
        esxVI_ManagedObjectReference_Free(&root);
    }

    VIR_FREE(tmp);
    esxVI_Folder_Free(&folder);

    return result;
1178 1179 1180
}

int
1181 1182
esxVI_Context_LookupManagedObjectsByHostSystemIp(esxVI_Context *ctx,
                                                 const char *hostSystemIpAddress)
1183 1184 1185 1186 1187
{
    int result = -1;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;

    /* Lookup HostSystem */
1188
    if (esxVI_FindByIp(ctx, NULL, hostSystemIpAddress, esxVI_Boolean_False,
1189
                       &managedObjectReference) < 0 ||
1190 1191 1192
        esxVI_LookupHostSystem(ctx, NULL, managedObjectReference, NULL,
                               &ctx->hostSystem,
                               esxVI_Occurrence_RequiredItem) < 0) {
1193 1194 1195
        goto cleanup;
    }

1196
    /* Lookup (Cluster)ComputeResource */
1197 1198 1199 1200 1201
    if (esxVI_LookupComputeResource(ctx, NULL, ctx->hostSystem->_reference,
                                    NULL, &ctx->computeResource,
                                    esxVI_Occurrence_RequiredItem) < 0) {
        goto cleanup;
    }
1202

1203
    if (!ctx->computeResource->resourcePool) {
1204 1205
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve resource pool"));
1206 1207 1208 1209
        goto cleanup;
    }

    /* Lookup Datacenter */
1210 1211 1212
    if (esxVI_LookupDatacenter(ctx, NULL, ctx->computeResource->_reference,
                               NULL, &ctx->datacenter,
                               esxVI_Occurrence_RequiredItem) < 0) {
1213 1214 1215 1216 1217
        goto cleanup;
    }

    result = 0;

1218
 cleanup:
1219
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
1220 1221 1222 1223 1224

    return result;
}

int
1225 1226 1227
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
1228
{
M
Matthias Bolte 已提交
1229
    int result = -1;
1230 1231
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
1232 1233 1234
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
1235

1236
    if (!request || !response || *response) {
1237
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1238
        return -1;
1239 1240
    }

1241
    if (esxVI_Response_Alloc(response) < 0) {
M
Matthias Bolte 已提交
1242
        return -1;
1243 1244
    }

1245
    virMutexLock(&ctx->curl->lock);
1246

1247
    curl_easy_setopt(ctx->curl->handle, CURLOPT_URL, ctx->url);
1248
    curl_easy_setopt(ctx->curl->handle, CURLOPT_RANGE, NULL);
1249 1250 1251 1252
    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));
1253

1254
    (*response)->responseCode = esxVI_CURL_Perform(ctx->curl, ctx->url);
1255

1256
    virMutexUnlock(&ctx->curl->lock);
1257

1258
    if ((*response)->responseCode < 0) {
M
Matthias Bolte 已提交
1259
        goto cleanup;
1260 1261 1262
    }

    if (virBufferError(&buffer)) {
1263
        virReportOOMError();
M
Matthias Bolte 已提交
1264
        goto cleanup;
1265 1266
    }

1267
    (*response)->content = virBufferContentAndReset(&buffer);
1268

1269
    if ((*response)->responseCode == 500 || (*response)->responseCode == 200) {
1270
        (*response)->document = virXMLParseStringCtxt((*response)->content,
1271
                                                      _("(esx execute response)"),
1272
                                                      &xpathContext);
1273

1274
        if (!(*response)->document) {
M
Matthias Bolte 已提交
1275
            goto cleanup;
1276 1277
        }

1278
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
1279
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
1280
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
1281

1282 1283
        if ((*response)->responseCode == 500) {
            (*response)->node =
1284
              virXPathNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault",
1285
                           xpathContext);
1286

1287
            if (!(*response)->node) {
1288 1289 1290 1291
                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 已提交
1292
                goto cleanup;
1293 1294
            }

1295
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
1296 1297 1298 1299
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("HTTP response code %d for call to '%s'. "
                                 "Fault is unknown, deserialization failed"),
                               (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1300
                goto cleanup;
1301 1302
            }

1303 1304 1305 1306
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("HTTP response code %d for call to '%s'. "
                             "Fault: %s - %s"), (*response)->responseCode,
                           methodName, fault->faultcode, fault->faultstring);
1307 1308 1309 1310 1311 1312

            /* 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 已提交
1313
            goto cleanup;
1314 1315 1316
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
1317
                            methodName) < 0)
M
Matthias Bolte 已提交
1318
                goto cleanup;
1319

1320
            responseNode = virXPathNode(xpathExpression, xpathContext);
1321

1322
            if (!responseNode) {
1323 1324 1325
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("XPath evaluation of response for call to '%s' "
                                 "failed"), methodName);
M
Matthias Bolte 已提交
1326
                goto cleanup;
1327 1328
            }

1329
            xpathContext->node = responseNode;
1330
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
1331

1332 1333
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
1334
                if (!(*response)->node) {
1335 1336 1337
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned an empty result, "
                                     "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
1338
                    goto cleanup;
1339
                } else if ((*response)->node->next) {
1340 1341 1342
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned a list, expecting "
                                     "exactly one item"), methodName);
M
Matthias Bolte 已提交
1343
                    goto cleanup;
1344 1345 1346 1347 1348
                }

                break;

              case esxVI_Occurrence_RequiredList:
1349
                if (!(*response)->node) {
1350 1351 1352
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned an empty result, "
                                     "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
1353
                    goto cleanup;
1354 1355 1356 1357 1358
                }

                break;

              case esxVI_Occurrence_OptionalItem:
1359 1360
                if ((*response)->node &&
                    (*response)->node->next) {
1361 1362 1363
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned a list, expecting "
                                     "exactly one item"), methodName);
M
Matthias Bolte 已提交
1364
                    goto cleanup;
1365 1366 1367 1368
                }

                break;

1369
              case esxVI_Occurrence_OptionalList:
1370 1371 1372 1373
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
1374
                if ((*response)->node) {
1375 1376 1377
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Call to '%s' returned something, expecting "
                                     "an empty result"), methodName);
M
Matthias Bolte 已提交
1378
                    goto cleanup;
1379 1380 1381 1382 1383
                }

                break;

              default:
1384 1385
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Invalid argument (occurrence)"));
M
Matthias Bolte 已提交
1386
                goto cleanup;
1387
            }
1388
        }
1389
    } else {
1390 1391 1392
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("HTTP response code %d for call to '%s'"),
                       (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
1393
        goto cleanup;
1394 1395
    }

M
Matthias Bolte 已提交
1396 1397
    result = 0;

1398
 cleanup:
M
Matthias Bolte 已提交
1399 1400 1401 1402 1403 1404
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
        esxVI_Response_Free(response);
        esxVI_Fault_Free(&fault);
    }

1405 1406 1407 1408
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
1409 1410 1411 1412 1413
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1414
 * Response
1415 1416
 */

1417
/* esxVI_Response_Alloc */
1418
ESX_VI__TEMPLATE__ALLOC(Response)
1419

1420 1421
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
1422
{
1423
    VIR_FREE(item->content);
1424

1425
    xmlFreeDoc(item->document);
1426
})
1427 1428 1429 1430 1431 1432 1433 1434



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

int
1435
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
1436 1437
                                  esxVI_AnyType *anyType, int *value)
{
1438
    size_t i;
1439

1440
    if (!anyType || !value) {
1441
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1442 1443 1444 1445 1446
        return -1;
    }

    *value = 0; /* undefined */

1447
    if (anyType->type != enumeration->type) {
1448 1449 1450
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting type '%s' but found '%s'"),
                       esxVI_Type_ToString(enumeration->type),
1451
                       esxVI_AnyType_TypeToString(anyType));
1452 1453 1454
        return -1;
    }

1455
    for (i = 0; enumeration->values[i].name; ++i) {
1456 1457 1458 1459 1460 1461
        if (STREQ(anyType->value, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
            return 0;
        }
    }

1462 1463 1464
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Unknown value '%s' for %s"), anyType->value,
                   esxVI_Type_ToString(enumeration->type));
1465 1466 1467 1468 1469

    return -1;
}

int
1470
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
1471
                            int value, const char *element, virBufferPtr output)
1472
{
1473
    size_t i;
1474 1475
    const char *name = NULL;

1476
    if (!element || !output) {
1477
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1478 1479 1480 1481
        return -1;
    }

    if (value == 0) { /* undefined */
1482
        return 0;
1483 1484
    }

1485
    for (i = 0; enumeration->values[i].name; ++i) {
1486 1487 1488 1489 1490 1491
        if (value == enumeration->values[i].value) {
            name = enumeration->values[i].name;
            break;
        }
    }

1492
    if (!name) {
1493
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1494 1495 1496
        return -1;
    }

1497 1498
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
1499 1500 1501 1502 1503 1504 1505 1506 1507

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
1508
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
1509 1510
                              xmlNodePtr node, int *value)
{
1511
    size_t i;
M
Matthias Bolte 已提交
1512
    int result = -1;
1513 1514
    char *name = NULL;

1515
    if (!value) {
1516
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1517
        return -1;
1518 1519 1520 1521
    }

    *value = 0; /* undefined */

1522
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
M
Matthias Bolte 已提交
1523
        return -1;
1524 1525
    }

1526
    for (i = 0; enumeration->values[i].name; ++i) {
1527 1528
        if (STREQ(name, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
M
Matthias Bolte 已提交
1529 1530
            result = 0;
            break;
1531 1532 1533
        }
    }

M
Matthias Bolte 已提交
1534
    if (result < 0) {
1535 1536
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Unknown value '%s' for %s"),
                       name, esxVI_Type_ToString(enumeration->type));
M
Matthias Bolte 已提交
1537
    }
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550

    VIR_FREE(name);

    return result;
}



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

int
1551
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
1552 1553 1554
{
    esxVI_List *next = NULL;

1555
    if (!list || !item) {
1556
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1557 1558 1559
        return -1;
    }

1560
    if (!(*list)) {
1561 1562 1563 1564 1565 1566
        *list = item;
        return 0;
    }

    next = *list;

1567
    while (next->_next) {
1568 1569 1570 1571 1572 1573 1574 1575 1576
        next = next->_next;
    }

    next->_next = item;

    return 0;
}

int
1577
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
1578 1579 1580 1581 1582 1583
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

1584
    if (!destList || *destList) {
1585
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1586
        return -1;
1587 1588
    }

1589
    for (src = srcList; src; src = src->_next) {
1590 1591
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
1592 1593 1594 1595 1596 1597 1598 1599
            goto failure;
        }

        dest = NULL;
    }

    return 0;

1600
 failure:
1601 1602 1603 1604 1605 1606
    freeFunc(&dest);
    freeFunc(destList);

    return -1;
}

1607
int
1608
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
1609 1610 1611
                           esxVI_List_CastFromAnyTypeFunc castFromAnyTypeFunc,
                           esxVI_List_FreeFunc freeFunc)
{
M
Matthias Bolte 已提交
1612
    int result = -1;
1613 1614 1615 1616
    xmlNodePtr childNode = NULL;
    esxVI_AnyType *childAnyType = NULL;
    esxVI_List *item = NULL;

1617
    if (!list || *list || !castFromAnyTypeFunc || !freeFunc) {
1618
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1619
        return -1;
1620 1621
    }

1622
    if (!anyType) {
1623 1624 1625 1626
        return 0;
    }

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
1627 1628 1629
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting type to begin with 'ArrayOf' but found '%s'"),
                       anyType->other);
1630
        return -1;
1631 1632
    }

1633
    for (childNode = anyType->node->children; childNode;
1634 1635
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1636 1637
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Wrong XML element type %d"), childNode->type);
M
Matthias Bolte 已提交
1638
            goto cleanup;
1639 1640 1641 1642
        }

        esxVI_AnyType_Free(&childAnyType);

1643 1644 1645
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
M
Matthias Bolte 已提交
1646
            goto cleanup;
1647 1648 1649 1650 1651
        }

        item = NULL;
    }

M
Matthias Bolte 已提交
1652 1653
    result = 0;

1654
 cleanup:
M
Matthias Bolte 已提交
1655 1656 1657 1658 1659
    if (result < 0) {
        freeFunc(&item);
        freeFunc(list);
    }

1660 1661 1662 1663 1664
    esxVI_AnyType_Free(&childAnyType);

    return result;
}

1665
int
1666
esxVI_List_Serialize(esxVI_List *list, const char *element,
1667
                     virBufferPtr output,
1668 1669 1670 1671
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

1672
    if (!element || !output || !serializeFunc) {
1673
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1674 1675 1676
        return -1;
    }

1677
    if (!list) {
1678
        return 0;
1679 1680
    }

1681
    for (item = list; item; item = item->_next) {
1682
        if (serializeFunc(item, element, output) < 0) {
1683 1684 1685 1686 1687 1688 1689 1690
            return -1;
        }
    }

    return 0;
}

int
1691
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1692 1693 1694 1695 1696
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

1697
    if (!list || *list || !deserializeFunc || !freeFunc) {
1698
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1699 1700 1701
        return -1;
    }

1702
    if (!node) {
1703 1704 1705
        return 0;
    }

1706
    for (; node; node = node->next) {
1707
        if (node->type != XML_ELEMENT_NODE) {
1708 1709
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Wrong XML element type %d"), node->type);
1710 1711 1712
            goto failure;
        }

1713 1714
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1715 1716 1717
            goto failure;
        }

1718
        item = NULL;
1719 1720 1721 1722
    }

    return 0;

1723
 failure:
1724
    freeFunc(&item);
1725 1726 1727 1728 1729 1730 1731 1732 1733
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1734 1735 1736 1737
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1738 1739 1740
 */

int
1741 1742 1743
esxVI_BuildSelectSet(esxVI_SelectionSpec **selectSet,
                     const char *name, const char *type,
                     const char *path, const char *selectSetNames)
1744 1745 1746 1747 1748
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

1749
    if (!selectSet) {
1750 1751 1752 1753
        /*
         * Don't check for *selectSet != NULL here because selectSet is a list
         * and might contain items already. This function appends to selectSet.
         */
1754
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1755 1756 1757
        return -1;
    }

1758
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1759 1760 1761
        VIR_STRDUP(traversalSpec->name, name) < 0 ||
        VIR_STRDUP(traversalSpec->type, type) < 0 ||
        VIR_STRDUP(traversalSpec->path, path) < 0) {
1762 1763 1764 1765 1766
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

1767
    if (selectSetNames) {
1768 1769
        currentSelectSetName = selectSetNames;

1770
        while (currentSelectSetName && *currentSelectSetName != '\0') {
1771
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
1772
                VIR_STRDUP(selectionSpec->name, currentSelectSetName) < 0 ||
1773
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1774 1775 1776 1777
                                                 selectionSpec) < 0) {
                goto failure;
            }

1778
            selectionSpec = NULL;
1779 1780 1781 1782
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1783
    if (esxVI_SelectionSpec_AppendToList(selectSet,
1784 1785
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1786 1787 1788 1789 1790
        goto failure;
    }

    return 0;

1791
 failure:
1792
    esxVI_TraversalSpec_Free(&traversalSpec);
1793
    esxVI_SelectionSpec_Free(&selectionSpec);
1794 1795 1796 1797 1798

    return -1;
}


1799

1800
int
1801
esxVI_BuildSelectSetCollection(esxVI_Context *ctx)
1802
{
1803
    /* Folder -> childEntity (ManagedEntity) */
1804 1805
    if (esxVI_BuildSelectSet(&ctx->selectSet_folderToChildEntity,
                             "folderToChildEntity",
1806
                             "Folder", "childEntity", NULL) < 0) {
1807
        return -1;
1808 1809
    }

1810
    /* ComputeResource -> host (HostSystem) */
1811 1812 1813 1814
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToHost,
                             "computeResourceToHost",
                             "ComputeResource", "host", NULL) < 0) {
        return -1;
1815 1816
    }

1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
    /* 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;
    }*/
1832

1833 1834 1835 1836 1837 1838
    /* ResourcePool -> vm (VirtualMachine) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_resourcePoolToVm,
                             "resourcePoolToVm",
                             "ResourcePool", "vm", NULL) < 0) {
        return -1;
    }*/
1839

1840
    /* HostSystem -> parent (ComputeResource) */
1841 1842 1843 1844
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToParent,
                             "hostSystemToParent",
                             "HostSystem", "parent", NULL) < 0) {
        return -1;
1845 1846
    }

1847
    /* HostSystem -> vm (VirtualMachine) */
1848 1849 1850 1851
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToVm,
                             "hostSystemToVm",
                             "HostSystem", "vm", NULL) < 0) {
        return -1;
1852 1853
    }

1854
    /* HostSystem -> datastore (Datastore) */
1855 1856 1857 1858
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToDatastore,
                             "hostSystemToDatastore",
                             "HostSystem", "datastore", NULL) < 0) {
        return -1;
1859 1860
    }

1861 1862 1863 1864 1865 1866
    /* Folder -> parent (Folder, Datacenter) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "managedEntityToParent",
                             "ManagedEntity", "parent", NULL) < 0) {
        return -1;
    }
1867

1868 1869 1870 1871 1872 1873 1874
    /* ComputeResource -> parent (Folder) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "computeResourceToParent",
                             "ComputeResource", "parent",
                             "managedEntityToParent\0") < 0) {
        return -1;
    }
1875

M
Matthias Bolte 已提交
1876 1877 1878 1879 1880 1881 1882
    /* Datacenter -> network (Network) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_datacenterToNetwork,
                             "datacenterToNetwork",
                             "Datacenter", "network", NULL) < 0) {
        return -1;
    }

1883
    return 0;
1884 1885 1886 1887 1888
}



int
1889
esxVI_EnsureSession(esxVI_Context *ctx)
1890
{
M
Matthias Bolte 已提交
1891
    int result = -1;
1892
    esxVI_Boolean active = esxVI_Boolean_Undefined;
1893 1894 1895 1896 1897
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;

1898
    if (!ctx->sessionLock) {
1899
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no mutex"));
1900 1901 1902
        return -1;
    }

1903 1904
    virMutexLock(ctx->sessionLock);

1905
    if (!ctx->session) {
1906
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no session"));
1907 1908 1909
        goto cleanup;
    }

1910 1911 1912
    if (ctx->hasSessionIsActive) {
        /*
         * Use SessionIsActive to check if there is an active session for this
E
Eric Blake 已提交
1913
         * connection, and re-login if there isn't.
1914 1915 1916
         */
        if (esxVI_SessionIsActive(ctx, ctx->session->key,
                                  ctx->session->userName, &active) < 0) {
1917
            goto cleanup;
1918
        }
1919

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

1923 1924
            if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                            &ctx->session) < 0) {
1925
                goto cleanup;
1926
            }
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
        }
    } 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,
1937 1938
                                            &sessionManager,
                                            esxVI_Occurrence_RequiredItem) < 0) {
1939
            goto cleanup;
1940 1941
        }

1942
        for (dynamicProperty = sessionManager->propSet; dynamicProperty;
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
             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);
            }
        }
1955

1956
        if (!currentSession) {
1957 1958 1959 1960 1961 1962 1963
            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)) {
1964 1965 1966
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Key of the current session differs from the key at "
                             "last login"));
M
Matthias Bolte 已提交
1967
            goto cleanup;
1968
        }
1969
    }
1970

1971
    result = 0;
M
Matthias Bolte 已提交
1972

1973
 cleanup:
1974
    virMutexUnlock(ctx->sessionLock);
1975

1976 1977 1978 1979 1980
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);

    return result;
1981 1982 1983 1984 1985
}



int
1986
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
1987 1988 1989
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
1990 1991
                                esxVI_ObjectContent **objectContentList,
                                esxVI_Occurrence occurrence)
1992
{
M
Matthias Bolte 已提交
1993
    int result = -1;
1994
    esxVI_ObjectSpec *objectSpec = NULL;
1995
    bool objectSpec_isAppended = false;
1996
    esxVI_PropertySpec *propertySpec = NULL;
1997
    bool propertySpec_isAppended = false;
1998 1999
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

2000
    if (!objectContentList || *objectContentList) {
2001
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2002 2003 2004
        return -1;
    }

2005
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
2006
        return -1;
2007 2008 2009 2010 2011
    }

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

2012
    if (STRNEQ(root->type, type) || STREQ(root->type, "Folder")) {
2013
        if (STREQ(root->type, "Folder")) {
2014 2015
            if (STREQ(type, "Folder") || STREQ(type, "Datacenter") ||
                STREQ(type, "ComputeResource") ||
2016
                STREQ(type, "ClusterComputeResource")) {
2017 2018
                objectSpec->selectSet = ctx->selectSet_folderToChildEntity;
            } else {
2019 2020 2021
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2022 2023
                goto cleanup;
            }
2024 2025
        } else if (STREQ(root->type, "ComputeResource") ||
                   STREQ(root->type, "ClusterComputeResource")) {
2026 2027 2028 2029 2030
            if (STREQ(type, "HostSystem")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToHost;
            } else if (STREQ(type, "Datacenter")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToParentToParent;
            } else {
2031 2032 2033
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2034 2035 2036
                goto cleanup;
            }
        } else if (STREQ(root->type, "HostSystem")) {
2037 2038
            if (STREQ(type, "ComputeResource") ||
                STREQ(type, "ClusterComputeResource")) {
2039 2040 2041 2042 2043 2044
                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 {
2045 2046 2047
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2048 2049
                goto cleanup;
            }
M
Matthias Bolte 已提交
2050 2051 2052 2053 2054 2055 2056 2057 2058
        } 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;
            }
2059
        } else {
2060 2061
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid lookup from '%s'"), root->type);
2062 2063
            goto cleanup;
        }
2064 2065
    }

2066
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
2067
        goto cleanup;
2068 2069 2070 2071 2072
    }

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

2073 2074
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
                                        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,
2089 2090 2091 2092
                                 objectContentList) < 0) {
        goto cleanup;
    }

2093
    if (!(*objectContentList)) {
2094 2095 2096 2097 2098 2099 2100
        switch (occurrence) {
          case esxVI_Occurrence_OptionalItem:
          case esxVI_Occurrence_OptionalList:
            result = 0;
            break;

          case esxVI_Occurrence_RequiredItem:
2101 2102 2103
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not lookup '%s' from '%s'"),
                           type, root->type);
2104 2105 2106
            break;

          case esxVI_Occurrence_RequiredList:
2107 2108 2109
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not lookup '%s' list from '%s'"),
                           type, root->type);
2110 2111 2112
            break;

          default:
2113 2114
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Invalid occurrence value"));
2115 2116 2117
            break;
        }

M
Matthias Bolte 已提交
2118
        goto cleanup;
2119 2120
    }

2121
    result = 0;
2122

2123
 cleanup:
2124 2125 2126
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
2127
     * objectSpec cannot be NULL here.
2128
     */
2129 2130
    objectSpec->obj = NULL;
    objectSpec->selectSet = NULL;
2131

2132
    if (propertySpec) {
2133 2134 2135 2136
        propertySpec->type = NULL;
        propertySpec->pathSet = NULL;
    }

2137 2138 2139 2140 2141 2142 2143 2144
    if (!objectSpec_isAppended) {
        esxVI_ObjectSpec_Free(&objectSpec);
    }

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

2145 2146 2147 2148 2149 2150 2151
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);

    return result;
}



2152
int
2153
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
2154 2155 2156 2157 2158
                             const char *propertyName,
                             esxVI_ManagedEntityStatus *managedEntityStatus)
{
    esxVI_DynamicProperty *dynamicProperty;

2159
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2160 2161 2162
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            return esxVI_ManagedEntityStatus_CastFromAnyType
2163
                     (dynamicProperty->val, managedEntityStatus);
2164 2165 2166
        }
    }

2167 2168 2169
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Missing '%s' property while looking for "
                     "ManagedEntityStatus"), propertyName);
2170 2171 2172 2173 2174 2175

    return -1;
}



2176
int
2177
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
2178 2179 2180 2181
                                  esxVI_VirtualMachinePowerState *powerState)
{
    esxVI_DynamicProperty *dynamicProperty;

2182
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2183 2184 2185
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            return esxVI_VirtualMachinePowerState_CastFromAnyType
2186
                     (dynamicProperty->val, powerState);
2187 2188 2189
        }
    }

2190 2191
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Missing 'runtime.powerState' property"));
2192 2193 2194 2195 2196 2197

    return -1;
}



2198 2199
int
esxVI_GetVirtualMachineQuestionInfo
2200
  (esxVI_ObjectContent *virtualMachine,
2201 2202 2203 2204
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

2205
    if (!questionInfo || *questionInfo) {
2206
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2207 2208 2209
        return -1;
    }

2210
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
2211 2212 2213
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
2214
                  (dynamicProperty->val, questionInfo) < 0) {
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
                return -1;
            }
        }
    }

    return 0;
}



2225 2226
int
esxVI_GetBoolean(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2227
                 esxVI_Boolean *value, esxVI_Occurrence occurrence)
2228 2229 2230
{
    esxVI_DynamicProperty *dynamicProperty;

2231
    if (!value || *value != esxVI_Boolean_Undefined) {
2232
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2233 2234 2235
        return -1;
    }

2236
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
         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 已提交
2250
        occurrence == esxVI_Occurrence_RequiredItem) {
2251 2252
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2253 2254 2255 2256 2257 2258
        return -1;
    }

    return 0;
}

M
Matthias Bolte 已提交
2259 2260


2261 2262
int
esxVI_GetLong(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2263
              esxVI_Long **value, esxVI_Occurrence occurrence)
2264 2265 2266
{
    esxVI_DynamicProperty *dynamicProperty;

2267
    if (!value || *value) {
2268
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2269 2270 2271
        return -1;
    }

2272
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_Long_CastFromAnyType(dynamicProperty->val, value) < 0) {
                return -1;
            }

            break;
        }
    }

2283
    if (!(*value) && occurrence == esxVI_Occurrence_RequiredItem) {
2284 2285
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2286 2287 2288 2289 2290 2291
        return -1;
    }

    return 0;
}

2292 2293 2294 2295 2296


int
esxVI_GetStringValue(esxVI_ObjectContent *objectContent,
                     const char *propertyName,
M
Matthias Bolte 已提交
2297
                     char **value, esxVI_Occurrence occurrence)
2298 2299 2300
{
    esxVI_DynamicProperty *dynamicProperty;

2301
    if (!value || *value) {
2302
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2303 2304 2305
        return -1;
    }

2306
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
         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;
        }
    }

2319
    if (!(*value) && occurrence == esxVI_Occurrence_RequiredItem) {
2320 2321
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
        return -1;
    }

    return 0;
}



int
esxVI_GetManagedObjectReference(esxVI_ObjectContent *objectContent,
                                const char *propertyName,
                                esxVI_ManagedObjectReference **value,
M
Matthias Bolte 已提交
2334
                                esxVI_Occurrence occurrence)
2335 2336 2337
{
    esxVI_DynamicProperty *dynamicProperty;

2338
    if (!value || *value) {
2339
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2340 2341 2342
        return -1;
    }

2343
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, value) < 0) {
                return -1;
            }

            break;
        }
    }

2355
    if (!(*value) && occurrence == esxVI_Occurrence_RequiredItem) {
2356 2357
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2358 2359 2360 2361 2362 2363 2364 2365
        return -1;
    }

    return 0;
}



2366
int
2367
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
2368
                                        esxVI_VirtualMachinePowerState powerState,
2369
                                        bool inverse)
2370
{
M
Matthias Bolte 已提交
2371
    bool success = false;
2372 2373 2374 2375 2376
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
M
Matthias Bolte 已提交
2377
    int count = 0;
2378

2379
    if (esxVI_String_AppendValueToList(&propertyNameList,
2380
                                       "runtime.powerState") < 0 ||
2381 2382
        esxVI_LookupVirtualMachineList(ctx, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2383
        goto cleanup;
2384 2385
    }

2386
    for (virtualMachine = virtualMachineList; virtualMachine;
2387 2388
         virtualMachine = virtualMachine->_next) {
        for (dynamicProperty = virtualMachine->propSet;
2389
             dynamicProperty;
2390 2391 2392
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "runtime.powerState")) {
                if (esxVI_VirtualMachinePowerState_CastFromAnyType
2393
                      (dynamicProperty->val, &powerState_) < 0) {
M
Matthias Bolte 已提交
2394
                    goto cleanup;
2395 2396
                }

2397
                if ((!inverse && powerState_ == powerState) ||
2398
                    (inverse && powerState_ != powerState)) {
M
Matthias Bolte 已提交
2399
                    count++;
2400 2401 2402 2403 2404 2405 2406
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

M
Matthias Bolte 已提交
2407 2408
    success = true;

2409
 cleanup:
2410 2411 2412
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
2413
    return success ? count : -1;
2414 2415 2416 2417 2418
}



int
2419
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
2420 2421 2422 2423
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
2424
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
2425 2426

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
2427 2428
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("ObjectContent does not reference a virtual machine"));
2429 2430 2431
        return -1;
    }

2432
    if (id) {
2433 2434
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
2435 2436 2437
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse positive integer from '%s'"),
                           virtualMachine->obj->value);
2438 2439 2440 2441
            goto failure;
        }
    }

2442 2443
    if (name) {
        if (*name) {
2444
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2445 2446 2447 2448
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
2449
             dynamicProperty;
2450 2451
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2452
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2453 2454 2455 2456
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

2457
                if (VIR_STRDUP(*name, dynamicProperty->val->string) < 0)
2458 2459
                    goto failure;

2460
                if (virVMXUnescapeHexPercent(*name) < 0) {
2461 2462
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Domain name contains invalid escape sequence"));
2463 2464 2465
                    goto failure;
                }

2466 2467 2468 2469
                break;
            }
        }

2470
        if (!(*name)) {
2471 2472
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not get name of virtual machine"));
2473 2474 2475 2476
            goto failure;
        }
    }

2477
    if (uuid) {
2478
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
2479 2480 2481 2482 2483 2484
                                         &configStatus) < 0) {
            goto failure;
        }

        if (configStatus == esxVI_ManagedEntityStatus_Green) {
            for (dynamicProperty = virtualMachine->propSet;
2485
                 dynamicProperty;
2486 2487
                 dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "config.uuid")) {
2488
                    if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2489 2490 2491 2492 2493 2494
                                                 esxVI_Type_String) < 0) {
                        goto failure;
                    }

                    uuid_string = dynamicProperty->val->string;
                    break;
2495
                }
2496
            }
2497

2498
            if (!uuid_string) {
2499 2500
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Could not get UUID of virtual machine"));
2501
                goto failure;
2502 2503
            }

2504
            if (virUUIDParse(uuid_string, uuid) < 0) {
2505 2506 2507
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not parse UUID from string '%s'"),
                               uuid_string);
2508 2509 2510 2511
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
2512

2513
            VIR_WARN("Cannot access UUID, because 'configStatus' property "
2514
                      "indicates a config problem");
2515 2516 2517 2518 2519
        }
    }

    return 0;

2520
 failure:
2521
    if (name) {
2522 2523 2524 2525 2526 2527 2528 2529
        VIR_FREE(*name);
    }

    return -1;
}



2530 2531
int
esxVI_GetNumberOfSnapshotTrees
2532 2533
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList, bool recurse,
   bool leaves)
2534 2535 2536 2537
{
    int count = 0;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

2538
    for (snapshotTree = snapshotTreeList; snapshotTree;
2539
         snapshotTree = snapshotTree->_next) {
2540 2541
        if (!(leaves && snapshotTree->childSnapshotList))
            count++;
2542 2543
        if (recurse)
            count += esxVI_GetNumberOfSnapshotTrees
2544
                (snapshotTree->childSnapshotList, true, leaves);
2545 2546 2547 2548 2549 2550 2551 2552 2553
    }

    return count;
}



int
esxVI_GetSnapshotTreeNames(esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
2554 2555
                           char **names, int nameslen, bool recurse,
                           bool leaves)
2556 2557 2558
{
    int count = 0;
    int result;
2559
    size_t i;
2560 2561 2562
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList;
2563
         snapshotTree && count < nameslen;
2564
         snapshotTree = snapshotTree->_next) {
2565
        if (!(leaves && snapshotTree->childSnapshotList)) {
2566
            if (VIR_STRDUP(names[count], snapshotTree->name) < 0)
2567
                goto failure;
2568

2569 2570
            count++;
        }
2571 2572 2573 2574 2575

        if (count >= nameslen) {
            break;
        }

2576 2577 2578 2579
        if (recurse) {
            result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
                                                names + count,
                                                nameslen - count,
2580
                                                true, leaves);
2581

2582 2583 2584
            if (result < 0) {
                goto failure;
            }
2585

2586 2587
            count += result;
        }
2588 2589 2590 2591
    }

    return count;

2592
 failure:
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
    for (i = 0; i < count; ++i) {
        VIR_FREE(names[i]);
    }

    return -1;
}



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

2611 2612
    if (!snapshotTree || *snapshotTree ||
        (snapshotTreeParent && *snapshotTreeParent)) {
2613
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2614 2615 2616
        return -1;
    }

2617
    for (candidate = snapshotTreeList; candidate;
2618 2619 2620
         candidate = candidate->_next) {
        if (STREQ(candidate->name, name)) {
            *snapshotTree = candidate;
2621 2622
            if (snapshotTreeParent)
                *snapshotTreeParent = NULL;
2623 2624 2625 2626 2627 2628
            return 1;
        }

        if (esxVI_GetSnapshotTreeByName(candidate->childSnapshotList, name,
                                        snapshotTree, snapshotTreeParent,
                                        occurrence) > 0) {
2629
            if (snapshotTreeParent && !(*snapshotTreeParent)) {
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
                *snapshotTreeParent = candidate;
            }

            return 1;
        }
    }

    if (occurrence == esxVI_Occurrence_OptionalItem) {
        return 0;
    } else {
2640 2641
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("Could not find snapshot with name '%s'"), name);
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656

        return -1;
    }
}



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

2657
    if (!snapshotTree || *snapshotTree) {
2658
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2659 2660 2661
        return -1;
    }

2662
    for (candidate = snapshotTreeList; candidate;
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
         candidate = candidate->_next) {
        if (STREQ(candidate->snapshot->value, snapshot->value)) {
            *snapshotTree = candidate;
            return 0;
        }

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

2675 2676 2677
    virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                   _("Could not find domain snapshot with internal name '%s'"),
                   snapshot->value);
2678 2679 2680 2681 2682 2683

    return -1;
}



M
Matthias Bolte 已提交
2684 2685 2686 2687
int
esxVI_LookupHostSystemProperties(esxVI_Context *ctx,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **hostSystem)
M
Matthias Bolte 已提交
2688
{
2689 2690
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "HostSystem", propertyNameList,
2691 2692
                                           hostSystem,
                                           esxVI_Occurrence_RequiredItem);
M
Matthias Bolte 已提交
2693 2694 2695 2696
}



2697
int
2698 2699 2700
esxVI_LookupVirtualMachineList(esxVI_Context *ctx,
                               esxVI_String *propertyNameList,
                               esxVI_ObjectContent **virtualMachineList)
2701
{
2702 2703 2704 2705
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource->resourcePool
     *        for cluster support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "VirtualMachine", propertyNameList,
2706 2707
                                           virtualMachineList,
                                           esxVI_Occurrence_OptionalList);
2708 2709 2710 2711 2712
}



int
2713
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
2714
                                 esxVI_String *propertyNameList,
2715
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
2716
                                 esxVI_Occurrence occurrence)
2717
{
M
Matthias Bolte 已提交
2718
    int result = -1;
2719
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
2720
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
2721

2722
    if (!virtualMachine || *virtualMachine) {
2723
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2724 2725 2726
        return -1;
    }

2727 2728
    virUUIDFormat(uuid, uuid_string);

2729
    if (esxVI_FindByUuid(ctx, ctx->datacenter->_reference, uuid_string,
2730 2731
                         esxVI_Boolean_True, esxVI_Boolean_Undefined,
                         &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2732
        return -1;
2733 2734
    }

2735
    if (!managedObjectReference) {
M
Matthias Bolte 已提交
2736
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2737 2738 2739
            result = 0;

            goto cleanup;
2740
        } else {
2741 2742 2743
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("Could not find domain with UUID '%s'"),
                           uuid_string);
M
Matthias Bolte 已提交
2744
            goto cleanup;
2745 2746 2747
        }
    }

2748
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2749
                                        "VirtualMachine", propertyNameList,
2750 2751
                                        virtualMachine,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2752
        goto cleanup;
2753 2754
    }

M
Matthias Bolte 已提交
2755 2756
    result = 0;

2757
 cleanup:
2758 2759 2760
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
M
Matthias Bolte 已提交
2761 2762 2763 2764
}



2765 2766 2767 2768 2769 2770
int
esxVI_LookupVirtualMachineByName(esxVI_Context *ctx, const char *name,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2771
    int result = -1;
2772 2773 2774 2775 2776
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate = NULL;

2777
    if (!virtualMachine || *virtualMachine) {
2778
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2779 2780 2781 2782 2783 2784
        return -1;
    }

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
2785 2786
        esxVI_LookupVirtualMachineList(ctx, completePropertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2787
        goto cleanup;
2788 2789
    }

2790
    for (candidate = virtualMachineList; candidate;
2791 2792 2793 2794 2795
         candidate = candidate->_next) {
        VIR_FREE(name_candidate);

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
M
Matthias Bolte 已提交
2796
            goto cleanup;
2797 2798 2799 2800 2801 2802 2803
        }

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

        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0) {
M
Matthias Bolte 已提交
2804
            goto cleanup;
2805 2806 2807 2808 2809
        }

        break;
    }

2810
    if (!(*virtualMachine)) {
2811
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2812 2813 2814
            result = 0;

            goto cleanup;
2815
        } else {
2816 2817
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("Could not find domain with name '%s'"), name);
M
Matthias Bolte 已提交
2818
            goto cleanup;
2819 2820 2821
        }
    }

M
Matthias Bolte 已提交
2822 2823
    result = 0;

2824
 cleanup:
2825 2826 2827 2828 2829 2830 2831 2832 2833
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;
}



2834 2835
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2836
  (esxVI_Context *ctx, const unsigned char *uuid,
2837
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
2838
   bool autoAnswer)
2839
{
M
Matthias Bolte 已提交
2840
    int result = -1;
2841 2842 2843
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;
2844
    bool blocked;
2845

2846
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2847
                                  propertyNameList) < 0 ||
2848
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2849 2850
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2851
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2852
                                         virtualMachine,
M
Matthias Bolte 已提交
2853
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2854
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
2855 2856
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
2857
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
M
Matthias Bolte 已提交
2858
        goto cleanup;
2859 2860
    }

2861
    if (questionInfo &&
2862
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
2863 2864
                                           questionInfo, autoAnswer,
                                           &blocked) < 0) {
M
Matthias Bolte 已提交
2865
        goto cleanup;
2866 2867
    }

2868
    if (pendingTaskInfoList) {
2869 2870
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Other tasks are pending for this domain"));
M
Matthias Bolte 已提交
2871
        goto cleanup;
2872 2873
    }

M
Matthias Bolte 已提交
2874 2875
    result = 0;

2876
 cleanup:
2877 2878 2879 2880 2881 2882 2883 2884 2885
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;
}



2886 2887 2888 2889 2890 2891 2892 2893
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,
2894 2895
                                           datastoreList,
                                           esxVI_Occurrence_OptionalList);
2896 2897 2898 2899
}



M
Matthias Bolte 已提交
2900
int
2901 2902
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
2903
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
2904
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
2905
{
M
Matthias Bolte 已提交
2906
    int result = -1;
M
Matthias Bolte 已提交
2907 2908 2909
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
2910
    char *name_candidate;
M
Matthias Bolte 已提交
2911

2912
    if (!datastore || *datastore) {
2913
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
2914 2915 2916 2917
        return -1;
    }

    /* Get all datastores */
2918
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
2919
                                  propertyNameList) < 0 ||
2920 2921
        esxVI_String_AppendValueToList(&completePropertyNameList,
                                       "summary.name") < 0 ||
2922 2923
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
M
Matthias Bolte 已提交
2924
        goto cleanup;
M
Matthias Bolte 已提交
2925 2926
    }

2927
    /* Search for a matching datastore */
2928
    for (candidate = datastoreList; candidate;
2929 2930 2931 2932 2933
         candidate = candidate->_next) {
        name_candidate = NULL;

        if (esxVI_GetStringValue(candidate, "summary.name", &name_candidate,
                                 esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2934
            goto cleanup;
M
Matthias Bolte 已提交
2935
        }
2936 2937 2938 2939 2940 2941

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

2942 2943 2944 2945
            /* Found datastore with matching name */
            result = 0;

            goto cleanup;
2946 2947 2948
        }
    }

2949
    if (!(*datastore) && occurrence != esxVI_Occurrence_OptionalItem) {
2950 2951
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datastore with name '%s'"), name);
2952 2953 2954 2955 2956
        goto cleanup;
    }

    result = 0;

2957
 cleanup:
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
    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;

2980
    if (!datastore || *datastore) {
2981
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
        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 已提交
2992 2993 2994
    }

    /* Search for a matching datastore */
2995
    for (candidate = datastoreList; candidate;
M
Matthias Bolte 已提交
2996
         candidate = candidate->_next) {
2997
        esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
2998

2999
        for (dynamicProperty = candidate->propSet; dynamicProperty;
M
Matthias Bolte 已提交
3000
             dynamicProperty = dynamicProperty->_next) {
3001 3002 3003
            if (STREQ(dynamicProperty->name, "host")) {
                if (esxVI_DatastoreHostMount_CastListFromAnyType
                      (dynamicProperty->val, &datastoreHostMountList) < 0) {
M
Matthias Bolte 已提交
3004
                    goto cleanup;
3005 3006 3007 3008 3009 3010
                }

                break;
            }
        }

3011
        if (!datastoreHostMountList) {
3012
            continue;
3013 3014
        }

3015
        for (datastoreHostMount = datastoreHostMountList;
3016
             datastoreHostMount;
3017 3018 3019 3020 3021
             datastoreHostMount = datastoreHostMount->_next) {
            if (STRNEQ(ctx->hostSystem->_reference->value,
                       datastoreHostMount->key->value)) {
                continue;
            }
3022

3023 3024
            if (STRPREFIX(absolutePath, datastoreHostMount->mountInfo->path)) {
                if (esxVI_ObjectContent_DeepCopy(datastore, candidate) < 0) {
M
Matthias Bolte 已提交
3025
                    goto cleanup;
M
Matthias Bolte 已提交
3026 3027
                }

3028
                /* Found datastore with matching mount path */
3029 3030 3031
                result = 0;

                goto cleanup;
M
Matthias Bolte 已提交
3032 3033 3034 3035
            }
        }
    }

3036
    if (!(*datastore) && occurrence != esxVI_Occurrence_OptionalItem) {
3037 3038 3039
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datastore containing absolute path '%s'"),
                       absolutePath);
M
Matthias Bolte 已提交
3040
        goto cleanup;
M
Matthias Bolte 已提交
3041 3042
    }

M
Matthias Bolte 已提交
3043 3044
    result = 0;

3045
 cleanup:
M
Matthias Bolte 已提交
3046 3047
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
3048
    esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
M
Matthias Bolte 已提交
3049 3050

    return result;
3051 3052 3053 3054
}



3055 3056 3057
int
esxVI_LookupDatastoreHostMount(esxVI_Context *ctx,
                               esxVI_ManagedObjectReference *datastore,
3058 3059
                               esxVI_DatastoreHostMount **hostMount,
                               esxVI_Occurrence occurrence)
3060 3061 3062 3063 3064 3065 3066 3067
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_DatastoreHostMount *hostMountList = NULL;
    esxVI_DatastoreHostMount *candidate = NULL;

3068
    if (!hostMount || *hostMount) {
3069
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3070 3071 3072 3073 3074
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList, "host") < 0 ||
        esxVI_LookupObjectContentByType(ctx, datastore, "Datastore",
3075 3076
                                        propertyNameList, &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
3077 3078 3079
        goto cleanup;
    }

3080
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
         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);
        }
    }

3094
    for (candidate = hostMountList; candidate;
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
         candidate = candidate->_next) {
        if (STRNEQ(ctx->hostSystem->_reference->value, candidate->key->value)) {
            continue;
        }

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

        break;
    }

3107
    if (!(*hostMount) && occurrence == esxVI_Occurrence_RequiredItem) {
3108 3109
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not lookup datastore host mount"));
3110 3111 3112 3113 3114
        goto cleanup;
    }

    result = 0;

3115
 cleanup:
3116 3117 3118 3119 3120 3121 3122 3123
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);
    esxVI_DatastoreHostMount_Free(&hostMountList);

    return result;
}


3124 3125 3126 3127
int
esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
                           esxVI_ManagedObjectReference *task,
                           esxVI_TaskInfo **taskInfo)
3128
{
M
Matthias Bolte 已提交
3129
    int result = -1;
3130 3131 3132 3133
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

3134
    if (!taskInfo || *taskInfo) {
3135
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3136 3137 3138
        return -1;
    }

3139 3140
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
3141 3142
                                        &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3143
        goto cleanup;
3144 3145
    }

3146
    for (dynamicProperty = objectContent->propSet; dynamicProperty;
3147 3148
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
3149
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
3150
                                               taskInfo) < 0) {
M
Matthias Bolte 已提交
3151
                goto cleanup;
3152 3153 3154 3155 3156 3157 3158 3159
            }

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

M
Matthias Bolte 已提交
3160 3161
    result = 0;

3162
 cleanup:
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);

    return result;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
3173
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
3174 3175
   esxVI_TaskInfo **pendingTaskInfoList)
{
M
Matthias Bolte 已提交
3176
    int result = -1;
3177 3178 3179 3180 3181 3182
    esxVI_String *propertyNameList = NULL;
    esxVI_ManagedObjectReference *recentTaskList = NULL;
    esxVI_ManagedObjectReference *recentTask = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_TaskInfo *taskInfo = NULL;

3183
    if (!pendingTaskInfoList || *pendingTaskInfoList) {
3184
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3185 3186 3187 3188
        return -1;
    }

    /* Get list of recent tasks */
3189
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
3190 3191 3192
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "recentTask")) {
            if (esxVI_ManagedObjectReference_CastListFromAnyType
3193
                  (dynamicProperty->val, &recentTaskList) < 0) {
M
Matthias Bolte 已提交
3194
                goto cleanup;
3195 3196 3197 3198 3199 3200 3201
            }

            break;
        }
    }

    /* Lookup task info for each task */
3202
    for (recentTask = recentTaskList; recentTask;
3203
         recentTask = recentTask->_next) {
3204
        if (esxVI_LookupTaskInfoByTask(ctx, recentTask, &taskInfo) < 0) {
M
Matthias Bolte 已提交
3205
            goto cleanup;
3206 3207 3208 3209
        }

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
3210
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
3211
                                            taskInfo) < 0) {
M
Matthias Bolte 已提交
3212
                goto cleanup;
3213 3214 3215 3216 3217 3218 3219 3220
            }

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

M
Matthias Bolte 已提交
3221 3222
    result = 0;

3223
 cleanup:
M
Matthias Bolte 已提交
3224 3225 3226 3227
    if (result < 0) {
        esxVI_TaskInfo_Free(pendingTaskInfoList);
    }

3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



int
3238
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
3239
                                            const unsigned char *uuid,
3240
                                            esxVI_Occurrence occurrence,
3241
                                            bool autoAnswer, bool *blocked)
3242
{
M
Matthias Bolte 已提交
3243
    int result = -1;
3244 3245 3246 3247
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

3248
    if (esxVI_String_AppendValueToList(&propertyNameList,
3249
                                       "runtime.question") < 0 ||
3250
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
3251
                                         &virtualMachine, occurrence) < 0) {
M
Matthias Bolte 已提交
3252
        goto cleanup;
3253 3254
    }

3255
    if (virtualMachine) {
3256 3257 3258 3259 3260
        if (esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
                                                &questionInfo) < 0) {
            goto cleanup;
        }

3261
        if (questionInfo &&
3262 3263 3264 3265 3266
            esxVI_HandleVirtualMachineQuestion(ctx, virtualMachine->obj,
                                               questionInfo, autoAnswer,
                                               blocked) < 0) {
            goto cleanup;
        }
3267 3268
    }

M
Matthias Bolte 已提交
3269 3270
    result = 0;

3271
 cleanup:
3272 3273 3274 3275 3276 3277 3278 3279 3280
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);

    return result;
}



3281 3282 3283 3284 3285
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
M
Matthias Bolte 已提交
3286
    int result = -1;
3287 3288 3289 3290
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

3291
    if (!rootSnapshotTreeList || *rootSnapshotTreeList) {
3292
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3293 3294 3295 3296 3297 3298 3299 3300
        return -1;
    }

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

3304
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
3305 3306 3307 3308
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3309
                goto cleanup;
3310 3311 3312 3313 3314 3315 3316 3317
            }

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

M
Matthias Bolte 已提交
3318 3319
    result = 0;

3320
 cleanup:
M
Matthias Bolte 已提交
3321 3322 3323 3324
    if (result < 0) {
        esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);
    }

3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338
    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 已提交
3339
    int result = -1;
3340 3341 3342 3343 3344 3345 3346
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *currentSnapshot = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;

3347
    if (!currentSnapshotTree || *currentSnapshotTree) {
3348
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3349 3350 3351 3352 3353 3354 3355 3356 3357
        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 已提交
3358
        goto cleanup;
3359 3360
    }

3361
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty;
3362 3363 3364 3365
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.currentSnapshot")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, &currentSnapshot) < 0) {
M
Matthias Bolte 已提交
3366
                goto cleanup;
3367 3368 3369 3370
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3371
                goto cleanup;
3372 3373 3374 3375 3376 3377
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

3378
    if (!currentSnapshot) {
3379
        if (occurrence == esxVI_Occurrence_OptionalItem) {
3380 3381 3382
            result = 0;

            goto cleanup;
3383
        } else {
3384 3385
            virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                           _("Domain has no current snapshot"));
M
Matthias Bolte 已提交
3386
            goto cleanup;
3387 3388 3389
        }
    }

3390
    if (!rootSnapshotTreeList) {
3391 3392
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not lookup root snapshot list"));
M
Matthias Bolte 已提交
3393
        goto cleanup;
3394 3395 3396 3397 3398 3399
    }

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

M
Matthias Bolte 已提交
3403 3404
    result = 0;

3405
 cleanup:
3406 3407 3408 3409 3410 3411 3412 3413 3414 3415
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



3416 3417 3418
int
esxVI_LookupFileInfoByDatastorePath(esxVI_Context *ctx,
                                    const char *datastorePath,
3419
                                    bool lookupFolder,
3420 3421 3422 3423 3424 3425
                                    esxVI_FileInfo **fileInfo,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    char *datastoreName = NULL;
    char *directoryName = NULL;
3426
    char *directoryAndFileName = NULL;
3427
    char *fileName = NULL;
3428
    size_t length;
3429 3430 3431 3432 3433
    char *datastorePathWithoutFileName = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
3434
    esxVI_FolderFileQuery *folderFileQuery = NULL;
3435 3436 3437 3438 3439
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3440
    char *taskInfoErrorMessage = NULL;
3441 3442 3443
    esxVI_TaskInfo *taskInfo = NULL;
    esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL;

3444
    if (!fileInfo || *fileInfo) {
3445
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3446 3447 3448 3449
        return -1;
    }

    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName,
3450
                                   &directoryName, &directoryAndFileName) < 0) {
3451 3452 3453
        goto cleanup;
    }

3454 3455 3456 3457 3458
    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.
         */
3459
        if (virAsprintf(&datastorePathWithoutFileName, "[%s]",
3460
                        datastoreName) < 0)
3461
            goto cleanup;
3462

3463
        if (VIR_STRDUP(fileName, directoryAndFileName) < 0) {
3464 3465
            goto cleanup;
        }
3466 3467
    } else {
        if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s",
3468
                        datastoreName, directoryName) < 0)
3469
            goto cleanup;
3470 3471 3472 3473 3474

        length = strlen(directoryName);

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

3481
        if (VIR_STRDUP(fileName, directoryAndFileName + length + 1) < 0) {
3482 3483
            goto cleanup;
        }
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
    }

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

3507 3508 3509 3510 3511 3512 3513
    if (lookupFolder) {
        if (esxVI_FolderFileQuery_Alloc(&folderFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(folderFileQuery)) < 0) {
            goto cleanup;
        }
3514
        folderFileQuery = NULL;
3515 3516 3517 3518 3519 3520 3521 3522
    } 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;
        }
3523

3524 3525 3526 3527 3528
        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;
3529
        vmDiskFileQuery = NULL;
3530

3531 3532 3533 3534 3535 3536
        if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
            goto cleanup;
        }
3537
        isoImageFileQuery = NULL;
3538

3539 3540 3541 3542 3543 3544
        if (esxVI_FloppyImageFileQuery_Alloc(&floppyImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(floppyImageFileQuery)) < 0) {
            goto cleanup;
        }
3545
        floppyImageFileQuery = NULL;
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
    }

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

    searchSpec->matchPattern->value = fileName;

    /* Search datastore for file */
    if (esxVI_SearchDatastore_Task(ctx, hostDatastoreBrowser,
                                   datastorePathWithoutFileName, searchSpec,
                                   &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3559
                                    false, &taskInfoState,
3560
                                    &taskInfoErrorMessage) < 0) {
3561 3562 3563 3564
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3565 3566 3567
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not search in datastore '%s': %s"),
                       datastoreName, taskInfoErrorMessage);
3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
        goto cleanup;
    }

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

    /* Interpret search result */
3578
    if (!searchResults->file) {
3579 3580 3581 3582 3583
        if (occurrence == esxVI_Occurrence_OptionalItem) {
            result = 0;

            goto cleanup;
        } else {
3584 3585 3586
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("No storage volume with key or path '%s'"),
                           datastorePath);
3587 3588 3589 3590 3591 3592 3593 3594 3595
            goto cleanup;
        }
    }

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

    result = 0;

3596
 cleanup:
3597
    /* Don't double free fileName */
3598
    if (searchSpec && searchSpec->matchPattern) {
3599 3600 3601 3602 3603
        searchSpec->matchPattern->value = NULL;
    }

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3604
    VIR_FREE(directoryAndFileName);
3605 3606 3607 3608 3609 3610 3611
    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);
3612
    VIR_FREE(taskInfoErrorMessage);
3613 3614
    esxVI_TaskInfo_Free(&taskInfo);
    esxVI_HostDatastoreBrowserSearchResults_Free(&searchResults);
3615 3616 3617 3618
    esxVI_FolderFileQuery_Free(&folderFileQuery);
    esxVI_VmDiskFileQuery_Free(&vmDiskFileQuery);
    esxVI_IsoImageFileQuery_Free(&isoImageFileQuery);
    esxVI_FloppyImageFileQuery_Free(&floppyImageFileQuery);
3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640

    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;
3641
    char *taskInfoErrorMessage = NULL;
3642 3643
    esxVI_TaskInfo *taskInfo = NULL;

3644
    if (!searchResultsList || *searchResultsList) {
3645
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682
        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;
3683
    vmDiskFileQuery = NULL;
3684 3685 3686 3687 3688 3689 3690

    if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
        esxVI_FileQuery_AppendToList
          (&searchSpec->query,
           esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
        goto cleanup;
    }
3691
    isoImageFileQuery = NULL;
3692 3693 3694 3695 3696 3697 3698

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

    /* Search datastore for files */
3702
    if (virAsprintf(&datastorePath, "[%s]", datastoreName) < 0)
3703 3704 3705 3706 3707 3708
        goto cleanup;

    if (esxVI_SearchDatastoreSubFolders_Task(ctx, hostDatastoreBrowser,
                                             datastorePath, searchSpec,
                                             &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3709
                                    false, &taskInfoState,
3710
                                    &taskInfoErrorMessage) < 0) {
3711 3712 3713 3714
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3715
        virReportError(VIR_ERR_INTERNAL_ERROR,
3716
                       _("Could not search in datastore '%s': %s"),
3717
                       datastoreName, taskInfoErrorMessage);
3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728
        goto cleanup;
    }

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

    result = 0;

3729
 cleanup:
3730 3731 3732 3733 3734 3735
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    VIR_FREE(datastorePath);
    esxVI_ManagedObjectReference_Free(&task);
3736
    VIR_FREE(taskInfoErrorMessage);
3737
    esxVI_TaskInfo_Free(&taskInfo);
3738 3739 3740
    esxVI_VmDiskFileQuery_Free(&vmDiskFileQuery);
    esxVI_IsoImageFileQuery_Free(&isoImageFileQuery);
    esxVI_FloppyImageFileQuery_Free(&floppyImageFileQuery);
3741 3742 3743 3744 3745 3746

    return result;
}



3747 3748 3749 3750 3751 3752 3753 3754 3755
int
esxVI_LookupStorageVolumeKeyByDatastorePath(esxVI_Context *ctx,
                                            const char *datastorePath,
                                            char **key)
{
    int result = -1;
    esxVI_FileInfo *fileInfo = NULL;
    char *uuid_string = NULL;

3756
    if (!key || *key) {
3757
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3758 3759 3760
        return -1;
    }

3761 3762 3763 3764
    if (ctx->hasQueryVirtualDiskUuid) {
        if (esxVI_LookupFileInfoByDatastorePath
              (ctx, datastorePath, false, &fileInfo,
               esxVI_Occurrence_RequiredItem) < 0) {
3765 3766 3767
            goto cleanup;
        }

3768
        if (esxVI_VmDiskFileInfo_DynamicCast(fileInfo)) {
3769 3770 3771 3772 3773 3774
            /* VirtualDisks have a UUID, use it as key */
            if (esxVI_QueryVirtualDiskUuid(ctx, datastorePath,
                                           ctx->datacenter->_reference,
                                           &uuid_string) < 0) {
                goto cleanup;
            }
3775

3776
            if (VIR_ALLOC_N(*key, VIR_UUID_STRING_BUFLEN) < 0)
3777 3778 3779 3780 3781
                goto cleanup;

            if (esxUtil_ReformatUuid(uuid_string, *key) < 0) {
                goto cleanup;
            }
3782
        }
3783 3784
    }

3785
    if (!(*key)) {
3786
        /* Other files don't have a UUID, fall back to the path as key */
3787
        if (VIR_STRDUP(*key, datastorePath) < 0) {
3788 3789 3790 3791 3792 3793
            goto cleanup;
        }
    }

    result = 0;

3794
 cleanup:
3795 3796 3797 3798 3799 3800 3801 3802
    esxVI_FileInfo_Free(&fileInfo);
    VIR_FREE(uuid_string);

    return result;
}



3803 3804 3805 3806 3807 3808 3809 3810 3811
int
esxVI_LookupAutoStartDefaults(esxVI_Context *ctx,
                              esxVI_AutoStartDefaults **defaults)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostAutoStartManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

3812
    if (!defaults || *defaults) {
3813
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826
        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,
3827
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3828 3829 3830 3831
        goto cleanup;
    }

    for (dynamicProperty = hostAutoStartManager->propSet;
3832
         dynamicProperty; dynamicProperty = dynamicProperty->_next) {
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
        if (STREQ(dynamicProperty->name, "config.defaults")) {
            if (esxVI_AutoStartDefaults_CastFromAnyType(dynamicProperty->val,
                                                        defaults) < 0) {
                goto cleanup;
            }

            break;
        }
    }

3843
    if (!(*defaults)) {
3844 3845
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve the AutoStartDefaults object"));
3846 3847 3848 3849 3850
        goto cleanup;
    }

    result = 0;

3851
 cleanup:
3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868
    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;

3869
    if (!powerInfoList || *powerInfoList) {
3870
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883
        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,
3884
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3885 3886 3887 3888
        goto cleanup;
    }

    for (dynamicProperty = hostAutoStartManager->propSet;
3889
         dynamicProperty; dynamicProperty = dynamicProperty->_next) {
3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
        if (STREQ(dynamicProperty->name, "config.powerInfo")) {
            if (esxVI_AutoStartPowerInfo_CastListFromAnyType
                  (dynamicProperty->val, powerInfoList) < 0) {
                goto cleanup;
            }

            break;
        }
    }

    result = 0;

3902
 cleanup:
3903 3904 3905 3906 3907 3908 3909 3910
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&hostAutoStartManager);

    return result;
}



M
Matthias Bolte 已提交
3911 3912 3913 3914 3915 3916 3917 3918 3919
int
esxVI_LookupPhysicalNicList(esxVI_Context *ctx,
                            esxVI_PhysicalNic **physicalNicList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

3920
    if (!physicalNicList || *physicalNicList) {
M
Matthias Bolte 已提交
3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931
        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;
    }

3932
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
M
Matthias Bolte 已提交
3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945
         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;

3946
 cleanup:
M
Matthias Bolte 已提交
3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963
    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;

3964
    if (!physicalNic || *physicalNic) {
M
Matthias Bolte 已提交
3965 3966 3967 3968 3969 3970 3971 3972 3973
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_LookupPhysicalNicList(ctx, &physicalNicList) < 0) {
        goto cleanup;
    }

    /* Search for a matching physical NIC */
3974
    for (candidate = physicalNicList; candidate;
M
Matthias Bolte 已提交
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987
         candidate = candidate->_next) {
        if (STRCASEEQ(candidate->device, name)) {
            if (esxVI_PhysicalNic_DeepCopy(physicalNic, candidate) < 0) {
                goto cleanup;
            }

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

            goto cleanup;
        }
    }

3988
    if (!(*physicalNic) && occurrence != esxVI_Occurrence_OptionalItem) {
M
Matthias Bolte 已提交
3989 3990 3991 3992 3993 3994 3995
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("Could not find physical NIC with name '%s'"), name);
        goto cleanup;
    }

    result = 0;

3996
 cleanup:
M
Matthias Bolte 已提交
3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012
    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;

4013
    if (!physicalNic || *physicalNic) {
M
Matthias Bolte 已提交
4014 4015 4016 4017 4018 4019 4020 4021 4022
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_LookupPhysicalNicList(ctx, &physicalNicList) < 0) {
        goto cleanup;
    }

    /* Search for a matching physical NIC */
4023
    for (candidate = physicalNicList; candidate;
M
Matthias Bolte 已提交
4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036
         candidate = candidate->_next) {
        if (STRCASEEQ(candidate->mac, mac)) {
            if (esxVI_PhysicalNic_DeepCopy(physicalNic, candidate) < 0) {
                goto cleanup;
            }

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

            goto cleanup;
        }
    }

4037
    if (!(*physicalNic) && occurrence != esxVI_Occurrence_OptionalItem) {
M
Matthias Bolte 已提交
4038 4039 4040 4041 4042 4043 4044
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("Could not find physical NIC with MAC address '%s'"), mac);
        goto cleanup;
    }

    result = 0;

4045
 cleanup:
M
Matthias Bolte 已提交
4046 4047 4048 4049 4050 4051 4052
    esxVI_PhysicalNic_Free(&physicalNicList);

    return result;
}



M
Matthias Bolte 已提交
4053 4054 4055 4056 4057 4058 4059 4060 4061
int
esxVI_LookupHostVirtualSwitchList(esxVI_Context *ctx,
                                  esxVI_HostVirtualSwitch **hostVirtualSwitchList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

4062
    if (!hostVirtualSwitchList || *hostVirtualSwitchList) {
M
Matthias Bolte 已提交
4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073
        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;
    }

4074
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087
         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;

4088
 cleanup:
M
Matthias Bolte 已提交
4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105
    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;

4106
    if (!hostVirtualSwitch || *hostVirtualSwitch) {
M
Matthias Bolte 已提交
4107 4108 4109 4110 4111 4112 4113 4114 4115
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_LookupHostVirtualSwitchList(ctx, &hostVirtualSwitchList) < 0) {
        goto cleanup;
    }

    /* Search for a matching HostVirtualSwitch */
4116
    for (candidate = hostVirtualSwitchList; candidate;
M
Matthias Bolte 已提交
4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130
         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;
        }
    }

4131
    if (!(*hostVirtualSwitch) &&
M
Matthias Bolte 已提交
4132 4133 4134 4135 4136 4137 4138 4139 4140
        occurrence != esxVI_Occurrence_OptionalItem) {
        virReportError(VIR_ERR_NO_NETWORK,
                       _("Could not find HostVirtualSwitch with name '%s'"),
                       name);
        goto cleanup;
    }

    result = 0;

4141
 cleanup:
M
Matthias Bolte 已提交
4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
    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;

4158
    if (!hostPortGroupList || *hostPortGroupList) {
M
Matthias Bolte 已提交
4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
        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;
    }

4170
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
M
Matthias Bolte 已提交
4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185
         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;

4186
 cleanup:
M
Matthias Bolte 已提交
4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206
    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);
}



4207 4208
int
esxVI_HandleVirtualMachineQuestion
4209
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
4210 4211
   esxVI_VirtualMachineQuestionInfo *questionInfo, bool autoAnswer,
   bool *blocked)
4212
{
M
Matthias Bolte 已提交
4213
    int result = -1;
4214 4215 4216 4217 4218 4219
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

4220
    if (!blocked) {
4221
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
4222 4223 4224
        return -1;
    }

4225
    *blocked = false;
4226

4227
    if (questionInfo->choice->choiceInfo) {
4228
        for (elementDescription = questionInfo->choice->choiceInfo;
4229
             elementDescription;
4230
             elementDescription = elementDescription->_next) {
4231
            virBufferAsprintf(&buffer, "'%s'", elementDescription->label);
4232

4233
            if (elementDescription->_next) {
4234 4235 4236
                virBufferAddLit(&buffer, ", ");
            }

4237 4238
            if (!answerChoice &&
                questionInfo->choice->defaultIndex &&
4239 4240 4241 4242 4243 4244 4245 4246
                questionInfo->choice->defaultIndex->value == answerIndex) {
                answerChoice = elementDescription;
            }

            ++answerIndex;
        }

        if (virBufferError(&buffer)) {
4247
            virReportOOMError();
M
Matthias Bolte 已提交
4248
            goto cleanup;
4249 4250 4251 4252 4253
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

4254
    if (autoAnswer) {
4255
        if (!possibleAnswers) {
4256 4257 4258 4259
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', no possible answers"),
                           questionInfo->text);
4260

4261
            *blocked = true;
M
Matthias Bolte 已提交
4262
            goto cleanup;
4263
        } else if (!answerChoice) {
4264 4265 4266 4267 4268
            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);
4269

4270
            *blocked = true;
M
Matthias Bolte 已提交
4271
            goto cleanup;
4272 4273 4274 4275 4276 4277 4278
        }

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

4279
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
4280
                           answerChoice->key) < 0) {
M
Matthias Bolte 已提交
4281
            goto cleanup;
4282 4283
        }
    } else {
4284
        if (possibleAnswers) {
4285 4286 4287 4288
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', possible answers are %s"),
                           questionInfo->text, possibleAnswers);
4289
        } else {
4290 4291 4292 4293
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', no possible answers"),
                           questionInfo->text);
4294 4295
        }

4296
        *blocked = true;
M
Matthias Bolte 已提交
4297
        goto cleanup;
4298 4299
    }

M
Matthias Bolte 已提交
4300 4301
    result = 0;

4302
 cleanup:
M
Matthias Bolte 已提交
4303 4304 4305 4306
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

4307 4308 4309 4310 4311 4312 4313
    VIR_FREE(possibleAnswers);

    return result;
}



4314
int
4315
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
4316
                            esxVI_ManagedObjectReference *task,
4317
                            const unsigned char *virtualMachineUuid,
4318
                            esxVI_Occurrence virtualMachineOccurrence,
4319
                            bool autoAnswer, esxVI_TaskInfoState *finalState,
4320
                            char **errorMessage)
4321
{
M
Matthias Bolte 已提交
4322
    int result = -1;
4323
    esxVI_ObjectSpec *objectSpec = NULL;
4324
    bool objectSpec_isAppended = false;
4325
    esxVI_PropertySpec *propertySpec = NULL;
4326
    bool propertySpec_isAppended = false;
4327 4328 4329 4330 4331 4332 4333 4334 4335
    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;
4336
    bool blocked;
4337
    esxVI_TaskInfo *taskInfo = NULL;
4338

4339
    if (!errorMessage || *errorMessage) {
4340
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
4341 4342 4343
        return -1;
    }

4344
    if (VIR_STRDUP(version, "") < 0)
M
Matthias Bolte 已提交
4345
        return -1;
4346

4347
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
4348
        goto cleanup;
4349 4350 4351 4352 4353
    }

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

4354
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
4355
        goto cleanup;
4356 4357 4358 4359
    }

    propertySpec->type = task->type;

4360
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
4361
                                       "info.state") < 0 ||
4362 4363
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377
                                        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,
4378
                           &propertyFilter) < 0) {
M
Matthias Bolte 已提交
4379
        goto cleanup;
4380 4381 4382 4383 4384 4385
    }

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

4386
        if (virtualMachineUuid) {
4387
            if (esxVI_LookupAndHandleVirtualMachineQuestion
4388 4389
                  (ctx, virtualMachineUuid, virtualMachineOccurrence,
                   autoAnswer, &blocked) < 0) {
4390 4391 4392 4393 4394
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
4395
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
M
Matthias Bolte 已提交
4396
                    goto cleanup;
4397 4398 4399
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
4400
                    if (esxVI_CancelTask(ctx, task) < 0 && blocked) {
4401
                        VIR_ERROR(_("Cancelable task is blocked by an "
E
Eric Blake 已提交
4402
                                     "unanswered question but cancellation "
4403
                                     "failed"));
4404
                    }
4405
                } else if (blocked) {
4406
                    VIR_ERROR(_("Non-cancelable task is blocked by an "
4407
                                 "unanswered question"));
4408 4409 4410 4411
                }

                /* FIXME: Enable error reporting here again */

M
Matthias Bolte 已提交
4412
                goto cleanup;
4413 4414 4415
            }
        }

4416
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
M
Matthias Bolte 已提交
4417
            goto cleanup;
4418 4419 4420
        }

        VIR_FREE(version);
4421
        if (VIR_STRDUP(version, updateSet->version) < 0)
M
Matthias Bolte 已提交
4422
            goto cleanup;
4423

4424
        if (!updateSet->filterSet) {
4425 4426 4427 4428
            continue;
        }

        for (propertyFilterUpdate = updateSet->filterSet;
4429
             propertyFilterUpdate;
4430 4431
             propertyFilterUpdate = propertyFilterUpdate->_next) {
            for (objectUpdate = propertyFilterUpdate->objectSet;
4432
                 objectUpdate; objectUpdate = objectUpdate->_next) {
4433
                for (propertyChange = objectUpdate->changeSet;
4434
                     propertyChange;
4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447
                     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;
                        }
                    }
                }
            }
        }

4448
        if (!propertyValue) {
4449 4450 4451
            continue;
        }

4452
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
M
Matthias Bolte 已提交
4453
            goto cleanup;
4454 4455 4456
        }
    }

4457
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
4458
        VIR_DEBUG("DestroyPropertyFilter failed");
4459 4460
    }

4461
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
M
Matthias Bolte 已提交
4462
        goto cleanup;
4463 4464
    }

4465 4466 4467 4468 4469
    if (*finalState != esxVI_TaskInfoState_Success) {
        if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
            goto cleanup;
        }

4470
        if (!taskInfo->error) {
4471
            if (VIR_STRDUP(*errorMessage, _("Unknown error")) < 0)
4472
                goto cleanup;
4473
        } else if (!taskInfo->error->localizedMessage) {
4474
            if (VIR_STRDUP(*errorMessage, taskInfo->error->fault->_actualType) < 0)
4475 4476 4477 4478
                goto cleanup;
        } else {
            if (virAsprintf(errorMessage, "%s - %s",
                            taskInfo->error->fault->_actualType,
4479
                            taskInfo->error->localizedMessage) < 0)
4480 4481 4482 4483
                goto cleanup;
        }
    }

M
Matthias Bolte 已提交
4484 4485
    result = 0;

4486
 cleanup:
4487 4488 4489 4490
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
     */
4491
    if (objectSpec) {
4492 4493 4494
        objectSpec->obj = NULL;
    }

4495
    if (propertySpec) {
4496 4497 4498
        propertySpec->type = NULL;
    }

4499 4500 4501 4502 4503 4504 4505 4506
    if (!objectSpec_isAppended) {
        esxVI_ObjectSpec_Free(&objectSpec);
    }

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

4507 4508 4509 4510
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);
    esxVI_ManagedObjectReference_Free(&propertyFilter);
    VIR_FREE(version);
    esxVI_UpdateSet_Free(&updateSet);
4511
    esxVI_TaskInfo_Free(&taskInfo);
4512 4513 4514

    return result;
}
4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527



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

4530
    memset(parsedHostCpuIdInfo, 0, sizeof(*parsedHostCpuIdInfo));
4531 4532 4533 4534 4535

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

    for (r = 0; r < 4; ++r) {
        if (strlen(input[r]) != expectedLength) {
4536 4537 4538
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("HostCpuIdInfo register '%s' has an unexpected length"),
                           name[r]);
M
Matthias Bolte 已提交
4539
            return -1;
4540 4541 4542 4543 4544 4545 4546 4547 4548 4549
        }

        /* 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] != ':') {
4550 4551 4552
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("HostCpuIdInfo register '%s' has an unexpected format"),
                               name[r]);
M
Matthias Bolte 已提交
4553
                return -1;
4554 4555 4556 4557 4558 4559
            }
        }
    }

    return 0;
}
4560 4561 4562 4563 4564 4565 4566 4567 4568



int
esxVI_ProductVersionToDefaultVirtualHWVersion(esxVI_ProductVersion productVersion)
{
    /*
     * virtualHW.version compatibility matrix:
     *
P
Patrice LACHANCE 已提交
4569 4570 4571 4572 4573 4574
     *              4 7 8   API
     *   ESX 3.5    +       2.5
     *   ESX 4.0    + +     4.0
     *   ESX 4.1    + +     4.1
     *   ESX 5.0    + + +   5.0
     *   GSX 2.0    + +     2.5
4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591
     */
    switch (productVersion) {
      case esxVI_ProductVersion_ESX35:
      case esxVI_ProductVersion_VPX25:
        return 4;

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

      case esxVI_ProductVersion_ESX4x:
      case esxVI_ProductVersion_VPX4x:
        return 7;

P
Patrice LACHANCE 已提交
4592 4593 4594 4595
      case esxVI_ProductVersion_ESX50:
      case esxVI_ProductVersion_VPX50:
        return 8;

4596
      case esxVI_ProductVersion_ESX51:
P
Patrice LACHANCE 已提交
4597
      case esxVI_ProductVersion_ESX5x:
4598
      case esxVI_ProductVersion_VPX51:
P
Patrice LACHANCE 已提交
4599 4600 4601
      case esxVI_ProductVersion_VPX5x:
        return 8;

4602
      default:
4603 4604
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unexpected product version"));
4605 4606 4607
        return -1;
    }
}
4608 4609 4610



4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625
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;
    }

4626
    if (!hostInternetScsiHba) {
4627 4628 4629 4630 4631
        /* iSCSI adapter may not be enabled for this host */
        return 0;
    }

    for (candidate = hostInternetScsiHba->configuredStaticTarget;
4632
         candidate; candidate = candidate->_next) {
4633 4634 4635 4636 4637
        if (STREQ(candidate->iScsiName, name)) {
            break;
        }
    }

4638
    if (!candidate) {
4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652
        if (occurrence == esxVI_Occurrence_RequiredItem) {
            virReportError(VIR_ERR_NO_STORAGE_POOL,
                           _("Could not find storage pool with name: %s"), name);
        }

        goto cleanup;
    }

    if (esxVI_HostInternetScsiHbaStaticTarget_DeepCopy(target, candidate) < 0) {
        goto cleanup;
    }

    result = 0;

4653
 cleanup:
4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678
    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;
    }

4679
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
4680 4681 4682 4683
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.storageDevice.hostBusAdapter")) {
            if (esxVI_HostHostBusAdapter_CastListFromAnyType
4684 4685
                (dynamicProperty->val, &hostHostBusAdapterList) < 0 ||
                !hostHostBusAdapterList) {
4686 4687 4688 4689 4690 4691 4692 4693 4694
                goto cleanup;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    /* See vSphere API documentation about HostInternetScsiHba for details */
    for (hostHostBusAdapter = hostHostBusAdapterList;
4695
         hostHostBusAdapter;
4696
         hostHostBusAdapter = hostHostBusAdapter->_next) {
4697
        esxVI_HostInternetScsiHba *candidate =
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710
            esxVI_HostInternetScsiHba_DynamicCast(hostHostBusAdapter);

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

    result = 0;

4711
 cleanup:
4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735
    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;
    }

4736
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751
         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;

4752
 cleanup:
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775
    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;

4776
    if (!hostScsiTopologyLunList || *hostScsiTopologyLunList) {
4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788
        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;
    }

4789
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812
         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;
4813
         hostScsiInterface && !found;
4814 4815
         hostScsiInterface = hostScsiInterface->_next) {
        for (hostScsiTopologyTarget = hostScsiInterface->target;
4816
             hostScsiTopologyTarget;
4817 4818 4819 4820
             hostScsiTopologyTarget = hostScsiTopologyTarget->_next) {
            candidate = esxVI_HostInternetScsiTargetTransport_DynamicCast
                          (hostScsiTopologyTarget->transport);

4821
            if (candidate && STREQ(candidate->iScsiName, name)) {
4822 4823 4824 4825 4826 4827
                found = true;
                break;
            }
        }
    }

4828
    if (!found || !hostScsiTopologyTarget) {
4829 4830 4831
        goto cleanup;
    }

4832
    if (!hostScsiTopologyTarget->lun) {
4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Target not found"));
        goto cleanup;
    }

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

    result = 0;

4845
 cleanup:
4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870
    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;

4871
    if (!poolName || *poolName) {
4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883
        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;
    }

4884
    for (dynamicProperty = hostSystem->propSet; dynamicProperty;
4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900
         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);
        }
    }

4901
    if (!hostScsiInterfaceList) {
4902 4903 4904 4905 4906 4907
        /* iSCSI adapter may not be enabled */
        return 0;
    }

    /* See vSphere API documentation about HostScsiTopologyInterface */
    for (hostScsiInterface = hostScsiInterfaceList;
4908
         hostScsiInterface && !found;
4909 4910
         hostScsiInterface = hostScsiInterface->_next) {
        for (hostScsiTopologyTarget = hostScsiInterface->target;
4911
             hostScsiTopologyTarget;
4912 4913
             hostScsiTopologyTarget = hostScsiTopologyTarget->_next) {
            candidate = esxVI_HostInternetScsiTargetTransport_DynamicCast
4914
                (hostScsiTopologyTarget->transport);
4915

4916
            if (candidate) {
4917 4918
                /* iterate hostScsiTopologyLun list to find matching key */
                for (hostScsiTopologyLun = hostScsiTopologyTarget->lun;
4919
                     hostScsiTopologyLun;
4920
                     hostScsiTopologyLun = hostScsiTopologyLun->_next) {
4921 4922 4923
                    if (STREQ(hostScsiTopologyLun->scsiLun, key) &&
                        VIR_STRDUP(*poolName, candidate->iScsiName) < 0)
                        goto cleanup;
4924 4925 4926 4927 4928 4929 4930 4931 4932 4933
                }

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

    result = 0;

4934
 cleanup:
4935 4936 4937 4938 4939 4940 4941 4942
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_String_Free(&propertyNameList);
    esxVI_HostScsiTopologyInterface_Free(&hostScsiInterfaceList);

    return result;
}


4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987

#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,                 \
4988
                                 _cast_from_anytype)                          \
4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
    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;                        \
                                                                              \
5002
        if (!ptrptr || *ptrptr) {                                             \
5003 5004
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",                      \
                           _("Invalid argument"));                            \
5005 5006 5007 5008 5009
            return -1;                                                        \
        }                                                                     \
                                                                              \
        propertyNameList = selectedPropertyNameList;                          \
                                                                              \
5010
        if (!propertyNameList &&                                              \
5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022
            esxVI_String_AppendValueListToList                                \
              (&propertyNameList, completePropertyNameValueList) < 0) {       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_LookupManagedObjectHelper(ctx, name, root, #_type,          \
                                            propertyNameList, &objectContent, \
                                            &objectContentList,               \
                                            occurrence) < 0) {                \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
5023
        if (!objectContent) {                                                 \
5024 5025 5026 5027 5028
            /* not found, exit early */                                       \
            result = 0;                                                       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
5029 5030 5031 5032 5033 5034 5035 5036 5037 5038
        if (esxVI_##_type##_Alloc(ptrptr) < 0) {                              \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_ManagedObjectReference_DeepCopy(&(*ptrptr)->_reference,     \
                                                  objectContent->obj) < 0) {  \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        for (dynamicProperty = objectContent->propSet;                        \
5039
             dynamicProperty;                                                 \
5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081
             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;

5082 5083
    if (!objectContent || *objectContent ||
        !objectContentList || *objectContentList) {
5084
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
5085 5086 5087 5088
        return -1;
    }

    if (!esxVI_String_ListContainsValue(propertyNameList, "name")) {
5089 5090
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing 'name' property in %s lookup"), type);
5091 5092 5093 5094 5095 5096 5097 5098 5099 5100
        goto cleanup;
    }

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

    /* Search for a matching item */
5101 5102
    if (name) {
        for (candidate = *objectContentList; candidate;
5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119
             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;
    }

5120
    if (!candidate) {
5121
        if (occurrence != esxVI_Occurrence_OptionalItem) {
5122
            if (name) {
5123 5124 5125 5126 5127 5128 5129
                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);
            }

5130 5131 5132 5133 5134 5135 5136 5137 5138 5139
            goto cleanup;
        }

        result = 0;

        goto cleanup;
    }

    result = 0;

5140
 cleanup:
5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152
    if (result < 0) {
        esxVI_ObjectContent_Free(objectContentList);
    } else {
        *objectContent = candidate;
    }

    return result;
}



#include "esx_vi.generated.c"