esx_vi.c 164.6 KB
Newer Older
1 2 3 4

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

#include <config.h>

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

29
#include "virbuffer.h"
30
#include "viralloc.h"
31
#include "virlog.h"
32
#include "viruuid.h"
33
#include "vmx.h"
34
#include "virxml.h"
35 36 37
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"
38
#include "virstring.h"
39 40 41 42 43 44 45 46 47 48 49 50 51

#define VIR_FROM_THIS VIR_FROM_ESX



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



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

57 58


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



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

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

85 86
/* esxVI_CURL_Free */
ESX_VI__TEMPLATE__FREE(CURL,
87
{
88
    esxVI_SharedCURL *shared = item->shared;
M
Matthias Bolte 已提交
89
    esxVI_MultiCURL *multi = item->multi;
90 91 92 93 94 95 96 97 98

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

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

M
Matthias Bolte 已提交
99 100 101 102 103 104 105 106
    if (multi != NULL) {
        esxVI_MultiCURL_Remove(multi, item);

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

107 108
    if (item->handle != NULL) {
        curl_easy_cleanup(item->handle);
109 110
    }

111 112
    if (item->headers != NULL) {
        curl_slist_free_all(item->headers);
113 114
    }

115 116
    virMutexDestroy(&item->lock);
})
117 118

static size_t
119
esxVI_CURL_ReadString(char *data, size_t size, size_t nmemb, void *userdata)
M
Matthias Bolte 已提交
120
{
121
    const char *content = *(const char **)userdata;
M
Matthias Bolte 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    size_t available = 0;
    size_t requested = size * nmemb;

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

    available = strlen(content);

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

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

    memcpy(data, content, requested);

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

    return requested;
}

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

151
    if (buffer != NULL) {
152 153 154 155 156 157 158 159 160 161 162
        /*
         * 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);
163 164 165 166 167 168 169 170 171 172 173

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

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

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

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

        VIR_DEBUG("CURLINFO_TEXT [[[[%s]]]]", buffer);
205 206 207
        break;

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

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

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

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

      default:
224
        VIR_DEBUG("unknown");
225 226 227
        break;
    }

228 229
    VIR_FREE(buffer);

230 231 232 233
    return 0;
}
#endif

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

243
    errorCode = curl_easy_perform(curl->handle);
244 245

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

252
    errorCode = curl_easy_getinfo(curl->handle, CURLINFO_RESPONSE_CODE,
253 254 255
                                  &responseCode);

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

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

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

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

        return -1;
    }

    return responseCode;
}

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

305
    curl->handle = curl_easy_init();
306

307
    if (curl->handle == NULL) {
308 309
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize CURL"));
310
        return -1;
311 312
    }

313 314
    curl->headers = curl_slist_append(curl->headers,
                                      "Content-Type: text/xml; charset=UTF-8");
315 316

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

326
    if (curl->headers == NULL) {
327 328
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not build CURL header list"));
329
        return -1;
330 331
    }

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

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

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

367 368
    return 0;
}
369

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

    if (content == NULL || *content != NULL) {
379
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
380 381 382
        return -1;
    }

383 384 385 386 387 388 389
    if (length != NULL && *length > 0) {
        /*
         * 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) {
390 391
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Download length it too large"));
392 393 394 395 396 397 398 399 400 401 402 403 404 405
            return -1;
        }

        if (virAsprintf(&range, "%llu-%llu", offset, offset + *length - 1) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    } else if (offset > 0) {
        if (virAsprintf(&range, "%llu-", offset) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

406 407 408
    virMutexLock(&curl->lock);

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

    if (virBufferError(&buffer)) {
428
        virReportOOMError();
429 430 431
        goto cleanup;
    }

432 433 434 435
    if (length != NULL) {
        *length = virBufferUse(&buffer);
    }

436 437 438
    *content = virBufferContentAndReset(&buffer);

  cleanup:
439 440
    VIR_FREE(range);

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

    return 0;
}

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

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

    virMutexLock(&curl->lock);

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

    return 0;
}



485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * SharedCURL
 */

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

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

      case CURL_LOCK_DATA_COOKIE:
        i = 1;
        break;

      case CURL_LOCK_DATA_DNS:
        i = 2;
        break;

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

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

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

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

      case CURL_LOCK_DATA_COOKIE:
        i = 1;
        break;

      case CURL_LOCK_DATA_DNS:
        i = 2;
        break;

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

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

/* esxVI_SharedCURL_Alloc */
ESX_VI__TEMPLATE__ALLOC(SharedCURL)

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

    if (item->count > 0) {
        /* Better leak than crash */
555
        VIR_ERROR(_("Trying to free SharedCURL object that is still in use"));
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        return;
    }

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

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

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

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

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

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

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

M
Matthias Bolte 已提交
613 614
    virMutexLock(&curl->lock);

615 616 617 618 619
    curl_easy_setopt(curl->handle, CURLOPT_SHARE, shared->handle);

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

M
Matthias Bolte 已提交
620 621
    virMutexUnlock(&curl->lock);

622 623 624 625 626 627 628
    return 0;
}

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

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

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

M
Matthias Bolte 已提交
645 646
    virMutexLock(&curl->lock);

647 648 649 650 651
    curl_easy_setopt(curl->handle, CURLOPT_SHARE, NULL);

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

M
Matthias Bolte 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    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;
    }

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

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

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

    if (multi->handle == NULL) {
        multi->handle = curl_multi_init();

        if (multi->handle == NULL) {
699 700
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not initialize CURL (multi)"));
M
Matthias Bolte 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
            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)
{
    if (curl->handle == NULL) {
721 722 723
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot remove uninitialized CURL handle from a "
                         "multi handle"));
M
Matthias Bolte 已提交
724 725 726 727
        return -1;
    }

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

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

    virMutexLock(&curl->lock);

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

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

    virMutexUnlock(&curl->lock);

748 749 750 751 752
    return 0;
}



753 754 755 756 757 758 759 760 761 762
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Context
 */

/* esxVI_Context_Alloc */
ESX_VI__TEMPLATE__ALLOC(Context)

/* esxVI_Context_Free */
ESX_VI__TEMPLATE__FREE(Context,
{
763 764 765 766
    if (item->sessionLock != NULL) {
        virMutexDestroy(item->sessionLock);
    }

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

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

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

811 812 813 814 815 816
    if (VIR_ALLOC(ctx->sessionLock) < 0) {
        virReportOOMError();
        return -1;
    }

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

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

826 827 828
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
829
            ctx->apiVersion = esxVI_APIVersion_25;
830
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
831
            ctx->apiVersion = esxVI_APIVersion_40;
M
Matthias Bolte 已提交
832 833 834 835
        } 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 已提交
836 837
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.0")) {
            ctx->apiVersion = esxVI_APIVersion_50;
838 839
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.1")) {
            ctx->apiVersion = esxVI_APIVersion_51;
P
Patrice LACHANCE 已提交
840 841
        } else if (STRPREFIX(ctx->service->about->apiVersion, "5.")) {
            ctx->apiVersion = esxVI_APIVersion_5x;
842
        } else {
843 844 845
            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);
846
            return -1;
847
        }
848

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

917 918 919 920 921 922 923 924 925 926 927
    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;
    }

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

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

937 938 939 940
    return 0;
}

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

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

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

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

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

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

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

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

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

    if (item == NULL) {
1001 1002
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' does not specify a datacenter"), path);
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 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 1043 1044
        goto cleanup;
    }

    root = ctx->service->rootFolder;

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

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

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

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

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

        virBufferAdd(&buffer, item, -1);

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

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

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

    ctx->datacenterPath = virBufferContentAndReset(&buffer);

    /* Lookup (Cluster)ComputeResource */
    if (item == NULL) {
1059 1060
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Path '%s' does not specify a compute resource"), path);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
        goto cleanup;
    }

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

    root = ctx->datacenter->hostFolder;

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

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

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

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

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

        virBufferAdd(&buffer, item, -1);

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

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

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

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

    ctx->computeResourcePath = virBufferContentAndReset(&buffer);

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

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

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

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

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

1157
    if (ctx->hostSystem == NULL) {
1158 1159
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find host system specified in '%s'"), path);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        goto cleanup;
    }

    result = 0;

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

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

    VIR_FREE(tmp);
    esxVI_Folder_Free(&folder);

    return result;
1179 1180 1181
}

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

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

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

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

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

    result = 0;

  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
1221 1222 1223 1224 1225

    return result;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1323
            responseNode = virXPathNode(xpathExpression, xpathContext);
1324

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

1332
            xpathContext->node = responseNode;
1333
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
1334

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

                break;

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

                break;

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

                break;

1372
              case esxVI_Occurrence_OptionalList:
1373 1374 1375 1376 1377
                /* Any amount of items is valid */
                break;

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

                break;

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

M
Matthias Bolte 已提交
1399 1400
    result = 0;

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

1408 1409 1410 1411
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
1412 1413 1414 1415 1416
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1417
 * Response
1418 1419
 */

1420
/* esxVI_Response_Alloc */
1421
ESX_VI__TEMPLATE__ALLOC(Response)
1422

1423 1424
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
1425
{
1426
    VIR_FREE(item->content);
1427

1428
    xmlFreeDoc(item->document);
1429
})
1430 1431 1432 1433 1434 1435 1436 1437



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

int
1438
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
1439 1440 1441 1442 1443
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
1444
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1445 1446 1447 1448 1449
        return -1;
    }

    *value = 0; /* undefined */

