hyperv_driver.c 49.6 KB
Newer Older
M
Matthias Bolte 已提交
1 2 3
/*
 * hyperv_driver.c: core driver functions for managing Microsoft Hyper-V hosts
 *
4
 * Copyright (C) 2011-2013 Matthias Bolte <matthias.bolte@googlemail.com>
M
Matthias Bolte 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2009 Michael Sievers <msievers83@googlemail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
M
Matthias Bolte 已提交
20 21 22 23 24 25 26
 *
 */

#include <config.h>

#include "internal.h"
#include "datatypes.h"
27
#include "virdomainobjlist.h"
28
#include "virauth.h"
29
#include "viralloc.h"
30
#include "virlog.h"
31
#include "viruuid.h"
M
Matthias Bolte 已提交
32 33
#include "hyperv_driver.h"
#include "hyperv_private.h"
34 35 36
#include "hyperv_util.h"
#include "hyperv_wmi.h"
#include "openwsman.h"
37
#include "virstring.h"
S
Sri Ramanujam 已提交
38 39
#include "virkeycode.h"
#include "intprops.h"
M
Matthias Bolte 已提交
40 41 42

#define VIR_FROM_THIS VIR_FROM_HYPERV

43
VIR_LOG_INIT("hyperv.hyperv_driver");
M
Matthias Bolte 已提交
44

45 46 47
static void
hypervFreePrivate(hypervPrivate **priv)
{
48
    if (priv == NULL || *priv == NULL)
49 50 51 52 53 54 55 56 57 58 59
        return;

    if ((*priv)->client != NULL) {
        /* FIXME: This leaks memory due to bugs in openwsman <= 2.2.6 */
        wsmc_release((*priv)->client);
    }

    hypervFreeParsedUri(&(*priv)->parsedUri);
    VIR_FREE(*priv);
}

60 61 62 63 64 65 66 67
static int
hypervInitConnection(virConnectPtr conn, hypervPrivate *priv,
                     char *username, char *password)
{
    virBuffer query = VIR_BUFFER_INITIALIZER;
    hypervWqlQuery wqlQuery = HYPERV_WQL_QUERY_INITIALIZER;
    hypervObject *computerSystem = NULL;
    int ret = -1;
68

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    /* Initialize the openwsman connection */
    priv->client = wsmc_create(conn->uri->server, conn->uri->port, "/wsman",
                               priv->parsedUri->transport, username, password);

    if (priv->client == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not create openwsman client"));
        goto cleanup;
    }

    if (wsmc_transport_init(priv->client, NULL) != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not initialize openwsman transport"));
        goto cleanup;
    }

    /* FIXME: Currently only basic authentication is supported  */
    wsman_transport_set_auth_method(priv->client, "basic");

    wqlQuery.info = Msvm_ComputerSystem_WmiInfo;
    wqlQuery.query = &query;

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "WHERE ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_PHYSICAL);

    /* try query using V2 namespace (for Hyper-V 2012+) */
    priv->wmiVersion = HYPERV_WMI_VERSION_V2;

    if (hypervEnumAndPull(priv, &wqlQuery, &computerSystem) < 0) {
        /* rebuild query because hypervEnumAndPull consumes it */
        virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
        virBufferAddLit(&query, "WHERE ");
        virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_PHYSICAL);

        /* fall back to V1 namespace (for Hyper-V 2008) */
        priv->wmiVersion = HYPERV_WMI_VERSION_V1;

107
        if (hypervEnumAndPull(priv, &wqlQuery, &computerSystem) < 0)
108 109 110 111 112 113 114 115 116 117
            goto cleanup;
    }

    ret = 0;

 cleanup:
    hypervFreeObject(priv, computerSystem);

    return ret;
}
118

M
Matthias Bolte 已提交
119
static virDrvOpenStatus
120 121 122
hypervConnectOpen(virConnectPtr conn, virConnectAuthPtr auth,
                  virConfPtr conf ATTRIBUTE_UNUSED,
                  unsigned int flags)
M
Matthias Bolte 已提交
123
{
124 125 126 127 128
    virDrvOpenStatus result = VIR_DRV_OPEN_ERROR;
    hypervPrivate *priv = NULL;
    char *username = NULL;
    char *password = NULL;

M
Matthias Bolte 已提交
129 130 131 132
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

    /* Require server part */
    if (conn->uri->server == NULL) {
133 134
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("URI is missing the server part"));
M
Matthias Bolte 已提交
135 136 137 138 139
        return VIR_DRV_OPEN_ERROR;
    }

    /* Require auth */
    if (auth == NULL || auth->cb == NULL) {
140 141
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Missing or invalid auth pointer"));
M
Matthias Bolte 已提交
142 143 144
        return VIR_DRV_OPEN_ERROR;
    }

145
    /* Allocate per-connection private data */
146
    if (VIR_ALLOC(priv) < 0)
147 148
        goto cleanup;

149
    if (hypervParseUri(&priv->parsedUri, conn->uri) < 0)
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
        goto cleanup;

    /* Set the port dependent on the transport protocol if no port is
     * specified. This allows us to rely on the port parameter being
     * correctly set when building URIs later on, without the need to
     * distinguish between the situations port == 0 and port != 0 */
    if (conn->uri->port == 0) {
        if (STRCASEEQ(priv->parsedUri->transport, "https")) {
            conn->uri->port = 5986;
        } else {
            conn->uri->port = 5985;
        }
    }

    /* Request credentials */
    if (conn->uri->user != NULL) {
166
        if (VIR_STRDUP(username, conn->uri->user) < 0)
167 168
            goto cleanup;
    } else {
169
        username = virAuthGetUsername(conn, auth, "hyperv", "administrator", conn->uri->server);
170 171

        if (username == NULL) {
172
            virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Username request failed"));
173 174 175 176
            goto cleanup;
        }
    }

177
    password = virAuthGetPassword(conn, auth, "hyperv", username, conn->uri->server);
178 179

    if (password == NULL) {
180
        virReportError(VIR_ERR_AUTH_FAILED, "%s", _("Password request failed"));
181 182 183 184
        goto cleanup;
    }


185
    if (hypervInitConnection(conn, priv, username, password) < 0)
186 187 188
        goto cleanup;

    conn->privateData = priv;
189
    priv = NULL;
190 191
    result = VIR_DRV_OPEN_SUCCESS;

192
 cleanup:
193
    hypervFreePrivate(&priv);