1450
    if (anyType->type != enumeration->type) {
1451 1452 1453
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Expecting type '%s' but found '%s'"),
                       esxVI_Type_ToString(enumeration->type),
1454
                       esxVI_AnyType_TypeToString(anyType));
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        return -1;
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(anyType->value, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
            return 0;
        }
    }

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

    return -1;
}

int
1473
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
1474
                            int value, const char *element, virBufferPtr output)
1475 1476 1477 1478 1479
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
1480
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1481 1482 1483 1484
        return -1;
    }

    if (value == 0) { /* undefined */
1485
        return 0;
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    }

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

    if (name == NULL) {
1496
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1497 1498 1499
        return -1;
    }

1500 1501
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
1502 1503 1504 1505 1506 1507 1508 1509 1510

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

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

    if (value == NULL) {
1519
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1520
        return -1;
1521 1522 1523 1524
    }

    *value = 0; /* undefined */

1525
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
M
Matthias Bolte 已提交
1526
        return -1;
1527 1528 1529 1530 1531
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(name, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
M
Matthias Bolte 已提交
1532 1533
            result = 0;
            break;
1534 1535 1536
        }
    }

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

    VIR_FREE(name);

    return result;
}



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

int
1554
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
1555 1556 1557 1558
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
1559
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
        return -1;
    }

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

    next = *list;

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

    next->_next = item;

    return 0;
}

int
1580
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
1581 1582 1583 1584 1585 1586 1587
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
1588
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1589
        return -1;
1590 1591 1592
    }

    for (src = srcList; src != NULL; src = src->_next) {
1593 1594
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
            goto failure;
        }

        dest = NULL;
    }

    return 0;

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

    return -1;
}

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

    if (list == NULL || *list != NULL ||
        castFromAnyTypeFunc == NULL || freeFunc == NULL) {
1622
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1623
        return -1;
1624 1625 1626 1627 1628 1629 1630
    }

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

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

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

        esxVI_AnyType_Free(&childAnyType);

1647 1648 1649
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
M
Matthias Bolte 已提交
1650
            goto cleanup;
1651 1652 1653 1654 1655
        }

        item = NULL;
    }

M
Matthias Bolte 已提交
1656 1657
    result = 0;

1658
  cleanup:
M
Matthias Bolte 已提交
1659 1660 1661 1662 1663
    if (result < 0) {
        freeFunc(&item);
        freeFunc(list);
    }

1664 1665 1666 1667 1668
    esxVI_AnyType_Free(&childAnyType);

    return result;
}

1669
int
1670
esxVI_List_Serialize(esxVI_List *list, const char *element,
1671
                     virBufferPtr output,
1672 1673 1674 1675 1676
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
1677
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1678 1679 1680 1681
        return -1;
    }

    if (list == NULL) {
1682
        return 0;
1683 1684 1685
    }

    for (item = list; item != NULL; item = item->_next) {
1686
        if (serializeFunc(item, element, output) < 0) {
1687 1688 1689 1690 1691 1692 1693 1694
            return -1;
        }
    }

    return 0;
}

int
1695
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1696 1697 1698 1699 1700 1701 1702
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
1703
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1704 1705 1706 1707 1708 1709 1710 1711 1712
        return -1;
    }

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

    for (; node != NULL; node = node->next) {
        if (node->type != XML_ELEMENT_NODE) {
1713 1714
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Wrong XML element type %d"), node->type);
1715 1716 1717
            goto failure;
        }

1718 1719
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1720 1721 1722
            goto failure;
        }

1723
        item = NULL;
1724 1725 1726 1727 1728
    }

    return 0;

  failure:
1729
    freeFunc(&item);
1730 1731 1732 1733 1734 1735 1736 1737 1738
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1739 1740 1741 1742
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1743 1744 1745
 */

int
1746
esxVI_Alloc(void **ptrptr, size_t size)
1747 1748
{
    if (ptrptr == NULL || *ptrptr != NULL) {
1749
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1750 1751 1752
        return -1;
    }

1753
    if (virAllocN(ptrptr, size, 1, false, 0, NULL, NULL, 0) < 0) {
1754
        virReportOOMError();
1755 1756 1757 1758 1759 1760
        return -1;
    }

    return 0;
}

1761 1762


1763
int
1764 1765 1766
esxVI_BuildSelectSet(esxVI_SelectionSpec **selectSet,
                     const char *name, const char *type,
                     const char *path, const char *selectSetNames)
1767 1768 1769 1770 1771
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

1772 1773 1774 1775 1776
    if (selectSet == NULL) {
        /*
         * Don't check for *selectSet != NULL here because selectSet is a list
         * and might contain items already. This function appends to selectSet.
         */
1777
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1778 1779 1780
        return -1;
    }

1781
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1782 1783 1784
        VIR_STRDUP(traversalSpec->name, name) < 0 ||
        VIR_STRDUP(traversalSpec->type, type) < 0 ||
        VIR_STRDUP(traversalSpec->path, path) < 0) {
1785 1786 1787 1788 1789 1790 1791 1792 1793
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

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

        while (currentSelectSetName != NULL && *currentSelectSetName != '\0') {
1794
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
1795
                VIR_STRDUP(selectionSpec->name, currentSelectSetName) < 0 ||
1796
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1797 1798 1799 1800
                                                 selectionSpec) < 0) {
                goto failure;
            }

1801
            selectionSpec = NULL;
1802 1803 1804 1805
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1806
    if (esxVI_SelectionSpec_AppendToList(selectSet,
1807 1808
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1809 1810 1811 1812 1813 1814 1815
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);
1816
    esxVI_SelectionSpec_Free(&selectionSpec);
1817 1818 1819 1820 1821

    return -1;
}


1822

1823
int
1824
esxVI_BuildSelectSetCollection(esxVI_Context *ctx)
1825
{
1826
    /* Folder -> childEntity (ManagedEntity) */
1827 1828
    if (esxVI_BuildSelectSet(&ctx->selectSet_folderToChildEntity,
                             "folderToChildEntity",
1829
                             "Folder", "childEntity", NULL) < 0) {
1830
        return -1;
1831 1832
    }

1833
    /* ComputeResource -> host (HostSystem) */
1834 1835 1836 1837
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToHost,
                             "computeResourceToHost",
                             "ComputeResource", "host", NULL) < 0) {
        return -1;
1838 1839
    }

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
    /* 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;
    }*/
1855

1856 1857 1858 1859 1860 1861
    /* ResourcePool -> vm (VirtualMachine) *//*
    if (esxVI_BuildSelectSet(&ctx->selectSet_resourcePoolToVm,
                             "resourcePoolToVm",
                             "ResourcePool", "vm", NULL) < 0) {
        return -1;
    }*/
1862

1863
    /* HostSystem -> parent (ComputeResource) */
1864 1865 1866 1867
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToParent,
                             "hostSystemToParent",
                             "HostSystem", "parent", NULL) < 0) {
        return -1;
1868 1869
    }

1870
    /* HostSystem -> vm (VirtualMachine) */
1871 1872 1873 1874
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToVm,
                             "hostSystemToVm",
                             "HostSystem", "vm", NULL) < 0) {
        return -1;
1875 1876
    }

1877
    /* HostSystem -> datastore (Datastore) */
1878 1879 1880 1881
    if (esxVI_BuildSelectSet(&ctx->selectSet_hostSystemToDatastore,
                             "hostSystemToDatastore",
                             "HostSystem", "datastore", NULL) < 0) {
        return -1;
1882 1883
    }

1884 1885 1886 1887 1888 1889
    /* Folder -> parent (Folder, Datacenter) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "managedEntityToParent",
                             "ManagedEntity", "parent", NULL) < 0) {
        return -1;
    }
1890

1891 1892 1893 1894 1895 1896 1897
    /* ComputeResource -> parent (Folder) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_computeResourceToParentToParent,
                             "computeResourceToParent",
                             "ComputeResource", "parent",
                             "managedEntityToParent\0") < 0) {
        return -1;
    }
1898

M
Matthias Bolte 已提交
1899 1900 1901 1902 1903 1904 1905
    /* Datacenter -> network (Network) */
    if (esxVI_BuildSelectSet(&ctx->selectSet_datacenterToNetwork,
                             "datacenterToNetwork",
                             "Datacenter", "network", NULL) < 0) {
        return -1;
    }

1906
    return 0;
1907 1908 1909 1910 1911
}



int
1912
esxVI_EnsureSession(esxVI_Context *ctx)
1913
{
M
Matthias Bolte 已提交
1914
    int result = -1;
1915
    esxVI_Boolean active = esxVI_Boolean_Undefined;
1916 1917 1918 1919 1920
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;

1921
    if (ctx->sessionLock == NULL) {
1922
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no mutex"));
1923 1924 1925
        return -1;
    }

1926 1927 1928
    virMutexLock(ctx->sessionLock);

    if (ctx->session == NULL) {
1929
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call, no session"));
1930 1931 1932
        goto cleanup;
    }

1933 1934 1935
    if (ctx->hasSessionIsActive) {
        /*
         * Use SessionIsActive to check if there is an active session for this
E
Eric Blake 已提交
1936
         * connection, and re-login if there isn't.
1937 1938 1939
         */
        if (esxVI_SessionIsActive(ctx, ctx->session->key,
                                  ctx->session->userName, &active) < 0) {
1940
            goto cleanup;
1941
        }
1942

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

1946 1947
            if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                            &ctx->session) < 0) {
1948
                goto cleanup;
1949
            }
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
        }
    } 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,
1960 1961
                                            &sessionManager,
                                            esxVI_Occurrence_RequiredItem) < 0) {
1962
            goto cleanup;
1963 1964
        }