194 195 196 197 198 199 200 201 202
    VIR_FREE(username);
    VIR_FREE(password);

    return result;
}



static int
203
hypervConnectClose(virConnectPtr conn)
204 205 206 207 208 209 210 211 212 213 214 215 216
{
    hypervPrivate *priv = conn->privateData;

    hypervFreePrivate(&priv);

    conn->privateData = NULL;

    return 0;
}



static const char *
217
hypervConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
218 219 220 221 222 223 224
{
    return "Hyper-V";
}



static char *
225
hypervConnectGetHostname(virConnectPtr conn)
226 227 228 229 230 231 232 233
{
    char *hostname = NULL;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Win32_ComputerSystem *computerSystem = NULL;

    virBufferAddLit(&query, WIN32_COMPUTERSYSTEM_WQL_SELECT);

234
    if (hypervGetWin32ComputerSystemList(priv, &query, &computerSystem) < 0)
235 236 237
        goto cleanup;

    if (computerSystem == NULL) {
238 239 240
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s"),
                       "Win32_ComputerSystem");
241 242 243
        goto cleanup;
    }

244
    ignore_value(VIR_STRDUP(hostname, computerSystem->data.common->DNSHostName));
245

246
 cleanup:
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return hostname;
}



static int
hypervNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
    int result = -1;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Win32_ComputerSystem *computerSystem = NULL;
    Win32_Processor *processorList = NULL;
    Win32_Processor *processor = NULL;
    char *tmp;

265
    memset(info, 0, sizeof(*info));
266 267 268 269

    virBufferAddLit(&query, WIN32_COMPUTERSYSTEM_WQL_SELECT);

    /* Get Win32_ComputerSystem */
270
    if (hypervGetWin32ComputerSystemList(priv, &query, &computerSystem) < 0)
271 272 273
        goto cleanup;

    if (computerSystem == NULL) {
274 275 276
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s"),
                       "Win32_ComputerSystem");
277 278 279 280
        goto cleanup;
    }

    /* Get Win32_Processor list */
L
Ladi Prosek 已提交
281 282 283 284 285 286
    virBufferEscapeSQL(&query,
                       "associators of "
                       "{Win32_ComputerSystem.Name=\"%s\"} "
                       "where AssocClass = Win32_ComputerSystemProcessor "
                       "ResultClass = Win32_Processor",
                       computerSystem->data.common->Name);
287

288
    if (hypervGetWin32ProcessorList(priv, &query, &processorList) < 0)
289 290 291
        goto cleanup;

    if (processorList == NULL) {
292 293 294
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s"),
                       "Win32_Processor");
295 296 297 298
        goto cleanup;
    }

    /* Strip the string to fit more relevant information in 32 chars */
299
    tmp = processorList->data.common->Name;
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

    while (*tmp != '\0') {
        if (STRPREFIX(tmp, "  ")) {
            memmove(tmp, tmp + 1, strlen(tmp + 1) + 1);
            continue;
        } else if (STRPREFIX(tmp, "(R)") || STRPREFIX(tmp, "(C)")) {
            memmove(tmp, tmp + 3, strlen(tmp + 3) + 1);
            continue;
        } else if (STRPREFIX(tmp, "(TM)")) {
            memmove(tmp, tmp + 4, strlen(tmp + 4) + 1);
            continue;
        }

        ++tmp;
    }

    /* Fill struct */
317
    if (virStrncpy(info->model, processorList->data.common->Name,
318
                   sizeof(info->model) - 1, sizeof(info->model)) == NULL) {
319 320
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("CPU model %s too long for destination"),
321
                       processorList->data.common->Name);
322 323 324
        goto cleanup;
    }

325 326
    info->memory = computerSystem->data.common->TotalPhysicalMemory / 1024; /* byte to kilobyte */
    info->mhz = processorList->data.common->MaxClockSpeed;
327 328 329 330 331 332 333 334
    info->nodes = 1;
    info->sockets = 0;

    for (processor = processorList; processor != NULL;
         processor = processor->next) {
        ++info->sockets;
    }

335 336
    info->cores = processorList->data.common->NumberOfCores;
    info->threads = info->cores / processorList->data.common->NumberOfLogicalProcessors;
337 338 339 340
    info->cpus = info->sockets * info->cores;

    result = 0;

341
 cleanup:
342 343 344 345 346 347 348 349 350
    hypervFreeObject(priv, (hypervObject *)computerSystem);
    hypervFreeObject(priv, (hypervObject *)processorList);

    return result;
}



static int
351
hypervConnectListDomains(virConnectPtr conn, int *ids, int maxids)
352 353 354 355 356 357 358 359
{
    bool success = false;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystemList = NULL;
    Msvm_ComputerSystem *computerSystem = NULL;
    int count = 0;

360
    if (maxids == 0)
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        return 0;

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);
    virBufferAddLit(&query, "and ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_ACTIVE);

    if (hypervGetMsvmComputerSystemList(priv, &query,
                                        &computerSystemList) < 0) {
        goto cleanup;
    }

    for (computerSystem = computerSystemList; computerSystem != NULL;
         computerSystem = computerSystem->next) {
376
        ids[count++] = computerSystem->data.common->ProcessID;
377

378
        if (count >= maxids)
379 380 381 382 383
            break;
    }

    success = true;

384
 cleanup:
385 386 387 388 389 390 391 392
    hypervFreeObject(priv, (hypervObject *)computerSystemList);

    return success ? count : -1;
}



static int
393
hypervConnectNumOfDomains(virConnectPtr conn)
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
{
    bool success = false;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystemList = NULL;
    Msvm_ComputerSystem *computerSystem = NULL;
    int count = 0;

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);
    virBufferAddLit(&query, "and ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_ACTIVE);

    if (hypervGetMsvmComputerSystemList(priv, &query,
                                        &computerSystemList) < 0) {
        goto cleanup;
    }

    for (computerSystem = computerSystemList; computerSystem != NULL;
         computerSystem = computerSystem->next) {
        ++count;
    }

    success = true;

420
 cleanup:
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    hypervFreeObject(priv, (hypervObject *)computerSystemList);

    return success ? count : -1;
}



static virDomainPtr
hypervDomainLookupByID(virConnectPtr conn, int id)
{
    virDomainPtr domain = NULL;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystem = NULL;

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);
    virBufferAsprintf(&query, "and ProcessID = %d", id);

441
    if (hypervGetMsvmComputerSystemList(priv, &query, &computerSystem) < 0)