1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
        for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "currentSession")) {
                if (esxVI_UserSession_CastFromAnyType(dynamicProperty->val,
                                                      &currentSession) < 0) {
                    goto cleanup;
                }

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

1979 1980 1981 1982 1983 1984 1985 1986
        if (currentSession == NULL) {
            esxVI_UserSession_Free(&ctx->session);

            if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                            &ctx->session) < 0) {
                goto cleanup;
            }
        } else if (STRNEQ(ctx->session->key, currentSession->key)) {
1987 1988 1989
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Key of the current session differs from the key at "
                             "last login"));
M
Matthias Bolte 已提交
1990
            goto cleanup;
1991
        }
1992
    }
1993

1994
    result = 0;
M
Matthias Bolte 已提交
1995

1996
  cleanup:
1997
    virMutexUnlock(ctx->sessionLock);
1998

1999 2000 2001 2002 2003
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);

    return result;
2004 2005 2006 2007 2008
}



int
2009
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
2010 2011 2012
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
2013 2014
                                esxVI_ObjectContent **objectContentList,
                                esxVI_Occurrence occurrence)
2015
{
M
Matthias Bolte 已提交
2016
    int result = -1;
2017
    esxVI_ObjectSpec *objectSpec = NULL;
2018
    bool objectSpec_isAppended = false;
2019
    esxVI_PropertySpec *propertySpec = NULL;
2020
    bool propertySpec_isAppended = false;
2021 2022
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

2023
    if (objectContentList == NULL || *objectContentList != NULL) {
2024
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2025 2026 2027
        return -1;
    }

2028
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
2029
        return -1;
2030 2031 2032 2033 2034
    }

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

2035
    if (STRNEQ(root->type, type) || STREQ(root->type, "Folder")) {
2036
        if (STREQ(root->type, "Folder")) {
2037 2038
            if (STREQ(type, "Folder") || STREQ(type, "Datacenter") ||
                STREQ(type, "ComputeResource") ||
2039
                STREQ(type, "ClusterComputeResource")) {
2040 2041
                objectSpec->selectSet = ctx->selectSet_folderToChildEntity;
            } else {
2042 2043 2044
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2045 2046
                goto cleanup;
            }
2047 2048
        } else if (STREQ(root->type, "ComputeResource") ||
                   STREQ(root->type, "ClusterComputeResource")) {
2049 2050 2051 2052 2053
            if (STREQ(type, "HostSystem")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToHost;
            } else if (STREQ(type, "Datacenter")) {
                objectSpec->selectSet = ctx->selectSet_computeResourceToParentToParent;
            } else {
2054 2055 2056
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2057 2058 2059
                goto cleanup;
            }
        } else if (STREQ(root->type, "HostSystem")) {
2060 2061
            if (STREQ(type, "ComputeResource") ||
                STREQ(type, "ClusterComputeResource")) {
2062 2063 2064 2065 2066 2067
                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 {
2068 2069 2070
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Invalid lookup of '%s' from '%s'"),
                               type, root->type);
2071 2072
                goto cleanup;
            }
M
Matthias Bolte 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081
        } 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;
            }
2082
        } else {
2083 2084
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid lookup from '%s'"), root->type);
2085 2086
            goto cleanup;
        }
2087 2088
    }

2089
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
2090
        goto cleanup;
2091 2092 2093 2094 2095
    }

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

2096 2097
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
                                        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,
2112 2113 2114 2115
                                 objectContentList) < 0) {
        goto cleanup;
    }

E
Eric Blake 已提交
2116
    if (*objectContentList == NULL) {
2117 2118 2119 2120 2121 2122 2123
        switch (occurrence) {
          case esxVI_Occurrence_OptionalItem:
          case esxVI_Occurrence_OptionalList:
            result = 0;
            break;

          case esxVI_Occurrence_RequiredItem:
2124 2125 2126
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not lookup '%s' from '%s'"),
                           type, root->type);
2127 2128 2129
            break;

          case esxVI_Occurrence_RequiredList:
2130 2131 2132
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not lookup '%s' list from '%s'"),
                           type, root->type);
2133 2134 2135
            break;

          default:
2136 2137
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Invalid occurrence value"));
2138 2139 2140
            break;
        }

M
Matthias Bolte 已提交
2141
        goto cleanup;
2142 2143
    }

2144
    result = 0;
2145 2146 2147 2148 2149

  cleanup:
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
2150
     * objectSpec cannot be NULL here.
2151
     */
2152 2153
    objectSpec->obj = NULL;
    objectSpec->selectSet = NULL;
2154

2155 2156 2157 2158 2159
    if (propertySpec != NULL) {
        propertySpec->type = NULL;
        propertySpec->pathSet = NULL;
    }

2160 2161 2162 2163 2164 2165 2166 2167
    if (!objectSpec_isAppended) {
        esxVI_ObjectSpec_Free(&objectSpec);
    }

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

2168 2169 2170 2171 2172 2173 2174
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);

    return result;
}



2175
int
2176
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
2177 2178 2179 2180 2181 2182 2183 2184 2185
                             const char *propertyName,
                             esxVI_ManagedEntityStatus *managedEntityStatus)
{
    esxVI_DynamicProperty *dynamicProperty;

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            return esxVI_ManagedEntityStatus_CastFromAnyType
2186
                     (dynamicProperty->val, managedEntityStatus);
2187 2188 2189
        }
    }

2190 2191 2192
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Missing '%s' property while looking for "
                     "ManagedEntityStatus"), propertyName);
2193 2194 2195 2196 2197 2198

    return -1;
}



2199
int
2200
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
2201 2202 2203 2204 2205 2206 2207 2208
                                  esxVI_VirtualMachinePowerState *powerState)
{
    esxVI_DynamicProperty *dynamicProperty;

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            return esxVI_VirtualMachinePowerState_CastFromAnyType
2209
                     (dynamicProperty->val, powerState);
2210 2211 2212
        }
    }

2213 2214
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Missing 'runtime.powerState' property"));
2215 2216 2217 2218 2219 2220

    return -1;
}



2221 2222
int
esxVI_GetVirtualMachineQuestionInfo
2223
  (esxVI_ObjectContent *virtualMachine,
2224 2225 2226 2227 2228
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (questionInfo == NULL || *questionInfo != NULL) {
2229
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2230 2231 2232 2233 2234 2235 2236
        return -1;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
2237
                  (dynamicProperty->val, questionInfo) < 0) {
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
                return -1;
            }
        }
    }

    return 0;
}



2248 2249
int
esxVI_GetBoolean(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2250
                 esxVI_Boolean *value, esxVI_Occurrence occurrence)
2251 2252 2253 2254
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != esxVI_Boolean_Undefined) {
2255
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
        return -1;
    }

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

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

    if (*value == esxVI_Boolean_Undefined &&
M
Matthias Bolte 已提交
2273
        occurrence == esxVI_Occurrence_RequiredItem) {
2274 2275
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2276 2277 2278 2279 2280 2281
        return -1;
    }

    return 0;
}

M
Matthias Bolte 已提交
2282 2283


2284 2285
int
esxVI_GetLong(esxVI_ObjectContent *objectContent, const char *propertyName,
M
Matthias Bolte 已提交
2286
              esxVI_Long **value, esxVI_Occurrence occurrence)
2287 2288 2289 2290
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
2291
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
        return -1;
    }

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

            break;
        }
    }

M
Matthias Bolte 已提交
2306
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
2307 2308
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2309 2310 2311 2312 2313 2314
        return -1;
    }

    return 0;
}

2315 2316 2317 2318 2319


int
esxVI_GetStringValue(esxVI_ObjectContent *objectContent,
                     const char *propertyName,
M
Matthias Bolte 已提交
2320
                     char **value, esxVI_Occurrence occurrence)
2321 2322 2323 2324
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
2325
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
        return -1;
    }

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

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

M
Matthias Bolte 已提交
2342
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
2343 2344
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
        return -1;
    }

    return 0;
}



int
esxVI_GetManagedObjectReference(esxVI_ObjectContent *objectContent,
                                const char *propertyName,
                                esxVI_ManagedObjectReference **value,
M
Matthias Bolte 已提交
2357
                                esxVI_Occurrence occurrence)
2358 2359 2360 2361
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
2362
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
        return -1;
    }

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

            break;
        }
    }

M
Matthias Bolte 已提交
2378
    if (*value == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
2379 2380
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing '%s' property"), propertyName);
2381 2382 2383 2384 2385 2386 2387 2388
        return -1;
    }

    return 0;
}



2389
int
2390
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
2391
                                        esxVI_VirtualMachinePowerState powerState,
2392
                                        bool inverse)
2393
{
M
Matthias Bolte 已提交
2394
    bool success = false;
2395 2396 2397 2398 2399
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
M
Matthias Bolte 已提交
2400
    int count = 0;
2401

2402
    if (esxVI_String_AppendValueToList(&propertyNameList,
2403
                                       "runtime.powerState") < 0 ||
2404 2405
        esxVI_LookupVirtualMachineList(ctx, propertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2406
        goto cleanup;
2407 2408 2409 2410 2411 2412 2413 2414 2415
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "runtime.powerState")) {
                if (esxVI_VirtualMachinePowerState_CastFromAnyType
2416
                      (dynamicProperty->val, &powerState_) < 0) {
M
Matthias Bolte 已提交
2417
                    goto cleanup;
2418 2419
                }

2420
                if ((!inverse && powerState_ == powerState) ||
2421
                    (inverse && powerState_ != powerState)) {
M
Matthias Bolte 已提交
2422
                    count++;
2423 2424 2425 2426 2427 2428 2429
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

M
Matthias Bolte 已提交
2430 2431
    success = true;

2432 2433 2434 2435
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
2436
    return success ? count : -1;
2437 2438 2439 2440 2441
}



int
2442
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
2443 2444 2445 2446
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
2447
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
2448 2449

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
2450 2451
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("ObjectContent does not reference a virtual machine"));
2452 2453 2454 2455 2456 2457
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
2458 2459 2460
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse positive integer from '%s'"),
                           virtualMachine->obj->value);