442 443 444
        goto cleanup;

    if (computerSystem == NULL) {
445
        virReportError(VIR_ERR_NO_DOMAIN, _("No domain with ID %d"), id);
446 447 448 449 450
        goto cleanup;
    }

    hypervMsvmComputerSystemToDomain(conn, computerSystem, &domain);

451
 cleanup:
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return domain;
}



static virDomainPtr
hypervDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
    virDomainPtr domain = NULL;
    hypervPrivate *priv = conn->privateData;
    char uuid_string[VIR_UUID_STRING_BUFLEN];
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystem = NULL;

    virUUIDFormat(uuid, uuid_string);

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);
L
Ladi Prosek 已提交
473
    virBufferEscapeSQL(&query, "and Name = \"%s\"", uuid_string);
474

475
    if (hypervGetMsvmComputerSystemList(priv, &query, &computerSystem) < 0)
476 477 478
        goto cleanup;

    if (computerSystem == NULL) {
479 480
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with UUID %s"), uuid_string);
481 482 483 484 485
        goto cleanup;
    }

    hypervMsvmComputerSystemToDomain(conn, computerSystem, &domain);

486
 cleanup:
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return domain;
}



static virDomainPtr
hypervDomainLookupByName(virConnectPtr conn, const char *name)
{
    virDomainPtr domain = NULL;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystem = NULL;

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);
L
Ladi Prosek 已提交
505
    virBufferEscapeSQL(&query, "and ElementName = \"%s\"", name);
506

507
    if (hypervGetMsvmComputerSystemList(priv, &query, &computerSystem) < 0)
508 509 510
        goto cleanup;

    if (computerSystem == NULL) {
511 512
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with name %s"), name);
513 514 515 516 517
        goto cleanup;
    }

    hypervMsvmComputerSystemToDomain(conn, computerSystem, &domain);

518
 cleanup:
519 520 521 522 523 524 525 526 527 528 529 530 531 532
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return domain;
}



static int
hypervDomainSuspend(virDomainPtr domain)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;

533
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
534 535
        goto cleanup;

536
    if (computerSystem->data.common->EnabledState !=
537
        MSVM_COMPUTERSYSTEM_ENABLEDSTATE_ENABLED) {
538 539
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not active"));
540 541 542 543 544 545
        goto cleanup;
    }

    result = hypervInvokeMsvmComputerSystemRequestStateChange
               (domain, MSVM_COMPUTERSYSTEM_REQUESTEDSTATE_PAUSED);

546
 cleanup:
547 548 549 550 551 552 553 554 555 556 557 558 559 560
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static int
hypervDomainResume(virDomainPtr domain)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;

561
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
562 563
        goto cleanup;

564
    if (computerSystem->data.common->EnabledState !=
565
        MSVM_COMPUTERSYSTEM_ENABLEDSTATE_PAUSED) {
566 567
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not paused"));
568 569 570 571 572 573
        goto cleanup;
    }

    result = hypervInvokeMsvmComputerSystemRequestStateChange
               (domain, MSVM_COMPUTERSYSTEM_REQUESTEDSTATE_ENABLED);

574
 cleanup:
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static int
hypervDomainDestroyFlags(virDomainPtr domain, unsigned int flags)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;
    bool in_transition = false;

    virCheckFlags(0, -1);

592
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
593 594 595 596
        goto cleanup;

    if (!hypervIsMsvmComputerSystemActive(computerSystem, &in_transition) ||
        in_transition) {
597 598
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not active or is in state transition"));
599 600 601 602 603 604
        goto cleanup;
    }

    result = hypervInvokeMsvmComputerSystemRequestStateChange
               (domain, MSVM_COMPUTERSYSTEM_REQUESTEDSTATE_DISABLED);

605
 cleanup:
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static int
hypervDomainDestroy(virDomainPtr domain)
{
    return hypervDomainDestroyFlags(domain, 0);
}



static char *
hypervDomainGetOSType(virDomainPtr domain ATTRIBUTE_UNUSED)
{
624
    char *osType;
625

626
    ignore_value(VIR_STRDUP(osType, "hvm"));
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    return osType;
}



static int
hypervDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    char uuid_string[VIR_UUID_STRING_BUFLEN];
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystem = NULL;
    Msvm_VirtualSystemSettingData *virtualSystemSettingData = NULL;
    Msvm_ProcessorSettingData *processorSettingData = NULL;
    Msvm_MemorySettingData *memorySettingData = NULL;

644
    memset(info, 0, sizeof(*info));
645 646 647 648

    virUUIDFormat(domain->uuid, uuid_string);

    /* Get Msvm_ComputerSystem */
649
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
650 651 652
        goto cleanup;

    /* Get Msvm_VirtualSystemSettingData */
L
Ladi Prosek 已提交
653 654 655 656 657 658 659
    virBufferEscapeSQL(&query,
                       "associators of "
                       "{Msvm_ComputerSystem.CreationClassName=\"Msvm_ComputerSystem\","
                       "Name=\"%s\"} "
                       "where AssocClass = Msvm_SettingsDefineState "
                       "ResultClass = Msvm_VirtualSystemSettingData",
                       uuid_string);
660 661 662 663 664 665 666

    if (hypervGetMsvmVirtualSystemSettingDataList(priv, &query,
                                                  &virtualSystemSettingData) < 0) {
        goto cleanup;
    }

    if (virtualSystemSettingData == NULL) {
667 668 669
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s for domain %s"),
                       "Msvm_VirtualSystemSettingData",
670
                       computerSystem->data.common->ElementName);
671 672 673 674
        goto cleanup;
    }

    /* Get Msvm_ProcessorSettingData */
L
Ladi Prosek 已提交
675 676 677 678 679 680
    virBufferEscapeSQL(&query,
                       "associators of "
                       "{Msvm_VirtualSystemSettingData.InstanceID=\"%s\"} "
                       "where AssocClass = Msvm_VirtualSystemSettingDataComponent "
                       "ResultClass = Msvm_ProcessorSettingData",
                       virtualSystemSettingData->data.common->InstanceID);
681 682 683 684 685 686 687

    if (hypervGetMsvmProcessorSettingDataList(priv, &query,
                                              &processorSettingData) < 0) {
        goto cleanup;
    }

    if (processorSettingData == NULL) {
688 689 690
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s for domain %s"),
                       "Msvm_ProcessorSettingData",
691
                       computerSystem->data.common->ElementName);
692 693 694 695
        goto cleanup;
    }

    /* Get Msvm_MemorySettingData */
L
Ladi Prosek 已提交
696 697 698 699 700 701
    virBufferEscapeSQL(&query,
                       "associators of "
                       "{Msvm_VirtualSystemSettingData.InstanceID=\"%s\"} "
                       "where AssocClass = Msvm_VirtualSystemSettingDataComponent "
                       "ResultClass = Msvm_MemorySettingData",
                       virtualSystemSettingData->data.common->InstanceID);
702 703 704 705 706 707 708 709

    if (hypervGetMsvmMemorySettingDataList(priv, &query,
                                           &memorySettingData) < 0) {
        goto cleanup;
    }


    if (memorySettingData == NULL) {
710 711 712
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s for domain %s"),
                       "Msvm_MemorySettingData",
713
                       computerSystem->data.common->ElementName);
714 715 716 717 718
        goto cleanup;
    }

    /* Fill struct */
    info->state = hypervMsvmComputerSystemEnabledStateToDomainState(computerSystem);
719 720 721
    info->maxMem = memorySettingData->data.common->Limit * 1024; /* megabyte to kilobyte */
    info->memory = memorySettingData->data.common->VirtualQuantity * 1024; /* megabyte to kilobyte */
    info->nrVirtCpu = processorSettingData->data.common->VirtualQuantity;
722 723 724 725
    info->cpuTime = 0;

    result = 0;

726
 cleanup:
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
    hypervFreeObject(priv, (hypervObject *)computerSystem);
    hypervFreeObject(priv, (hypervObject *)virtualSystemSettingData);
    hypervFreeObject(priv, (hypervObject *)processorSettingData);
    hypervFreeObject(priv, (hypervObject *)memorySettingData);

    return result;
}



static int
hypervDomainGetState(virDomainPtr domain, int *state, int *reason,
                     unsigned int flags)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;

    virCheckFlags(0, -1);

747
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
748 749 750 751
        goto cleanup;

    *state = hypervMsvmComputerSystemEnabledStateToDomainState(computerSystem);

752
    if (reason != NULL)
753 754 755 756
        *reason = 0;

    result = 0;

757
 cleanup:
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static char *
hypervDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
{
    char *xml = NULL;
    hypervPrivate *priv = domain->conn->privateData;
    virDomainDefPtr def = NULL;
    char uuid_string[VIR_UUID_STRING_BUFLEN];
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystem = NULL;
    Msvm_VirtualSystemSettingData *virtualSystemSettingData = NULL;
    Msvm_ProcessorSettingData *processorSettingData = NULL;
    Msvm_MemorySettingData *memorySettingData = NULL;

    /* Flags checked by virDomainDefFormat */

780
    if (!(def = virDomainDefNew()))
781 782 783 784 785
        goto cleanup;

    virUUIDFormat(domain->uuid, uuid_string);

    /* Get Msvm_ComputerSystem */
786
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
787 788 789
        goto cleanup;

    /* Get Msvm_VirtualSystemSettingData */
L
Ladi Prosek 已提交
790 791 792 793 794 795 796
    virBufferEscapeSQL(&query,
                       "associators of "
                       "{Msvm_ComputerSystem.CreationClassName=\"Msvm_ComputerSystem\","
                       "Name=\"%s\"} "
                       "where AssocClass = Msvm_SettingsDefineState "
                       "ResultClass = Msvm_VirtualSystemSettingData",
                       uuid_string);
797 798 799 800 801 802 803

    if (hypervGetMsvmVirtualSystemSettingDataList(priv, &query,
                                                  &virtualSystemSettingData) < 0) {
        goto cleanup;
    }

    if (virtualSystemSettingData == NULL) {
804 805 806
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s for domain %s"),
                       "Msvm_VirtualSystemSettingData",
807
                       computerSystem->data.common->ElementName);
808 809 810 811
        goto cleanup;
    }

    /* Get Msvm_ProcessorSettingData */
L
Ladi Prosek 已提交
812 813 814 815 816 817
    virBufferEscapeSQL(&query,
                       "associators of "
                       "{Msvm_VirtualSystemSettingData.InstanceID=\"%s\"} "
                       "where AssocClass = Msvm_VirtualSystemSettingDataComponent "
                       "ResultClass = Msvm_ProcessorSettingData",
                       virtualSystemSettingData->data.common->InstanceID);
818 819 820 821 822 823 824

    if (hypervGetMsvmProcessorSettingDataList(priv, &query,
                                              &processorSettingData) < 0) {
        goto cleanup;
    }

    if (processorSettingData == NULL) {
825 826 827
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s for domain %s"),
                       "Msvm_ProcessorSettingData",
828
                       computerSystem->data.common->ElementName);
829 830 831 832
        goto cleanup;
    }

    /* Get Msvm_MemorySettingData */
L
Ladi Prosek 已提交
833 834 835 836 837 838
    virBufferEscapeSQL(&query,
                       "associators of "
                       "{Msvm_VirtualSystemSettingData.InstanceID=\"%s\"} "
                       "where AssocClass = Msvm_VirtualSystemSettingDataComponent "
                       "ResultClass = Msvm_MemorySettingData",
                       virtualSystemSettingData->data.common->InstanceID);
839 840 841 842 843 844 845 846

    if (hypervGetMsvmMemorySettingDataList(priv, &query,
                                           &memorySettingData) < 0) {
        goto cleanup;
    }


    if (memorySettingData == NULL) {
847 848 849
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not lookup %s for domain %s"),
                       "Msvm_MemorySettingData",
850
                       computerSystem->data.common->ElementName);
851 852 853 854 855 856 857
        goto cleanup;
    }

    /* Fill struct */
    def->virtType = VIR_DOMAIN_VIRT_HYPERV;

    if (hypervIsMsvmComputerSystemActive(computerSystem, NULL)) {
858
        def->id = computerSystem->data.common->ProcessID;
859 860 861 862
    } else {
        def->id = -1;
    }

863
    if (virUUIDParse(computerSystem->data.common->Name, def->uuid) < 0) {
864 865
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not parse UUID from string '%s'"),
866
                       computerSystem->data.common->Name);
867 868 869
        return NULL;
    }

870
    if (VIR_STRDUP(def->name, computerSystem->data.common->ElementName) < 0)
871 872
        goto cleanup;