2461 2462 2463 2464 2465 2466
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
2467
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2468 2469 2470 2471 2472 2473 2474
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
2475
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2476 2477 2478 2479
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

2480
                if (VIR_STRDUP(*name, dynamicProperty->val->string) < 0)
2481 2482
                    goto failure;

2483
                if (virVMXUnescapeHexPercent(*name) < 0) {
2484 2485
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Domain name contains invalid escape sequence"));
2486 2487 2488
                    goto failure;
                }

2489 2490 2491 2492 2493
                break;
            }
        }

        if (*name == NULL) {
2494 2495
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not get name of virtual machine"));
2496 2497 2498 2499 2500
            goto failure;
        }
    }

    if (uuid != NULL) {
2501
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
2502 2503 2504 2505 2506 2507 2508 2509 2510
                                         &configStatus) < 0) {
            goto failure;
        }

        if (configStatus == esxVI_ManagedEntityStatus_Green) {
            for (dynamicProperty = virtualMachine->propSet;
                 dynamicProperty != NULL;
                 dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "config.uuid")) {
2511
                    if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2512 2513 2514 2515 2516 2517
                                                 esxVI_Type_String) < 0) {
                        goto failure;
                    }

                    uuid_string = dynamicProperty->val->string;
                    break;
2518
                }
2519
            }
2520

2521
            if (uuid_string == NULL) {
2522 2523
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Could not get UUID of virtual machine"));
2524
                goto failure;
2525 2526
            }

2527
            if (virUUIDParse(uuid_string, uuid) < 0) {
2528 2529 2530
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Could not parse UUID from string '%s'"),
                               uuid_string);
2531 2532 2533 2534
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
2535

2536
            VIR_WARN("Cannot access UUID, because 'configStatus' property "
2537
                      "indicates a config problem");
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
        }
    }

    return 0;

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

    return -1;
}



2553 2554
int
esxVI_GetNumberOfSnapshotTrees
2555 2556
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList, bool recurse,
   bool leaves)
2557 2558 2559 2560 2561 2562
{
    int count = 0;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList; snapshotTree != NULL;
         snapshotTree = snapshotTree->_next) {
2563 2564
        if (!(leaves && snapshotTree->childSnapshotList))
            count++;
2565 2566
        if (recurse)
            count += esxVI_GetNumberOfSnapshotTrees
2567
                (snapshotTree->childSnapshotList, true, leaves);
2568 2569 2570 2571 2572 2573 2574 2575 2576
    }

    return count;
}



int
esxVI_GetSnapshotTreeNames(esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
2577 2578
                           char **names, int nameslen, bool recurse,
                           bool leaves)
2579 2580 2581 2582 2583 2584 2585 2586 2587
{
    int count = 0;
    int result;
    int i;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList;
         snapshotTree != NULL && count < nameslen;
         snapshotTree = snapshotTree->_next) {
2588
        if (!(leaves && snapshotTree->childSnapshotList)) {
2589
            if (VIR_STRDUP(names[count], snapshotTree->name) < 0)
2590
                goto failure;
2591

2592 2593
            count++;
        }
2594 2595 2596 2597 2598

        if (count >= nameslen) {
            break;
        }

2599 2600 2601 2602
        if (recurse) {
            result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
                                                names + count,
                                                nameslen - count,
2603
                                                true, leaves);
2604

2605 2606 2607
            if (result < 0) {
                goto failure;
            }
2608

2609 2610
            count += result;
        }
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
    }

    return count;

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

    return -1;
}



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

    if (snapshotTree == NULL || *snapshotTree != NULL ||
2635
        (snapshotTreeParent && *snapshotTreeParent != NULL)) {
2636
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2637 2638 2639 2640 2641 2642 2643
        return -1;
    }

    for (candidate = snapshotTreeList; candidate != NULL;
         candidate = candidate->_next) {
        if (STREQ(candidate->name, name)) {
            *snapshotTree = candidate;
2644 2645
            if (snapshotTreeParent)
                *snapshotTreeParent = NULL;
2646 2647 2648 2649 2650 2651
            return 1;
        }

        if (esxVI_GetSnapshotTreeByName(candidate->childSnapshotList, name,
                                        snapshotTree, snapshotTreeParent,
                                        occurrence) > 0) {
2652
            if (snapshotTreeParent && *snapshotTreeParent == NULL) {
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
                *snapshotTreeParent = candidate;
            }

            return 1;
        }
    }

    if (occurrence == esxVI_Occurrence_OptionalItem) {
        return 0;
    } else {
2663 2664
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("Could not find snapshot with name '%s'"), name);
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680

        return -1;
    }
}



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

    if (snapshotTree == NULL || *snapshotTree != NULL) {
2681
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
        return -1;
    }

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

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

2698 2699 2700
    virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                   _("Could not find domain snapshot with internal name '%s'"),
                   snapshot->value);
2701 2702 2703 2704 2705 2706

    return -1;
}



M
Matthias Bolte 已提交
2707 2708 2709 2710
int
esxVI_LookupHostSystemProperties(esxVI_Context *ctx,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **hostSystem)
M
Matthias Bolte 已提交
2711
{
2712 2713
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "HostSystem", propertyNameList,
2714 2715
                                           hostSystem,
                                           esxVI_Occurrence_RequiredItem);
M
Matthias Bolte 已提交
2716 2717 2718 2719
}



2720
int
2721 2722 2723
esxVI_LookupVirtualMachineList(esxVI_Context *ctx,
                               esxVI_String *propertyNameList,
                               esxVI_ObjectContent **virtualMachineList)
2724
{
2725 2726 2727 2728
    /* FIXME: Switch from ctx->hostSystem to ctx->computeResource->resourcePool
     *        for cluster support */
    return esxVI_LookupObjectContentByType(ctx, ctx->hostSystem->_reference,
                                           "VirtualMachine", propertyNameList,
2729 2730
                                           virtualMachineList,
                                           esxVI_Occurrence_OptionalList);
2731 2732 2733 2734 2735
}



int
2736
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
2737
                                 esxVI_String *propertyNameList,
2738
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
2739
                                 esxVI_Occurrence occurrence)
2740
{
M
Matthias Bolte 已提交
2741
    int result = -1;
2742
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
2743
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
2744 2745

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2746
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2747 2748 2749
        return -1;
    }

2750 2751
    virUUIDFormat(uuid, uuid_string);

2752
    if (esxVI_FindByUuid(ctx, ctx->datacenter->_reference, uuid_string,
2753 2754
                         esxVI_Boolean_True, esxVI_Boolean_Undefined,
                         &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2755
        return -1;
2756 2757
    }

2758
    if (managedObjectReference == NULL) {
M
Matthias Bolte 已提交
2759
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2760 2761 2762
            result = 0;

            goto cleanup;
2763
        } else {
2764 2765 2766
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("Could not find domain with UUID '%s'"),
                           uuid_string);
M
Matthias Bolte 已提交
2767
            goto cleanup;
2768 2769 2770
        }
    }

2771
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2772
                                        "VirtualMachine", propertyNameList,
2773 2774
                                        virtualMachine,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2775
        goto cleanup;
2776 2777
    }

M
Matthias Bolte 已提交
2778 2779
    result = 0;

2780 2781 2782 2783
  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
M
Matthias Bolte 已提交
2784 2785 2786 2787
}



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

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2801
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2802 2803 2804 2805 2806 2807
        return -1;
    }

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
2808 2809
        esxVI_LookupVirtualMachineList(ctx, completePropertyNameList,
                                       &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2810
        goto cleanup;
2811 2812 2813 2814 2815 2816 2817 2818
    }

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

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
M
Matthias Bolte 已提交
2819
            goto cleanup;
2820 2821 2822 2823 2824 2825 2826
        }

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

        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0) {
M
Matthias Bolte 已提交
2827
            goto cleanup;
2828 2829 2830 2831 2832 2833 2834
        }

        break;
    }

    if (*virtualMachine == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2835 2836 2837
            result = 0;

            goto cleanup;
2838
        } else {
2839 2840
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("Could not find domain with name '%s'"), name);
M
Matthias Bolte 已提交
2841
            goto cleanup;
2842 2843 2844
        }
    }

M
Matthias Bolte 已提交
2845 2846
    result = 0;

2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;
}



2857 2858
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2859
  (esxVI_Context *ctx, const unsigned char *uuid,
2860
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
2861
   bool autoAnswer)
2862
{
M
Matthias Bolte 已提交
2863
    int result = -1;
2864 2865 2866
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;
2867
    bool blocked;
2868

2869
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2870
                                  propertyNameList) < 0 ||
2871
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2872 2873
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2874
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2875
                                         virtualMachine,
M
Matthias Bolte 已提交
2876
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2877
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
2878 2879
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
2880
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
M
Matthias Bolte 已提交
2881
        goto cleanup;
2882 2883 2884
    }

    if (questionInfo != NULL &&
2885
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
2886 2887
                                           questionInfo, autoAnswer,
                                           &blocked) < 0) {
M
Matthias Bolte 已提交
2888
        goto cleanup;
2889 2890 2891
    }

    if (pendingTaskInfoList != NULL) {
2892 2893
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Other tasks are pending for this domain"));
M
Matthias Bolte 已提交
2894
        goto cleanup;
2895 2896
    }