873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
    if (priv->wmiVersion == HYPERV_WMI_VERSION_V1) {
        if (VIR_STRDUP(def->description,
                       virtualSystemSettingData->data.v1->Notes) < 0)
            goto cleanup;
    } else if (priv->wmiVersion == HYPERV_WMI_VERSION_V2 &&
               virtualSystemSettingData->data.v2->Notes.data != NULL) {
        char **notes = (char **)virtualSystemSettingData->data.v2->Notes.data;
        virBuffer buf = VIR_BUFFER_INITIALIZER;
        size_t i = 0;

        /* in practice Notes has 1 element */
        for (i = 0; i < virtualSystemSettingData->data.v2->Notes.count; i++) {
            /* but if there's more than 1, separate by double new line */
            if (virBufferUse(&buf) > 0)
                virBufferAddLit(&buf, "\n\n");

            virBufferAdd(&buf, *notes, -1);
            notes++;
        }

        if (virBufferCheckError(&buf))
            goto cleanup;

        def->description = virBufferContentAndReset(&buf);
    }
898

899 900 901 902
    /* mebibytes to kibibytes */
    def->mem.max_memory = memorySettingData->data.common->Limit * 1024;
    def->mem.cur_balloon = memorySettingData->data.common->VirtualQuantity * 1024;
    virDomainDefSetMemoryTotal(def, memorySettingData->data.common->VirtualQuantity * 1024);
903

904
    if (virDomainDefSetVcpusMax(def,
905
                                processorSettingData->data.common->VirtualQuantity,
906
                                NULL) < 0)
907 908
        goto cleanup;

909
    if (virDomainDefSetVcpus(def,
910
                             processorSettingData->data.common->VirtualQuantity) < 0)
911 912
        goto cleanup;

913
    def->os.type = VIR_DOMAIN_OSTYPE_HVM;
914 915 916

    /* FIXME: devices section is totally missing */

917
    xml = virDomainDefFormat(def, NULL,
918
                             virDomainDefFormatConvertXMLFlags(flags));
919

920
 cleanup:
921 922 923 924 925 926 927 928 929 930 931 932
    virDomainDefFree(def);
    hypervFreeObject(priv, (hypervObject *)computerSystem);
    hypervFreeObject(priv, (hypervObject *)virtualSystemSettingData);
    hypervFreeObject(priv, (hypervObject *)processorSettingData);
    hypervFreeObject(priv, (hypervObject *)memorySettingData);

    return xml;
}



static int
933
hypervConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxnames)
934 935 936 937 938 939 940
{
    bool success = false;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystemList = NULL;
    Msvm_ComputerSystem *computerSystem = NULL;
    int count = 0;
941
    size_t i;
942

943
    if (maxnames == 0)
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
        return 0;

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);
    virBufferAddLit(&query, "and ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_INACTIVE);

    if (hypervGetMsvmComputerSystemList(priv, &query,
                                        &computerSystemList) < 0) {
        goto cleanup;
    }

    for (computerSystem = computerSystemList; computerSystem != NULL;
         computerSystem = computerSystem->next) {
959
        if (VIR_STRDUP(names[count], computerSystem->data.common->ElementName) < 0)
960 961 962 963
            goto cleanup;

        ++count;

964
        if (count >= maxnames)
965 966 967 968 969
            break;
    }

    success = true;

970
 cleanup:
971
    if (!success) {
972
        for (i = 0; i < count; ++i)
973 974 975 976 977 978 979 980
            VIR_FREE(names[i]);

        count = -1;
    }

    hypervFreeObject(priv, (hypervObject *)computerSystemList);

    return count;
M
Matthias Bolte 已提交
981 982 983 984 985
}



static int
986
hypervConnectNumOfDefinedDomains(virConnectPtr conn)
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
{
    bool success = false;
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystemList = NULL;
    Msvm_ComputerSystem *computerSystem = NULL;
    int count = 0;

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);
    virBufferAddLit(&query, "and ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_INACTIVE);

    if (hypervGetMsvmComputerSystemList(priv, &query,
                                        &computerSystemList) < 0) {
        goto cleanup;
    }

    for (computerSystem = computerSystemList; computerSystem != NULL;
         computerSystem = computerSystem->next) {
        ++count;
    }

    success = true;

1013
 cleanup:
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    hypervFreeObject(priv, (hypervObject *)computerSystemList);

    return success ? count : -1;
}



static int
hypervDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;

    virCheckFlags(0, -1);

1030
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
1031 1032 1033
        goto cleanup;

    if (hypervIsMsvmComputerSystemActive(computerSystem, NULL)) {
1034 1035
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is already active or is in state transition"));
1036 1037 1038 1039 1040 1041
        goto cleanup;
    }

    result = hypervInvokeMsvmComputerSystemRequestStateChange
               (domain, MSVM_COMPUTERSYSTEM_REQUESTEDSTATE_ENABLED);

1042
 cleanup:
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static int
hypervDomainCreate(virDomainPtr domain)
{
    return hypervDomainCreateWithFlags(domain, 0);
}



static int
1059
hypervConnectIsEncrypted(virConnectPtr conn)
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
{
    hypervPrivate *priv = conn->privateData;

    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
        return 1;
    } else {
        return 0;
    }
}



static int
1073
hypervConnectIsSecure(virConnectPtr conn)
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
{
    hypervPrivate *priv = conn->privateData;

    if (STRCASEEQ(priv->parsedUri->transport, "https")) {
        return 1;
    } else {
        return 0;
    }
}



1086
static int
1087
hypervConnectIsAlive(virConnectPtr conn)
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
{
    hypervPrivate *priv = conn->privateData;

    /* XXX we should be able to do something better than this is simple, safe,
     * and good enough for now. In worst case, the function will return true
     * even though the connection is not alive.
     */
    if (priv->client)
        return 1;
    else
        return 0;
}



1103 1104 1105 1106 1107 1108 1109
static int
hypervDomainIsActive(virDomainPtr domain)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;

1110
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
1111 1112 1113 1114
        goto cleanup;

    result = hypervIsMsvmComputerSystemActive(computerSystem, NULL) ? 1 : 0;

1115
 cleanup:
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static int
hypervDomainIsPersistent(virDomainPtr domain ATTRIBUTE_UNUSED)
{
    /* Hyper-V has no concept of transient domains, so all of them are persistent */
    return 1;
}



static int
hypervDomainIsUpdated(virDomainPtr domain ATTRIBUTE_UNUSED)
M
Matthias Bolte 已提交
1134 1135 1136 1137 1138 1139
{
    return 0;
}



1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
static int
hypervDomainManagedSave(virDomainPtr domain, unsigned int flags)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;
    bool in_transition = false;

    virCheckFlags(0, -1);

1150
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
1151 1152 1153 1154
        goto cleanup;

    if (!hypervIsMsvmComputerSystemActive(computerSystem, &in_transition) ||
        in_transition) {
1155 1156
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not active or is in state transition"));
1157 1158 1159 1160 1161 1162
        goto cleanup;
    }

    result = hypervInvokeMsvmComputerSystemRequestStateChange
               (domain, MSVM_COMPUTERSYSTEM_REQUESTEDSTATE_SUSPENDED);

1163
 cleanup:
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static int
hypervDomainHasManagedSaveImage(virDomainPtr domain, unsigned int flags)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;

    virCheckFlags(0, -1);

1180
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
1181 1182
        goto cleanup;

1183
    result = computerSystem->data.common->EnabledState ==
1184 1185
             MSVM_COMPUTERSYSTEM_ENABLEDSTATE_SUSPENDED ? 1 : 0;

1186
 cleanup:
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}



static int
hypervDomainManagedSaveRemove(virDomainPtr domain, unsigned int flags)
{
    int result = -1;
    hypervPrivate *priv = domain->conn->privateData;
    Msvm_ComputerSystem *computerSystem = NULL;

    virCheckFlags(0, -1);

1203
    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
1204 1205
        goto cleanup;

1206
    if (computerSystem->data.common->EnabledState !=
1207
        MSVM_COMPUTERSYSTEM_ENABLEDSTATE_SUSPENDED) {
1208 1209
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain has no managed save image"));
1210 1211 1212 1213 1214 1215
        goto cleanup;
    }

    result = hypervInvokeMsvmComputerSystemRequestStateChange
               (domain, MSVM_COMPUTERSYSTEM_REQUESTEDSTATE_DISABLED);

1216
 cleanup:
1217 1218 1219 1220 1221 1222
    hypervFreeObject(priv, (hypervObject *)computerSystem);

    return result;
}


1223 1224
#define MATCH(FLAG) (flags & (FLAG))
static int
1225 1226 1227
hypervConnectListAllDomains(virConnectPtr conn,
                            virDomainPtr **domains,
                            unsigned int flags)
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
{
    hypervPrivate *priv = conn->privateData;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    Msvm_ComputerSystem *computerSystemList = NULL;
    Msvm_ComputerSystem *computerSystem = NULL;
    size_t ndoms;
    virDomainPtr domain;
    virDomainPtr *doms = NULL;
    int count = 0;
    int ret = -1;
1238
    size_t i;
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);

    /* check for filter combinations that return no results:
     * persistent: all hyperv guests are persistent
     * snapshot: the driver does not support snapshot management
     * autostart: the driver does not support autostarting guests
     */
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT))) {
1253 1254
        if (domains && VIR_ALLOC_N(*domains, 1) < 0)
            goto cleanup;
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264

        ret = 0;
        goto cleanup;
    }

    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_SELECT);
    virBufferAddLit(&query, "where ");
    virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_VIRTUAL);

    /* construct query with filter depending on flags */
1265 1266 1267
    if (!(MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) &&
          MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE))) {
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE)) {
1268 1269 1270
            virBufferAddLit(&query, "and ");
            virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_ACTIVE);
        }
1271 1272

        if (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE)) {
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
            virBufferAddLit(&query, "and ");
            virBufferAddLit(&query, MSVM_COMPUTERSYSTEM_WQL_INACTIVE);
        }
    }

    if (hypervGetMsvmComputerSystemList(priv, &query,
                                        &computerSystemList) < 0)
        goto cleanup;

    if (domains) {
        if (VIR_ALLOC_N(doms, 1) < 0)
1284
            goto cleanup;
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        ndoms = 1;
    }

    for (computerSystem = computerSystemList; computerSystem != NULL;
         computerSystem = computerSystem->next) {

        /* filter by domain state */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE)) {
            int st = hypervMsvmComputerSystemEnabledStateToDomainState(computerSystem);
            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
                   st == VIR_DOMAIN_RUNNING) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
                   st == VIR_DOMAIN_PAUSED) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
                   st == VIR_DOMAIN_SHUTOFF) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
                   (st != VIR_DOMAIN_RUNNING &&
                    st != VIR_DOMAIN_PAUSED &&
                    st != VIR_DOMAIN_SHUTOFF))))
                continue;
        }

        /* managed save filter */
        if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_MANAGEDSAVE)) {
1309
            bool mansave = computerSystem->data.common->EnabledState ==
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
                           MSVM_COMPUTERSYSTEM_ENABLEDSTATE_SUSPENDED;

            if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) && mansave) ||
                  (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE) && !mansave)))
                continue;
        }

        if (!doms) {
            count++;
            continue;
        }

1322
        if (VIR_RESIZE_N(doms, ndoms, count, 2) < 0)
1323
            goto cleanup;
1324

1325 1326
        domain = NULL;

1327 1328 1329 1330
        if (hypervMsvmComputerSystemToDomain(conn, computerSystem,
                                             &domain) < 0)
            goto cleanup;

1331
        doms[count++] = domain;
1332 1333 1334 1335 1336 1337 1338
    }

    if (doms)
        *domains = doms;
    doms = NULL;
    ret = count;

1339
 cleanup:
1340
    if (doms) {
1341
        for (i = 0; i < count; ++i)
1342
            virObjectUnref(doms[i]);
1343 1344

        VIR_FREE(doms);
1345 1346 1347
    }

    hypervFreeObject(priv, (hypervObject *)computerSystemList);
1348

1349 1350 1351 1352 1353
    return ret;
}
#undef MATCH