M
Matthias Bolte 已提交
2897 2898
    result = 0;

2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;
}



2909 2910 2911 2912 2913 2914 2915 2916
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,
2917 2918
                                           datastoreList,
                                           esxVI_Occurrence_OptionalList);
2919 2920 2921 2922
}



M
Matthias Bolte 已提交
2923
int
2924 2925
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
2926
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
2927
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
2928
{
M
Matthias Bolte 已提交
2929
    int result = -1;
M
Matthias Bolte 已提交
2930 2931 2932
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
2933
    char *name_candidate;
M
Matthias Bolte 已提交
2934 2935

    if (datastore == NULL || *datastore != NULL) {
2936
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
2937 2938 2939 2940
        return -1;
    }

    /* Get all datastores */
2941
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
2942
                                  propertyNameList) < 0 ||
2943 2944
        esxVI_String_AppendValueToList(&completePropertyNameList,
                                       "summary.name") < 0 ||
2945 2946
        esxVI_LookupDatastoreList(ctx, completePropertyNameList,
                                  &datastoreList) < 0) {
M
Matthias Bolte 已提交
2947
        goto cleanup;
M
Matthias Bolte 已提交
2948 2949
    }

2950 2951 2952 2953 2954 2955 2956
    /* Search for a matching datastore */
    for (candidate = datastoreList; candidate != NULL;
         candidate = candidate->_next) {
        name_candidate = NULL;

        if (esxVI_GetStringValue(candidate, "summary.name", &name_candidate,
                                 esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2957
            goto cleanup;
M
Matthias Bolte 已提交
2958
        }
2959 2960 2961 2962 2963 2964

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

2965 2966 2967 2968
            /* Found datastore with matching name */
            result = 0;

            goto cleanup;
2969 2970 2971 2972
        }
    }

    if (*datastore == NULL && occurrence != esxVI_Occurrence_OptionalItem) {
2973 2974
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datastore with name '%s'"), name);
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
        goto cleanup;
    }

    result = 0;

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

    return result;
}


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

    if (datastore == NULL || *datastore != NULL) {
3004
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
        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 已提交
3015 3016 3017 3018 3019
    }

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

M
Matthias Bolte 已提交
3022 3023
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
3024 3025 3026
            if (STREQ(dynamicProperty->name, "host")) {
                if (esxVI_DatastoreHostMount_CastListFromAnyType
                      (dynamicProperty->val, &datastoreHostMountList) < 0) {
M
Matthias Bolte 已提交
3027
                    goto cleanup;
3028 3029 3030 3031 3032 3033
                }

                break;
            }
        }

3034 3035
        if (datastoreHostMountList == NULL) {
            continue;
3036 3037
        }

3038 3039 3040 3041 3042 3043 3044
        for (datastoreHostMount = datastoreHostMountList;
             datastoreHostMount != NULL;
             datastoreHostMount = datastoreHostMount->_next) {
            if (STRNEQ(ctx->hostSystem->_reference->value,
                       datastoreHostMount->key->value)) {
                continue;
            }
3045

3046 3047
            if (STRPREFIX(absolutePath, datastoreHostMount->mountInfo->path)) {
                if (esxVI_ObjectContent_DeepCopy(datastore, candidate) < 0) {
M
Matthias Bolte 已提交
3048
                    goto cleanup;
M
Matthias Bolte 已提交
3049 3050
                }

3051
                /* Found datastore with matching mount path */
3052 3053 3054
                result = 0;

                goto cleanup;
M
Matthias Bolte 已提交
3055 3056 3057 3058
            }
        }
    }

3059
    if (*datastore == NULL && occurrence != esxVI_Occurrence_OptionalItem) {
3060 3061 3062
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not find datastore containing absolute path '%s'"),
                       absolutePath);
M
Matthias Bolte 已提交
3063
        goto cleanup;
M
Matthias Bolte 已提交
3064 3065
    }

M
Matthias Bolte 已提交
3066 3067
    result = 0;

M
Matthias Bolte 已提交
3068 3069 3070
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);
3071
    esxVI_DatastoreHostMount_Free(&datastoreHostMountList);
M
Matthias Bolte 已提交
3072 3073

    return result;
3074 3075 3076 3077
}



3078 3079 3080
int
esxVI_LookupDatastoreHostMount(esxVI_Context *ctx,
                               esxVI_ManagedObjectReference *datastore,
3081 3082
                               esxVI_DatastoreHostMount **hostMount,
                               esxVI_Occurrence occurrence)
3083 3084 3085 3086 3087 3088 3089 3090 3091
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_DatastoreHostMount *hostMountList = NULL;
    esxVI_DatastoreHostMount *candidate = NULL;

    if (hostMount == NULL || *hostMount != NULL) {
3092
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3093 3094 3095 3096 3097
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList, "host") < 0 ||
        esxVI_LookupObjectContentByType(ctx, datastore, "Datastore",
3098 3099
                                        propertyNameList, &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
        goto cleanup;
    }

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

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

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

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

        break;
    }

3130
    if (*hostMount == NULL && occurrence == esxVI_Occurrence_RequiredItem) {
3131 3132
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not lookup datastore host mount"));
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
        goto cleanup;
    }

    result = 0;

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

    return result;
}


3147 3148 3149 3150
int
esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
                           esxVI_ManagedObjectReference *task,
                           esxVI_TaskInfo **taskInfo)
3151
{
M
Matthias Bolte 已提交
3152
    int result = -1;
3153 3154 3155 3156 3157
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (taskInfo == NULL || *taskInfo != NULL) {
3158
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3159 3160 3161
        return -1;
    }

3162 3163
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
3164 3165
                                        &objectContent,
                                        esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3166
        goto cleanup;
3167 3168 3169 3170 3171
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
3172
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
3173
                                               taskInfo) < 0) {
M
Matthias Bolte 已提交
3174
                goto cleanup;
3175 3176 3177 3178 3179 3180 3181 3182
            }

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

M
Matthias Bolte 已提交
3183 3184
    result = 0;

3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);

    return result;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
3196
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
3197 3198
   esxVI_TaskInfo **pendingTaskInfoList)
{
M
Matthias Bolte 已提交
3199
    int result = -1;
3200 3201 3202 3203 3204 3205 3206
    esxVI_String *propertyNameList = NULL;
    esxVI_ManagedObjectReference *recentTaskList = NULL;
    esxVI_ManagedObjectReference *recentTask = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_TaskInfo *taskInfo = NULL;

    if (pendingTaskInfoList == NULL || *pendingTaskInfoList != NULL) {
3207
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3208 3209 3210 3211 3212 3213 3214 3215
        return -1;
    }

    /* Get list of recent tasks */
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "recentTask")) {
            if (esxVI_ManagedObjectReference_CastListFromAnyType
3216
                  (dynamicProperty->val, &recentTaskList) < 0) {
M
Matthias Bolte 已提交
3217
                goto cleanup;
3218 3219 3220 3221 3222 3223 3224 3225 3226
            }

            break;
        }
    }

    /* Lookup task info for each task */
    for (recentTask = recentTaskList; recentTask != NULL;
         recentTask = recentTask->_next) {
3227
        if (esxVI_LookupTaskInfoByTask(ctx, recentTask, &taskInfo) < 0) {
M
Matthias Bolte 已提交
3228
            goto cleanup;
3229 3230 3231 3232
        }

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
3233
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
3234
                                            taskInfo) < 0) {
M
Matthias Bolte 已提交
3235
                goto cleanup;
3236 3237 3238 3239 3240 3241 3242 3243
            }

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

M
Matthias Bolte 已提交
3244 3245
    result = 0;

3246
  cleanup:
M
Matthias Bolte 已提交
3247 3248 3249 3250
    if (result < 0) {
        esxVI_TaskInfo_Free(pendingTaskInfoList);
    }

3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



int
3261
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
3262
                                            const unsigned char *uuid,
3263
                                            esxVI_Occurrence occurrence,
3264
                                            bool autoAnswer, bool *blocked)
3265
{
M
Matthias Bolte 已提交
3266
    int result = -1;
3267 3268 3269 3270
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

3271
    if (esxVI_String_AppendValueToList(&propertyNameList,
3272
                                       "runtime.question") < 0 ||
3273
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
3274
                                         &virtualMachine, occurrence) < 0) {
M
Matthias Bolte 已提交
3275
        goto cleanup;
3276 3277
    }

3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
    if (virtualMachine != NULL) {
        if (esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
                                                &questionInfo) < 0) {
            goto cleanup;
        }

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

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

3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);

    return result;
}



3304 3305 3306 3307 3308
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
M
Matthias Bolte 已提交
3309
    int result = -1;
3310 3311 3312 3313 3314
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (rootSnapshotTreeList == NULL || *rootSnapshotTreeList != NULL) {
3315
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3316 3317 3318 3319 3320 3321 3322 3323
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "snapshot.rootSnapshotList") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
3324
        goto cleanup;
3325 3326 3327 3328 3329 3330 3331
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3332
                goto cleanup;
3333 3334 3335 3336 3337 3338 3339 3340
            }

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

M
Matthias Bolte 已提交
3341 3342
    result = 0;

3343
  cleanup:
M
Matthias Bolte 已提交
3344 3345 3346 3347
    if (result < 0) {
        esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);
    }

3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
    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 已提交
3362
    int result = -1;