S
Sri Ramanujam 已提交
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
static int
hypervDomainSendKey(virDomainPtr domain, unsigned int codeset,
        unsigned int holdtime, unsigned int *keycodes, int nkeycodes,
        unsigned int flags)
{
    int result = -1;
    size_t i = 0;
    int keycode = 0;
    int *translatedKeycodes = NULL;
    hypervPrivate *priv = domain->conn->privateData;
    char uuid_string[VIR_UUID_STRING_BUFLEN];
    char *selector = NULL;
    Msvm_ComputerSystem *computerSystem = NULL;
    Msvm_Keyboard *keyboard = NULL;
    virBuffer query = VIR_BUFFER_INITIALIZER;
    hypervInvokeParamsListPtr params = NULL;
    char keycodeStr[INT_BUFSIZE_BOUND(int)];

    virCheckFlags(0, -1);

    virUUIDFormat(domain->uuid, uuid_string);

    if (hypervMsvmComputerSystemFromDomain(domain, &computerSystem) < 0)
        goto cleanup;

L
Ladi Prosek 已提交
1379
    virBufferEscapeSQL(&query,
S
Sri Ramanujam 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
            "associators of "
            "{Msvm_ComputerSystem.CreationClassName=\"Msvm_ComputerSystem\","
            "Name=\"%s\"} "
            "where ResultClass = Msvm_Keyboard",
            uuid_string);

    if (hypervGetMsvmKeyboardList(priv, &query, &keyboard) < 0)
        goto cleanup;

    if (VIR_ALLOC_N(translatedKeycodes, nkeycodes) < 0)
        goto cleanup;

    /* translate keycodes to win32 and generate keyup scancodes. */
    for (i = 0; i < nkeycodes; i++) {
        if (codeset != VIR_KEYCODE_SET_WIN32) {
            keycode = virKeycodeValueTranslate(codeset, VIR_KEYCODE_SET_WIN32,
                    keycodes[i]);

            if (keycode < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("Could not translate keycode"));
                goto cleanup;
            }
            translatedKeycodes[i] = keycode;
        }
    }

    if (virAsprintf(&selector,
                "CreationClassName=Msvm_Keyboard&DeviceID=%s&"
                "SystemCreationClassName=Msvm_ComputerSystem&"
                "SystemName=%s", keyboard->data.common->DeviceID, uuid_string) < 0)
        goto cleanup;

    /* press the keys */
    for (i = 0; i < nkeycodes; i++) {
        snprintf(keycodeStr, sizeof(keycodeStr), "%d", translatedKeycodes[i]);

        params = hypervCreateInvokeParamsList(priv, "PressKey", selector,
                Msvm_Keyboard_WmiInfo);

        if (!params) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create param"));
            goto cleanup;
        }

        if (hypervAddSimpleParam(params, "keyCode", keycodeStr) < 0) {
            hypervFreeInvokeParams(params);
            goto cleanup;
        }

        if (hypervInvokeMethod(priv, params, NULL) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not press key %d"),
                           translatedKeycodes[i]);
            goto cleanup;
        }
    }

    /* simulate holdtime by sleeping */
    if (holdtime > 0)
        usleep(holdtime * 1000);

    /* release the keys */
    for (i = 0; i < nkeycodes; i++) {
        snprintf(keycodeStr, sizeof(keycodeStr), "%d", translatedKeycodes[i]);
        params = hypervCreateInvokeParamsList(priv, "ReleaseKey", selector,
                Msvm_Keyboard_WmiInfo);

        if (!params) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create param"));
            goto cleanup;
        }

        if (hypervAddSimpleParam(params, "keyCode", keycodeStr) < 0) {
            hypervFreeInvokeParams(params);
            goto cleanup;
        }

        if (hypervInvokeMethod(priv, params, NULL) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not release key %s"),
                    keycodeStr);
            goto cleanup;
        }
    }

    result = 0;

 cleanup:
    VIR_FREE(translatedKeycodes);
    VIR_FREE(selector);
    hypervFreeObject(priv, (hypervObject *) keyboard);
    hypervFreeObject(priv, (hypervObject *) computerSystem);
    virBufferFreeAndReset(&query);
    return result;
}
1474

1475

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
static int
hypervDomainSetMemoryFlags(virDomainPtr domain, unsigned long memory,
        unsigned int flags)
{
    int result = -1;
    char uuid_string[VIR_UUID_STRING_BUFLEN];
    hypervPrivate *priv = domain->conn->privateData;
    char *memory_str = NULL;
    hypervInvokeParamsListPtr params = NULL;
    unsigned long memory_mb = VIR_ROUND_UP(VIR_DIV_UP(memory, 1024), 2);
    Msvm_VirtualSystemSettingData *vssd = NULL;
    Msvm_MemorySettingData *memsd = NULL;
    virBuffer eprQuery = VIR_BUFFER_INITIALIZER;
    virHashTablePtr memResource = NULL;

    virCheckFlags(0, -1);

    if (virAsprintf(&memory_str, "%lu", memory_mb) < 0)
        goto cleanup;

    virUUIDFormat(domain->uuid, uuid_string);

    if (hypervGetMsvmVirtualSystemSettingDataFromUUID(priv, uuid_string, &vssd) < 0)
        goto cleanup;

    if (hypervGetMsvmMemorySettingDataFromVSSD(priv, vssd->data.common->InstanceID,
                &memsd) < 0)
        goto cleanup;

    if (priv->wmiVersion == HYPERV_WMI_VERSION_V1) {
        params = hypervCreateInvokeParamsList(priv, "ModifyVirtualSystemResources",
                MSVM_VIRTUALSYSTEMMANAGEMENTSERVICE_SELECTOR,
                Msvm_VirtualSystemManagementService_WmiInfo);

        if (!params) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create params"));
            goto cleanup;
        }

        virBufferAddLit(&eprQuery, MSVM_COMPUTERSYSTEM_WQL_SELECT);
L
Ladi Prosek 已提交
1516
        virBufferEscapeSQL(&eprQuery, "where Name = \"%s\"", uuid_string);
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587

        if (hypervAddEprParam(params, "ComputerSystem", priv, &eprQuery,
                    Msvm_ComputerSystem_WmiInfo) < 0)
            goto params_cleanup;
    } else if (priv->wmiVersion == HYPERV_WMI_VERSION_V2) {
        params = hypervCreateInvokeParamsList(priv, "ModifyResourceSettings",
                MSVM_VIRTUALSYSTEMMANAGEMENTSERVICE_SELECTOR,
                Msvm_VirtualSystemManagementService_WmiInfo);

        if (!params) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not create params"));
            goto cleanup;
        }
    }

    memResource = hypervCreateEmbeddedParam(priv, Msvm_MemorySettingData_WmiInfo);
    if (!memResource)
        goto params_cleanup;

    if (hypervSetEmbeddedProperty(memResource, "VirtualQuantity", memory_str) < 0) {
        hypervFreeEmbeddedParam(memResource);
        goto params_cleanup;
    }

    if (hypervSetEmbeddedProperty(memResource, "InstanceID",
                memsd->data.common->InstanceID) < 0) {
        hypervFreeEmbeddedParam(memResource);
        goto params_cleanup;
    }

    if (priv->wmiVersion == HYPERV_WMI_VERSION_V1) {
        if (hypervAddEmbeddedParam(params, priv, "ResourceSettingData",
                    memResource, Msvm_MemorySettingData_WmiInfo) < 0) {
            hypervFreeEmbeddedParam(memResource);
            goto params_cleanup;
        }

    } else if (priv->wmiVersion == HYPERV_WMI_VERSION_V2) {
        if (hypervAddEmbeddedParam(params, priv, "ResourceSettings",
                    memResource, Msvm_MemorySettingData_WmiInfo) < 0) {
            hypervFreeEmbeddedParam(memResource);
            goto params_cleanup;
        }
    }

    if (hypervInvokeMethod(priv, params, NULL) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Could not set memory"));
        goto cleanup;
    }

    result = 0;
    goto cleanup;

 params_cleanup:
    hypervFreeInvokeParams(params);
    virBufferFreeAndReset(&eprQuery);
 cleanup:
    VIR_FREE(memory_str);
    hypervFreeObject(priv, (hypervObject *) vssd);
    hypervFreeObject(priv, (hypervObject *) memsd);
    return result;
}


static int
hypervDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
    return hypervDomainSetMemoryFlags(domain, memory, 0);
}


1588
static virHypervisorDriver hypervHypervisorDriver = {
M
Matthias Bolte 已提交
1589
    .name = "Hyper-V",
1590 1591 1592 1593
    .connectOpen = hypervConnectOpen, /* 0.9.5 */
    .connectClose = hypervConnectClose, /* 0.9.5 */
    .connectGetType = hypervConnectGetType, /* 0.9.5 */
    .connectGetHostname = hypervConnectGetHostname, /* 0.9.5 */
1594
    .nodeGetInfo = hypervNodeGetInfo, /* 0.9.5 */
1595 1596 1597
    .connectListDomains = hypervConnectListDomains, /* 0.9.5 */
    .connectNumOfDomains = hypervConnectNumOfDomains, /* 0.9.5 */
    .connectListAllDomains = hypervConnectListAllDomains, /* 0.10.2 */
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
    .domainLookupByID = hypervDomainLookupByID, /* 0.9.5 */
    .domainLookupByUUID = hypervDomainLookupByUUID, /* 0.9.5 */
    .domainLookupByName = hypervDomainLookupByName, /* 0.9.5 */
    .domainSuspend = hypervDomainSuspend, /* 0.9.5 */
    .domainResume = hypervDomainResume, /* 0.9.5 */
    .domainDestroy = hypervDomainDestroy, /* 0.9.5 */
    .domainDestroyFlags = hypervDomainDestroyFlags, /* 0.9.5 */
    .domainGetOSType = hypervDomainGetOSType, /* 0.9.5 */
    .domainGetInfo = hypervDomainGetInfo, /* 0.9.5 */
    .domainGetState = hypervDomainGetState, /* 0.9.5 */
    .domainGetXMLDesc = hypervDomainGetXMLDesc, /* 0.9.5 */
1609 1610
    .connectListDefinedDomains = hypervConnectListDefinedDomains, /* 0.9.5 */
    .connectNumOfDefinedDomains = hypervConnectNumOfDefinedDomains, /* 0.9.5 */
1611 1612
    .domainCreate = hypervDomainCreate, /* 0.9.5 */
    .domainCreateWithFlags = hypervDomainCreateWithFlags, /* 0.9.5 */
1613 1614
    .connectIsEncrypted = hypervConnectIsEncrypted, /* 0.9.5 */
    .connectIsSecure = hypervConnectIsSecure, /* 0.9.5 */
1615 1616 1617 1618 1619 1620
    .domainIsActive = hypervDomainIsActive, /* 0.9.5 */
    .domainIsPersistent = hypervDomainIsPersistent, /* 0.9.5 */
    .domainIsUpdated = hypervDomainIsUpdated, /* 0.9.5 */
    .domainManagedSave = hypervDomainManagedSave, /* 0.9.5 */
    .domainHasManagedSaveImage = hypervDomainHasManagedSaveImage, /* 0.9.5 */
    .domainManagedSaveRemove = hypervDomainManagedSaveRemove, /* 0.9.5 */
S
Sri Ramanujam 已提交
1621
    .domainSendKey = hypervDomainSendKey, /* 3.6.0 */
1622 1623
    .domainSetMemory = hypervDomainSetMemory, /* 3.6.0 */
    .domainSetMemoryFlags = hypervDomainSetMemoryFlags, /* 3.6.0 */
1624
    .connectIsAlive = hypervConnectIsAlive, /* 0.9.8 */
M
Matthias Bolte 已提交
1625 1626 1627 1628
};



1629 1630 1631 1632 1633 1634 1635
static void
hypervDebugHandler(const char *message, debug_level_e level,
                   void *user_data ATTRIBUTE_UNUSED)
{
    switch (level) {
      case DEBUG_LEVEL_ERROR:
      case DEBUG_LEVEL_CRITICAL:
1636 1637
      case DEBUG_LEVEL_ALWAYS:
        VIR_ERROR(_("openwsman: %s"), message);
1638 1639 1640
        break;

      case DEBUG_LEVEL_WARNING:
1641
        VIR_WARN("openwsman: %s", message);
1642 1643
        break;

1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
      case DEBUG_LEVEL_MESSAGE:
        VIR_INFO("openwsman: %s", message);
        break;

      case DEBUG_LEVEL_INFO:
        VIR_INFO("openwsman: %s", message);
        break;

      case DEBUG_LEVEL_DEBUG:
        VIR_DEBUG("openwsman: %s", message);
        break;

      case DEBUG_LEVEL_NONE:
1657 1658 1659 1660 1661 1662 1663
      default:
        /* Ignore the rest */
        break;
    }
}


1664
static virConnectDriver hypervConnectDriver = {
1665
    .uriSchemes = (const char *[]){ "hyperv", NULL },
1666 1667
    .hypervisorDriver = &hypervHypervisorDriver,
};
1668

M
Matthias Bolte 已提交
1669 1670 1671
int
hypervRegister(void)
{
1672 1673 1674
    /* Forward openwsman errors and warnings to libvirt's logging */
    debug_add_handler(hypervDebugHandler, DEBUG_LEVEL_WARNING, NULL);

1675 1676
    return virRegisterConnectDriver(&hypervConnectDriver,
                                    false);
M
Matthias Bolte 已提交
1677
}