3363 3364 3365 3366 3367 3368 3369 3370
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *currentSnapshot = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;

    if (currentSnapshotTree == NULL || *currentSnapshotTree != NULL) {
3371
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3372 3373 3374 3375 3376 3377 3378 3379 3380
        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 已提交
3381
        goto cleanup;
3382 3383 3384 3385 3386 3387 3388
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.currentSnapshot")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, &currentSnapshot) < 0) {
M
Matthias Bolte 已提交
3389
                goto cleanup;
3390 3391 3392 3393
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
3394
                goto cleanup;
3395 3396 3397 3398 3399 3400 3401 3402
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (currentSnapshot == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
3403 3404 3405
            result = 0;

            goto cleanup;
3406
        } else {
3407 3408
            virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                           _("Domain has no current snapshot"));
M
Matthias Bolte 已提交
3409
            goto cleanup;
3410 3411 3412 3413
        }
    }

    if (rootSnapshotTreeList == NULL) {
3414 3415
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not lookup root snapshot list"));
M
Matthias Bolte 已提交
3416
        goto cleanup;
3417 3418 3419 3420 3421 3422
    }

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

M
Matthias Bolte 已提交
3426 3427
    result = 0;

3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



3439 3440 3441
int
esxVI_LookupFileInfoByDatastorePath(esxVI_Context *ctx,
                                    const char *datastorePath,
3442
                                    bool lookupFolder,
3443 3444 3445 3446 3447 3448
                                    esxVI_FileInfo **fileInfo,
                                    esxVI_Occurrence occurrence)
{
    int result = -1;
    char *datastoreName = NULL;
    char *directoryName = NULL;
3449
    char *directoryAndFileName = NULL;
3450
    char *fileName = NULL;
3451
    size_t length;
3452 3453 3454 3455 3456
    char *datastorePathWithoutFileName = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
3457
    esxVI_FolderFileQuery *folderFileQuery = NULL;
3458 3459 3460 3461 3462
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3463
    char *taskInfoErrorMessage = NULL;
3464 3465 3466 3467
    esxVI_TaskInfo *taskInfo = NULL;
    esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL;

    if (fileInfo == NULL || *fileInfo != NULL) {
3468
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3469 3470 3471 3472
        return -1;
    }

    if (esxUtil_ParseDatastorePath(datastorePath, &datastoreName,
3473
                                   &directoryName, &directoryAndFileName) < 0) {
3474 3475 3476
        goto cleanup;
    }

3477 3478 3479 3480 3481
    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.
         */
3482 3483 3484 3485 3486
        if (virAsprintf(&datastorePathWithoutFileName, "[%s]",
                        datastoreName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
3487

3488
        if (VIR_STRDUP(fileName, directoryAndFileName) < 0) {
3489 3490
            goto cleanup;
        }
3491 3492 3493 3494 3495 3496
    } else {
        if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s",
                        datastoreName, directoryName) < 0) {
            virReportOOMError();
            goto cleanup;
        }
3497 3498 3499 3500 3501

        length = strlen(directoryName);

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

3508
        if (VIR_STRDUP(fileName, directoryAndFileName + length + 1) < 0) {
3509 3510
            goto cleanup;
        }
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
    }

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

3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548
    if (lookupFolder) {
        if (esxVI_FolderFileQuery_Alloc(&folderFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(folderFileQuery)) < 0) {
            goto cleanup;
        }
    } else {
        if (esxVI_VmDiskFileQuery_Alloc(&vmDiskFileQuery) < 0 ||
            esxVI_VmDiskFileQueryFlags_Alloc(&vmDiskFileQuery->details) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(vmDiskFileQuery)) < 0) {
            goto cleanup;
        }
3549

3550 3551 3552 3553 3554
        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;
3555

3556 3557 3558 3559 3560 3561
        if (esxVI_IsoImageFileQuery_Alloc(&isoImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(isoImageFileQuery)) < 0) {
            goto cleanup;
        }
3562

3563 3564 3565 3566 3567 3568
        if (esxVI_FloppyImageFileQuery_Alloc(&floppyImageFileQuery) < 0 ||
            esxVI_FileQuery_AppendToList
              (&searchSpec->query,
               esxVI_FileQuery_DynamicCast(floppyImageFileQuery)) < 0) {
            goto cleanup;
        }
3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581
    }

    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,
3582
                                    false, &taskInfoState,
3583
                                    &taskInfoErrorMessage) < 0) {
3584 3585 3586 3587
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3588 3589 3590
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not search in datastore '%s': %s"),
                       datastoreName, taskInfoErrorMessage);
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
        goto cleanup;
    }

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

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

            goto cleanup;
        } else {
3607 3608 3609
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("No storage volume with key or path '%s'"),
                           datastorePath);
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
            goto cleanup;
        }
    }

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

    result = 0;

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

    VIR_FREE(datastoreName);
    VIR_FREE(directoryName);
3627
    VIR_FREE(directoryAndFileName);
3628 3629 3630 3631 3632 3633 3634
    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);
3635
    VIR_FREE(taskInfoErrorMessage);
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
    esxVI_TaskInfo_Free(&taskInfo);
    esxVI_HostDatastoreBrowserSearchResults_Free(&searchResults);

    return result;
}



int
esxVI_LookupDatastoreContentByDatastoreName
  (esxVI_Context *ctx, const char *datastoreName,
   esxVI_HostDatastoreBrowserSearchResults **searchResultsList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datastore = NULL;
    esxVI_ManagedObjectReference *hostDatastoreBrowser = NULL;
    esxVI_HostDatastoreBrowserSearchSpec *searchSpec = NULL;
    esxVI_VmDiskFileQuery *vmDiskFileQuery = NULL;
    esxVI_IsoImageFileQuery *isoImageFileQuery = NULL;
    esxVI_FloppyImageFileQuery *floppyImageFileQuery = NULL;
    char *datastorePath = NULL;
    esxVI_ManagedObjectReference *task = NULL;
    esxVI_TaskInfoState taskInfoState;
3660
    char *taskInfoErrorMessage = NULL;
3661 3662 3663
    esxVI_TaskInfo *taskInfo = NULL;

    if (searchResultsList == NULL || *searchResultsList != NULL) {
3664
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726
        return -1;
    }

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

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

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

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

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

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

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

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

    if (esxVI_SearchDatastoreSubFolders_Task(ctx, hostDatastoreBrowser,
                                             datastorePath, searchSpec,
                                             &task) < 0 ||
        esxVI_WaitForTaskCompletion(ctx, task, NULL, esxVI_Occurrence_None,
3727
                                    false, &taskInfoState,
3728
                                    &taskInfoErrorMessage) < 0) {
3729 3730 3731 3732
        goto cleanup;
    }

    if (taskInfoState != esxVI_TaskInfoState_Success) {
3733 3734 3735
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not serach in datastore '%s': %s"),
                       datastoreName, taskInfoErrorMessage);
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753
        goto cleanup;
    }

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

    result = 0;

  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datastore);
    esxVI_ManagedObjectReference_Free(&hostDatastoreBrowser);
    esxVI_HostDatastoreBrowserSearchSpec_Free(&searchSpec);
    VIR_FREE(datastorePath);
    esxVI_ManagedObjectReference_Free(&task);
3754
    VIR_FREE(taskInfoErrorMessage);
3755 3756 3757 3758 3759 3760 3761
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



3762 3763 3764 3765 3766 3767 3768 3769 3770 3771
int
esxVI_LookupStorageVolumeKeyByDatastorePath(esxVI_Context *ctx,
                                            const char *datastorePath,
                                            char **key)
{
    int result = -1;
    esxVI_FileInfo *fileInfo = NULL;
    char *uuid_string = NULL;

    if (key == NULL || *key != NULL) {
3772
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3773 3774 3775
        return -1;
    }

3776 3777 3778 3779
    if (ctx->hasQueryVirtualDiskUuid) {
        if (esxVI_LookupFileInfoByDatastorePath
              (ctx, datastorePath, false, &fileInfo,
               esxVI_Occurrence_RequiredItem) < 0) {
3780 3781 3782
            goto cleanup;
        }

3783 3784 3785 3786 3787 3788 3789
        if (esxVI_VmDiskFileInfo_DynamicCast(fileInfo) != NULL) {
            /* VirtualDisks have a UUID, use it as key */
            if (esxVI_QueryVirtualDiskUuid(ctx, datastorePath,
                                           ctx->datacenter->_reference,
                                           &uuid_string) < 0) {
                goto cleanup;
            }
3790

3791 3792 3793 3794 3795 3796 3797 3798
            if (VIR_ALLOC_N(*key, VIR_UUID_STRING_BUFLEN) < 0) {
                virReportOOMError();
                goto cleanup;
            }

            if (esxUtil_ReformatUuid(uuid_string, *key) < 0) {
                goto cleanup;
            }
3799
        }
3800 3801 3802
    }

    if (*key == NULL) {
3803
        /* Other files don't have a UUID, fall back to the path as key */
3804
        if (VIR_STRDUP(*key, datastorePath) < 0) {
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
            goto cleanup;
        }
    }

    result = 0;

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

    return result;
}



3820 3821 3822 3823 3824 3825 3826 3827 3828 3829
int
esxVI_LookupAutoStartDefaults(esxVI_Context *ctx,
                              esxVI_AutoStartDefaults **defaults)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostAutoStartManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (defaults == NULL || *defaults != NULL) {
3830
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
        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,
3844
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
        goto cleanup;
    }

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

            break;
        }
    }

    if (*defaults == NULL) {
3861 3862
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not retrieve the AutoStartDefaults object"));
3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
        goto cleanup;
    }

    result = 0;

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

    return result;
}



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

    if (powerInfoList == NULL || *powerInfoList != NULL) {
3887
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900
        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,
3901
           &hostAutoStartManager, esxVI_Occurrence_RequiredItem) < 0) {
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
        goto cleanup;
    }

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

            break;
        }
    }

    result = 0;

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

    return result;
}



M
Matthias Bolte 已提交
3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069
int
esxVI_LookupPhysicalNicList(esxVI_Context *ctx,
                            esxVI_PhysicalNic **physicalNicList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (physicalNicList == NULL || *physicalNicList != NULL) {
        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;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         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;

  cleanup:
    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;

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

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

    /* Search for a matching physical NIC */
    for (candidate = physicalNicList; candidate != NULL;
         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;
        }
    }

    if (*physicalNic == NULL && occurrence != esxVI_Occurrence_OptionalItem) {
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("Could not find physical NIC with name '%s'"), name);
        goto cleanup;
    }

    result = 0;

  cleanup:
    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;

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

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

    /* Search for a matching physical NIC */
    for (candidate = physicalNicList; candidate != NULL;
         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;
        }
    }

    if (*physicalNic == NULL && occurrence != esxVI_Occurrence_OptionalItem) {
        virReportError(VIR_ERR_NO_INTERFACE,
                       _("Could not find physical NIC with MAC address '%s'"), mac);
        goto cleanup;
    }

    result = 0;

  cleanup:
    esxVI_PhysicalNic_Free(&physicalNicList);

    return result;
}



M
Matthias Bolte 已提交
4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223
int
esxVI_LookupHostVirtualSwitchList(esxVI_Context *ctx,
                                  esxVI_HostVirtualSwitch **hostVirtualSwitchList)
{
    int result = -1;
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *hostSystem = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (hostVirtualSwitchList == NULL || *hostVirtualSwitchList != NULL) {
        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;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         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;

  cleanup:
    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;

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

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

    /* Search for a matching HostVirtualSwitch */
    for (candidate = hostVirtualSwitchList; candidate != NULL;
         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;
        }
    }

    if (*hostVirtualSwitch == NULL &&
        occurrence != esxVI_Occurrence_OptionalItem) {
        virReportError(VIR_ERR_NO_NETWORK,
                       _("Could not find HostVirtualSwitch with name '%s'"),
                       name);
        goto cleanup;
    }

    result = 0;

  cleanup:
    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;

    if (hostPortGroupList == NULL || *hostPortGroupList != NULL) {
        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;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         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;

  cleanup:
    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);
}



4224 4225
int
esxVI_HandleVirtualMachineQuestion
4226
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
4227 4228
   esxVI_VirtualMachineQuestionInfo *questionInfo, bool autoAnswer,
   bool *blocked)
4229
{
M
Matthias Bolte 已提交
4230
    int result = -1;
4231 4232 4233 4234 4235 4236
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

4237
    if (blocked == NULL) {
4238
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
4239 4240 4241
        return -1;
    }

4242
    *blocked = false;
4243

4244 4245 4246 4247
    if (questionInfo->choice->choiceInfo != NULL) {
        for (elementDescription = questionInfo->choice->choiceInfo;
             elementDescription != NULL;
             elementDescription = elementDescription->_next) {
4248
            virBufferAsprintf(&buffer, "'%s'", elementDescription->label);
4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263

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

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

            ++answerIndex;
        }

        if (virBufferError(&buffer)) {
4264
            virReportOOMError();
M
Matthias Bolte 已提交
4265
            goto cleanup;
4266 4267 4268 4269 4270
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

4271
    if (autoAnswer) {
4272
        if (possibleAnswers == NULL) {
4273 4274 4275 4276
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', no possible answers"),
                           questionInfo->text);
4277

4278
            *blocked = true;
M
Matthias Bolte 已提交
4279
            goto cleanup;
4280
        } else if (answerChoice == NULL) {
4281 4282 4283 4284 4285
            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);
4286

4287
            *blocked = true;
M
Matthias Bolte 已提交
4288
            goto cleanup;
4289 4290 4291 4292 4293 4294 4295
        }

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

4296
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
4297
                           answerChoice->key) < 0) {
M
Matthias Bolte 已提交
4298
            goto cleanup;
4299 4300 4301
        }
    } else {
        if (possibleAnswers != NULL) {
4302 4303 4304 4305
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', possible answers are %s"),
                           questionInfo->text, possibleAnswers);
4306
        } else {
4307 4308 4309 4310
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Pending question blocks virtual machine execution, "
                             "question is '%s', no possible answers"),
                           questionInfo->text);
4311 4312
        }

4313
        *blocked = true;
M
Matthias Bolte 已提交
4314
        goto cleanup;
4315 4316
    }

M
Matthias Bolte 已提交
4317 4318
    result = 0;

4319
  cleanup:
M
Matthias Bolte 已提交
4320 4321 4322 4323
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

4324 4325 4326 4327 4328 4329 4330
    VIR_FREE(possibleAnswers);

    return result;
}



4331
int
4332
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
4333
                            esxVI_ManagedObjectReference *task,
4334
                            const unsigned char *virtualMachineUuid,
4335
                            esxVI_Occurrence virtualMachineOccurrence,
4336
                            bool autoAnswer, esxVI_TaskInfoState *finalState,
4337
                            char **errorMessage)
4338
{
M
Matthias Bolte 已提交
4339
    int result = -1;
4340
    esxVI_ObjectSpec *objectSpec = NULL;
4341
    bool objectSpec_isAppended = false;
4342
    esxVI_PropertySpec *propertySpec = NULL;
4343
    bool propertySpec_isAppended = false;
4344 4345 4346 4347 4348 4349 4350 4351 4352
    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;
4353
    bool blocked;
4354
    esxVI_TaskInfo *taskInfo = NULL;
4355

4356
    if (errorMessage == NULL || *errorMessage != NULL) {
4357
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
4358 4359 4360
        return -1;
    }

4361
    if (VIR_STRDUP(version, "") < 0)
M
Matthias Bolte 已提交
4362
        return -1;
4363

4364
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
4365
        goto cleanup;
4366 4367 4368 4369 4370
    }

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

4371
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
4372
        goto cleanup;
4373 4374 4375 4376
    }

    propertySpec->type = task->type;

4377
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
4378
                                       "info.state") < 0 ||
4379 4380
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394
                                        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,
4395
                           &propertyFilter) < 0) {
M
Matthias Bolte 已提交
4396
        goto cleanup;
4397 4398 4399 4400 4401 4402
    }

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

4403 4404
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
4405 4406
                  (ctx, virtualMachineUuid, virtualMachineOccurrence,
                   autoAnswer, &blocked) < 0) {
4407 4408 4409 4410 4411
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
4412
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
M
Matthias Bolte 已提交
4413
                    goto cleanup;
4414 4415 4416
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
4417
                    if (esxVI_CancelTask(ctx, task) < 0 && blocked) {
4418
                        VIR_ERROR(_("Cancelable task is blocked by an "
E
Eric Blake 已提交
4419
                                     "unanswered question but cancellation "
4420
                                     "failed"));
4421
                    }
4422
                } else if (blocked) {
4423
                    VIR_ERROR(_("Non-cancelable task is blocked by an "
4424
                                 "unanswered question"));
4425 4426 4427 4428
                }

                /* FIXME: Enable error reporting here again */

M
Matthias Bolte 已提交
4429
                goto cleanup;
4430 4431 4432
            }
        }

4433
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
M
Matthias Bolte 已提交
4434
            goto cleanup;
4435 4436 4437
        }

        VIR_FREE(version);
4438
        if (VIR_STRDUP(version, updateSet->version) < 0)
M
Matthias Bolte 已提交
4439
            goto cleanup;
4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468

        if (updateSet->filterSet == NULL) {
            continue;
        }

        for (propertyFilterUpdate = updateSet->filterSet;
             propertyFilterUpdate != NULL;
             propertyFilterUpdate = propertyFilterUpdate->_next) {
            for (objectUpdate = propertyFilterUpdate->objectSet;
                 objectUpdate != NULL; objectUpdate = objectUpdate->_next) {
                for (propertyChange = objectUpdate->changeSet;
                     propertyChange != NULL;
                     propertyChange = propertyChange->_next) {
                    if (STREQ(propertyChange->name, "info.state")) {
                        if (propertyChange->op == esxVI_PropertyChangeOp_Add ||
                            propertyChange->op == esxVI_PropertyChangeOp_Assign) {
                            propertyValue = propertyChange->val;
                        } else {
                            propertyValue = NULL;
                        }
                    }
                }
            }
        }

        if (propertyValue == NULL) {
            continue;
        }

4469
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
M
Matthias Bolte 已提交
4470
            goto cleanup;
4471 4472 4473
        }
    }

4474
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
4475
        VIR_DEBUG("DestroyPropertyFilter failed");
4476 4477
    }

4478
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
M
Matthias Bolte 已提交
4479
        goto cleanup;
4480 4481
    }

4482 4483 4484 4485 4486 4487
    if (*finalState != esxVI_TaskInfoState_Success) {
        if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
            goto cleanup;
        }

        if (taskInfo->error == NULL) {
4488
            if (VIR_STRDUP(*errorMessage, _("Unknown error")) < 0)
4489 4490
                goto cleanup;
        } else if (taskInfo->error->localizedMessage == NULL) {
4491
            if (VIR_STRDUP(*errorMessage, taskInfo->error->fault->_actualType) < 0)
4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502
                goto cleanup;
        } else {
            if (virAsprintf(errorMessage, "%s - %s",
                            taskInfo->error->fault->_actualType,
                            taskInfo->error->localizedMessage) < 0) {
                virReportOOMError();
                goto cleanup;
            }
        }
    }

M
Matthias Bolte 已提交
4503 4504
    result = 0;

4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
  cleanup:
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
     */
    if (objectSpec != NULL) {
        objectSpec->obj = NULL;
    }

    if (propertySpec != NULL) {
        propertySpec->type = NULL;
    }

4518 4519 4520 4521 4522 4523 4524 4525
    if (!objectSpec_isAppended) {
        esxVI_ObjectSpec_Free(&objectSpec);
    }

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

4526 4527 4528 4529
    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);
    esxVI_ManagedObjectReference_Free(&propertyFilter);
    VIR_FREE(version);
    esxVI_UpdateSet_Free(&updateSet);
4530
    esxVI_TaskInfo_Free(&taskInfo);
4531 4532 4533

    return result;
}
4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548



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

4549
    memset(parsedHostCpuIdInfo, 0, sizeof(*parsedHostCpuIdInfo));
4550 4551 4552 4553 4554

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

    for (r = 0; r < 4; ++r) {
        if (strlen(input[r]) != expectedLength) {
4555 4556 4557
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("HostCpuIdInfo register '%s' has an unexpected length"),
                           name[r]);
M
Matthias Bolte 已提交
4558
            return -1;
4559 4560 4561 4562 4563 4564 4565 4566 4567 4568
        }

        /* 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] != ':') {
4569 4570 4571
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("HostCpuIdInfo register '%s' has an unexpected format"),
                               name[r]);
M
Matthias Bolte 已提交
4572
                return -1;
4573 4574 4575 4576 4577 4578
            }
        }
    }

    return 0;
}
4579 4580 4581 4582 4583 4584 4585 4586 4587



int
esxVI_ProductVersionToDefaultVirtualHWVersion(esxVI_ProductVersion productVersion)
{
    /*
     * virtualHW.version compatibility matrix:
     *
P
Patrice LACHANCE 已提交
4588 4589 4590 4591 4592 4593
     *              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
4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610
     */
    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 已提交
4611 4612 4613 4614
      case esxVI_ProductVersion_ESX50:
      case esxVI_ProductVersion_VPX50:
        return 8;

4615
      case esxVI_ProductVersion_ESX51:
P
Patrice LACHANCE 已提交
4616
      case esxVI_ProductVersion_ESX5x:
4617
      case esxVI_ProductVersion_VPX51:
P
Patrice LACHANCE 已提交
4618 4619 4620
      case esxVI_ProductVersion_VPX5x:
        return 8;

4621
      default:
4622 4623
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unexpected product version"));
4624 4625 4626
        return -1;
    }
}
4627 4628 4629



4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 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 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 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 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932
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;
    }

    if (hostInternetScsiHba == NULL) {
        /* iSCSI adapter may not be enabled for this host */
        return 0;
    }

    for (candidate = hostInternetScsiHba->configuredStaticTarget;
         candidate != NULL; candidate = candidate->_next) {
        if (STREQ(candidate->iScsiName, name)) {
            break;
        }
    }

    if (candidate == NULL) {
        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;

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

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name,
                  "config.storageDevice.hostBusAdapter")) {
            if (esxVI_HostHostBusAdapter_CastListFromAnyType
                  (dynamicProperty->val, &hostHostBusAdapterList) < 0 ||
                hostHostBusAdapterList == NULL) {
                goto cleanup;
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    /* See vSphere API documentation about HostInternetScsiHba for details */
    for (hostHostBusAdapter = hostHostBusAdapterList;
         hostHostBusAdapter != NULL;
         hostHostBusAdapter = hostHostBusAdapter->_next) {
        esxVI_HostInternetScsiHba *candidate=
            esxVI_HostInternetScsiHba_DynamicCast(hostHostBusAdapter);

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

    result = 0;

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

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         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;

  cleanup:
    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;

    if (hostScsiTopologyLunList == NULL || *hostScsiTopologyLunList != NULL) {
        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;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         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;
         hostScsiInterface != NULL && !found;
         hostScsiInterface = hostScsiInterface->_next) {
        for (hostScsiTopologyTarget = hostScsiInterface->target;
             hostScsiTopologyTarget != NULL;
             hostScsiTopologyTarget = hostScsiTopologyTarget->_next) {
            candidate = esxVI_HostInternetScsiTargetTransport_DynamicCast
                          (hostScsiTopologyTarget->transport);

            if (candidate != NULL && STREQ(candidate->iScsiName, name)) {
                found = true;
                break;
            }
        }
    }

    if (!found || hostScsiTopologyTarget == NULL) {
        goto cleanup;
    }

    if (hostScsiTopologyTarget->lun == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Target not found"));
        goto cleanup;
    }

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

    result = 0;

  cleanup:
    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;

    if (poolName == NULL || *poolName != NULL) {
        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;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         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;
         hostScsiInterface != NULL && !found;
         hostScsiInterface = hostScsiInterface->_next) {
        for (hostScsiTopologyTarget = hostScsiInterface->target;
             hostScsiTopologyTarget != NULL;
             hostScsiTopologyTarget = hostScsiTopologyTarget->_next) {
            candidate = esxVI_HostInternetScsiTargetTransport_DynamicCast
4933
                (hostScsiTopologyTarget->transport);
4934 4935 4936 4937 4938 4939

            if (candidate != NULL) {
                /* iterate hostScsiTopologyLun list to find matching key */
                for (hostScsiTopologyLun = hostScsiTopologyTarget->lun;
                     hostScsiTopologyLun != NULL;
                     hostScsiTopologyLun = hostScsiTopologyLun->_next) {
4940 4941 4942
                    if (STREQ(hostScsiTopologyLun->scsiLun, key) &&
                        VIR_STRDUP(*poolName, candidate->iScsiName) < 0)
                        goto cleanup;
4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961
                }

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

    result = 0;

  cleanup:
    esxVI_ObjectContent_Free(&hostSystem);
    esxVI_String_Free(&propertyNameList);
    esxVI_HostScsiTopologyInterface_Free(&hostScsiInterfaceList);

    return result;
}


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 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006

#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,                 \
5007
                                 _cast_from_anytype)                          \
5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021
    int                                                                       \
    esxVI_Lookup##_type(esxVI_Context *ctx, const char* name /* optional */,  \
                        esxVI_ManagedObjectReference *root,                   \
                        esxVI_String *selectedPropertyNameList /* optional */,\
                        esxVI_##_type **ptrptr, esxVI_Occurrence occurrence)  \
    {                                                                         \
        int result = -1;                                                      \
        const char *completePropertyNameValueList = _complete_properties;     \
        esxVI_String *propertyNameList = NULL;                                \
        esxVI_ObjectContent *objectContent = NULL;                            \
        esxVI_ObjectContent *objectContentList = NULL;                        \
        esxVI_DynamicProperty *dynamicProperty = NULL;                        \
                                                                              \
        if (ptrptr == NULL || *ptrptr != NULL) {                              \
5022 5023
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",                      \
                           _("Invalid argument"));                            \
5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041
            return -1;                                                        \
        }                                                                     \
                                                                              \
        propertyNameList = selectedPropertyNameList;                          \
                                                                              \
        if (propertyNameList == NULL &&                                       \
            esxVI_String_AppendValueListToList                                \
              (&propertyNameList, completePropertyNameValueList) < 0) {       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_LookupManagedObjectHelper(ctx, name, root, #_type,          \
                                            propertyNameList, &objectContent, \
                                            &objectContentList,               \
                                            occurrence) < 0) {                \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
5042 5043 5044 5045 5046 5047
        if (objectContent == NULL) {                                          \
            /* not found, exit early */                                       \
            result = 0;                                                       \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
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 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
        if (esxVI_##_type##_Alloc(ptrptr) < 0) {                              \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        if (esxVI_ManagedObjectReference_DeepCopy(&(*ptrptr)->_reference,     \
                                                  objectContent->obj) < 0) {  \
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        for (dynamicProperty = objectContent->propSet;                        \
             dynamicProperty != NULL;                                         \
             dynamicProperty = dynamicProperty->_next) {                      \
            _cast_from_anytype                                                \
                                                                              \
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);      \
        }                                                                     \
                                                                              \
        if (esxVI_##_type##_Validate(*ptrptr, selectedPropertyNameList) < 0) {\
            goto cleanup;                                                     \
        }                                                                     \
                                                                              \
        result = 0;                                                           \
                                                                              \
      cleanup:                                                                \
        if (result < 0) {                                                     \
            esxVI_##_type##_Free(ptrptr);                                     \
        }                                                                     \
                                                                              \
        if (propertyNameList != selectedPropertyNameList) {                   \
            esxVI_String_Free(&propertyNameList);                             \
        }                                                                     \
                                                                              \
        esxVI_ObjectContent_Free(&objectContentList);                         \
                                                                              \
        return result;                                                        \
    }



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

    if (objectContent == NULL || *objectContent != NULL ||
        objectContentList == NULL || *objectContentList != NULL) {
5103
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
5104 5105 5106 5107
        return -1;
    }

    if (!esxVI_String_ListContainsValue(propertyNameList, "name")) {
5108 5109
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Missing 'name' property in %s lookup"), type);
5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140
        goto cleanup;
    }

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

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

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

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

    if (candidate == NULL) {
        if (occurrence != esxVI_Occurrence_OptionalItem) {
5141 5142 5143 5144 5145 5146 5147 5148
            if (name != NULL) {
                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);
            }

5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171
            goto cleanup;
        }

        result = 0;

        goto cleanup;
    }

    result = 0;

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

    return result;
}



#include "esx_vi.generated.c"