vz_sdk.c 123.1 KB
Newer Older
1
/*
2
 * vz_sdk.c: core driver functions for managing
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * Parallels Cloud Server hosts
 *
 * Copyright (C) 2014 Parallels, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 */

#include <config.h>
24
#include <stdarg.h>
25 26 27

#include "virerror.h"
#include "viralloc.h"
28 29 30
#include "virstring.h"
#include "nodeinfo.h"
#include "virlog.h"
31
#include "datatypes.h"
32
#include "domain_conf.h"
33
#include "virtime.h"
34
#include "virhostcpu.h"
35

36
#include "vz_sdk.h"
37 38 39 40

#define VIR_FROM_THIS VIR_FROM_PARALLELS
#define JOB_INFINIT_WAIT_TIMEOUT UINT_MAX

41 42 43
static int
prlsdkUUIDParse(const char *uuidstr, unsigned char *uuid);

44 45
VIR_LOG_INIT("parallels.sdk");

N
Nikolay Shirokovskiy 已提交
46 47 48 49 50
static PRL_HANDLE
prlsdkFindNetByMAC(PRL_HANDLE sdkdom, virMacAddrPtr mac);
static PRL_HANDLE
prlsdkGetDisk(PRL_HANDLE sdkdom, virDomainDiskDefPtr disk, bool isCt);

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
/*
 * Log error description
 */
static void
logPrlErrorHelper(PRL_RESULT err, const char *filename,
                  const char *funcname, size_t linenr)
{
    char *msg1 = NULL, *msg2 = NULL;
    PRL_UINT32 len = 0;

    /* Get required buffer length */
    PrlApi_GetResultDescription(err, PRL_TRUE, PRL_FALSE, NULL, &len);

    if (VIR_ALLOC_N(msg1, len) < 0)
        goto cleanup;

    /* get short error description */
    PrlApi_GetResultDescription(err, PRL_TRUE, PRL_FALSE, msg1, &len);

    PrlApi_GetResultDescription(err, PRL_FALSE, PRL_FALSE, NULL, &len);

    if (VIR_ALLOC_N(msg2, len) < 0)
        goto cleanup;

    /* get long error description */
    PrlApi_GetResultDescription(err, PRL_FALSE, PRL_FALSE, msg2, &len);

    virReportErrorHelper(VIR_FROM_THIS, VIR_ERR_INTERNAL_ERROR,
                         filename, funcname, linenr,
                         _("%s %s"), msg1, msg2);

 cleanup:
    VIR_FREE(msg1);
    VIR_FREE(msg2);
}

#define logPrlError(code)                          \
    logPrlErrorHelper(code, __FILE__,              \
M
Michal Privoznik 已提交
89
                      __FUNCTION__, __LINE__)
90

91 92 93 94 95 96 97 98
#define prlsdkCheckRetGoto(ret, label)             \
    do {                                           \
        if (PRL_FAILED(ret)) {                     \
            logPrlError(ret);                      \
            goto label;                            \
        }                                          \
    } while (0)

99 100 101 102 103 104 105 106
#define prlsdkCheckRetExit(ret, code)              \
    do {                                           \
        if (PRL_FAILED(ret)) {                     \
            logPrlError(ret);                      \
            return code;                           \
        }                                          \
    } while (0)

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
static PRL_RESULT
logPrlEventErrorHelper(PRL_HANDLE event, const char *filename,
                       const char *funcname, size_t linenr)
{
    PRL_RESULT ret, retCode;
    char *msg1 = NULL, *msg2 = NULL;
    PRL_UINT32 len = 0;
    int err = -1;

    if ((ret = PrlEvent_GetErrCode(event, &retCode))) {
        logPrlError(ret);
        return ret;
    }

    PrlEvent_GetErrString(event, PRL_TRUE, PRL_FALSE, NULL, &len);

    if (VIR_ALLOC_N(msg1, len) < 0)
        goto cleanup;

    PrlEvent_GetErrString(event, PRL_TRUE, PRL_FALSE, msg1, &len);

    PrlEvent_GetErrString(event, PRL_FALSE, PRL_FALSE, NULL, &len);

    if (VIR_ALLOC_N(msg2, len) < 0)
        goto cleanup;

    PrlEvent_GetErrString(event, PRL_FALSE, PRL_FALSE, msg2, &len);

    virReportErrorHelper(VIR_FROM_THIS, VIR_ERR_INTERNAL_ERROR,
                         filename, funcname, linenr,
                         _("%s %s"), msg1, msg2);
    err = 0;

 cleanup:
    VIR_FREE(msg1);
    VIR_FREE(msg2);

    return err;
}

147 148
static PRL_RESULT
getJobResultHelper(PRL_HANDLE job, unsigned int timeout, PRL_HANDLE *result,
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
                   const char *filename, const char *funcname,
                   size_t linenr)
{
    PRL_RESULT ret, retCode;

    if ((ret = PrlJob_Wait(job, timeout))) {
        logPrlErrorHelper(ret, filename, funcname, linenr);
        goto cleanup;
    }

    if ((ret = PrlJob_GetRetCode(job, &retCode))) {
        logPrlErrorHelper(ret, filename, funcname, linenr);
        goto cleanup;
    }

    if (retCode) {
        PRL_HANDLE err_handle;

        /* Sometimes it's possible to get additional error info. */
        if ((ret = PrlJob_GetError(job, &err_handle))) {
            logPrlErrorHelper(ret, filename, funcname, linenr);
            goto cleanup;
        }

        if (logPrlEventErrorHelper(err_handle, filename, funcname, linenr))
            logPrlErrorHelper(retCode, filename, funcname, linenr);

        PrlHandle_Free(err_handle);
177
        ret = retCode;
178
    } else {
179
        ret = PrlJob_GetResult(job, result);
180 181
        if (PRL_FAILED(ret)) {
            logPrlErrorHelper(ret, filename, funcname, linenr);
182 183
            PrlHandle_Free(*result);
            *result = NULL;
184 185
            goto cleanup;
        }
186 187

        ret = PRL_ERR_SUCCESS;
188
    }
189 190 191

 cleanup:
    PrlHandle_Free(job);
192
    return ret;
193 194
}

195 196
#define getJobResult(job, result)                       \
    getJobResultHelper(job, JOB_INFINIT_WAIT_TIMEOUT,   \
M
Michal Privoznik 已提交
197
                       result, __FILE__, __FUNCTION__, __LINE__)
198

199
static PRL_RESULT
200 201 202 203
waitJobHelper(PRL_HANDLE job, unsigned int timeout,
              const char *filename, const char *funcname,
              size_t linenr)
{
204 205
    PRL_HANDLE result = PRL_INVALID_HANDLE;
    PRL_RESULT ret;
206

207 208 209 210
    ret = getJobResultHelper(job, timeout, &result,
                             filename, funcname, linenr);
    PrlHandle_Free(result);
    return ret;
211 212
}

213 214
#define waitJob(job)                                        \
    waitJobHelper(job, JOB_INFINIT_WAIT_TIMEOUT, __FILE__,  \
M
Michal Privoznik 已提交
215
                  __FUNCTION__, __LINE__)
216

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
typedef PRL_RESULT (*prlsdkParamGetterType)(PRL_HANDLE, char*, PRL_UINT32*);

static char*
prlsdkGetStringParamVar(prlsdkParamGetterType getter, PRL_HANDLE handle)
{
    PRL_RESULT pret;
    PRL_UINT32 buflen = 0;
    char *str = NULL;

    pret = getter(handle, NULL, &buflen);
    prlsdkCheckRetGoto(pret, error);

    if (VIR_ALLOC_N(str, buflen) < 0)
        goto error;

    pret = getter(handle, str, &buflen);
    prlsdkCheckRetGoto(pret, error);

    return str;

 error:
    VIR_FREE(str);
    return NULL;
}

static PRL_RESULT
prlsdkGetStringParamBuf(prlsdkParamGetterType getter,
                        PRL_HANDLE handle, char *buf, size_t size)
{
    PRL_UINT32 buflen = size;
    return getter(handle, buf, &buflen);
}
249

250
int
251
prlsdkInit(void)
252 253 254
{
    PRL_RESULT ret;

255 256 257
    /* Disable console output */
    PrlApi_SwitchConsoleLogging(0);

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    ret = PrlApi_InitEx(PARALLELS_API_VER, PAM_SERVER, 0, 0);
    if (PRL_FAILED(ret)) {
        logPrlError(ret);
        return -1;
    }

    return 0;
};

void
prlsdkDeinit(void)
{
    PrlApi_Deinit();
};

int
274
prlsdkConnect(vzDriverPtr driver)
275
{
276 277
    int ret = -1;
    PRL_RESULT pret;
278
    PRL_HANDLE job = PRL_INVALID_HANDLE;
279 280
    PRL_HANDLE result = PRL_INVALID_HANDLE;
    PRL_HANDLE response = PRL_INVALID_HANDLE;
281
    char session_uuid[VIR_UUID_STRING_BRACED_BUFLEN];
282

283 284
    pret = PrlSrv_Create(&driver->server);
    prlsdkCheckRetExit(pret, -1);
285

286
    job = PrlSrv_LoginLocalEx(driver->server, NULL, 0,
287
                              PSL_HIGH_SECURITY, PACF_NON_INTERACTIVE_MODE);
288 289 290 291 292
    if (PRL_FAILED(getJobResult(job, &result)))
        goto cleanup;

    pret = PrlResult_GetParam(result, &response);
    prlsdkCheckRetGoto(pret, cleanup);
293

294 295 296 297 298 299 300 301 302 303 304
    pret = prlsdkGetStringParamBuf(PrlLoginResponse_GetSessionUuid,
                                   response, session_uuid, sizeof(session_uuid));
    prlsdkCheckRetGoto(pret, cleanup);

    if (prlsdkUUIDParse(session_uuid, driver->session_uuid) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    if (ret < 0) {
305
        PrlHandle_Free(driver->server);
306
        driver->server = PRL_INVALID_HANDLE;
307 308
    }

309 310 311 312
    PrlHandle_Free(result);
    PrlHandle_Free(response);

    return ret;
313 314 315
}

void
316
prlsdkDisconnect(vzDriverPtr driver)
317 318 319
{
    PRL_HANDLE job;

320
    job = PrlSrv_Logoff(driver->server);
321
    waitJob(job);
322

323
    PrlHandle_Free(driver->server);
324
}
325 326

static int
327
prlsdkSdkDomainLookup(vzDriverPtr driver,
328 329 330 331 332 333 334 335 336
                      const char *id,
                      unsigned int flags,
                      PRL_HANDLE *sdkdom)
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;
    PRL_HANDLE result = PRL_INVALID_HANDLE;
    PRL_RESULT pret = PRL_ERR_UNINITIALIZED;
    int ret = -1;

337
    job = PrlSrv_GetVmConfig(driver->server, id, flags);
338
    if (PRL_FAILED(getJobResult(job, &result)))
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        goto cleanup;

    pret = PrlResult_GetParamByIndex(result, 0, sdkdom);
    prlsdkCheckRetGoto(pret, cleanup);

    ret = 0;

 cleanup:
    PrlHandle_Free(result);
    return ret;
}

static void
prlsdkUUIDFormat(const unsigned char *uuid, char *uuidstr)
{
    virUUIDFormat(uuid, uuidstr + 1);

    uuidstr[0] = '{';
    uuidstr[VIR_UUID_STRING_BUFLEN] = '}';
    uuidstr[VIR_UUID_STRING_BUFLEN + 1] = '\0';
}

static PRL_HANDLE
362
prlsdkSdkDomainLookupByUUID(vzDriverPtr driver, const unsigned char *uuid)
363
{
364
    char uuidstr[VIR_UUID_STRING_BRACED_BUFLEN];
365 366 367 368
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;

    prlsdkUUIDFormat(uuid, uuidstr);

369
    if (prlsdkSdkDomainLookup(driver, uuidstr,
370 371 372 373 374 375 376 377 378 379
                              PGVC_SEARCH_BY_UUID, &sdkdom) < 0) {
        virUUIDFormat(uuid, uuidstr);
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
        return PRL_INVALID_HANDLE;
    }

    return sdkdom;
}

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
PRL_HANDLE
prlsdkSdkDomainLookupByName(vzDriverPtr driver, const char *name)
{
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;

    if (prlsdkSdkDomainLookup(driver, name,
                              PGVC_SEARCH_BY_NAME, &sdkdom) < 0) {
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching name '%s'"), name);
        return PRL_INVALID_HANDLE;
    }

    return sdkdom;
}

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
static int
prlsdkUUIDParse(const char *uuidstr, unsigned char *uuid)
{
    char *tmp = NULL;
    int ret = -1;

    virCheckNonNullArgGoto(uuidstr, error);
    virCheckNonNullArgGoto(uuid, error);

    if (VIR_STRDUP(tmp, uuidstr) < 0)
        goto error;

    tmp[strlen(tmp) - 1] = '\0';

    /* trim curly braces */
410
    if (virUUIDParse(tmp + 1, uuid) < 0)
411 412 413 414 415 416 417 418 419 420 421 422 423
        goto error;

    ret = 0;
 error:
    VIR_FREE(tmp);
    return ret;
}

static int
prlsdkGetDomainIds(PRL_HANDLE sdkdom,
                   char **name,
                   unsigned char *uuid)
{
424
    char uuidstr[VIR_UUID_STRING_BRACED_BUFLEN];
425 426
    PRL_RESULT pret;

427 428
    if (name && !(*name = prlsdkGetStringParamVar(PrlVmCfg_GetName, sdkdom)))
        goto error;
429

430
    if (uuid) {
431 432
        pret = prlsdkGetStringParamBuf(PrlVmCfg_GetUuid,
                                       sdkdom, uuidstr, sizeof(uuidstr));
433
        prlsdkCheckRetGoto(pret, error);
434

435 436 437 438 439
        if (prlsdkUUIDParse(uuidstr, uuid) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Domain UUID is malformed or empty"));
            goto error;
        }
440
    }
441 442 443 444

    return 0;

 error:
445 446
    if (name)
        VIR_FREE(*name);
447 448 449 450
    return -1;
}

static int
451
prlsdkGetDomainState(PRL_HANDLE sdkdom, VIRTUAL_MACHINE_STATE_PTR vmState)
452 453 454 455 456 457 458 459 460
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;
    PRL_HANDLE result = PRL_INVALID_HANDLE;
    PRL_HANDLE vmInfo = PRL_INVALID_HANDLE;
    PRL_RESULT pret;
    int ret = -1;

    job = PrlVm_GetState(sdkdom);

461
    if (PRL_FAILED(getJobResult(job, &result)))
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        goto cleanup;

    pret = PrlResult_GetParamByIndex(result, 0, &vmInfo);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmInfo_GetState(vmInfo, vmState);
    prlsdkCheckRetGoto(pret, cleanup);

    ret = 0;

 cleanup:
    PrlHandle_Free(vmInfo);
    PrlHandle_Free(result);
    return ret;
}

478
void
479 480
prlsdkDomObjFreePrivate(void *p)
{
481
    vzDomObjPtr pdom = p;
482 483 484 485 486

    if (!pdom)
        return;

    PrlHandle_Free(pdom->sdkdom);
487
    PrlHandle_Free(pdom->stats);
488 489 490 491
    VIR_FREE(p);
};

static int
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
prlsdkAddDomainVideoInfoCt(virDomainDefPtr def)
{
    virDomainVideoDefPtr video = NULL;
    int ret = -1;

    if (def->ngraphics == 0)
        return 0;

    if (VIR_ALLOC(video) < 0)
        goto cleanup;

    video->type = VIR_DOMAIN_VIDEO_TYPE_PARALLELS;
    video->vram = 0;
    video->heads = 1;

    if (VIR_APPEND_ELEMENT(def->videos, def->nvideos, video) < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    virDomainVideoDefFree(video);

    return ret;
}

static int
prlsdkAddDomainVideoInfoVm(PRL_HANDLE sdkdom, virDomainDefPtr def)
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
{
    virDomainVideoDefPtr video = NULL;
    virDomainVideoAccelDefPtr accel = NULL;
    PRL_RESULT ret;
    PRL_UINT32 videoRam;

    /* video info */
    ret = PrlVmCfg_GetVideoRamSize(sdkdom, &videoRam);
    prlsdkCheckRetGoto(ret, error);

    if (VIR_ALLOC(video) < 0)
        goto error;

    if (VIR_ALLOC(accel) < 0)
        goto error;

    if (VIR_APPEND_ELEMENT_COPY(def->videos, def->nvideos, video) < 0)
        goto error;

    video->type = VIR_DOMAIN_VIDEO_TYPE_VGA;
    video->vram = videoRam << 10; /* from mbibytes to kbibytes */
    video->heads = 1;
    video->accel = accel;

    return 0;

 error:
    VIR_FREE(accel);
    virDomainVideoDefFree(video);
    return -1;
}

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
static int
prlsdkGetDiskId(PRL_HANDLE disk, bool isCt, int *bus, char **dst)
{
    PRL_RESULT pret;
    PRL_UINT32 pos, ifType;

    pret = PrlVmDev_GetStackIndex(disk, &pos);
    prlsdkCheckRetExit(pret, -1);

    /* Let physical devices added to CT look like SATA disks */
    if (isCt) {
        ifType = PMS_SATA_DEVICE;
    } else {
        pret = PrlVmDev_GetIfaceType(disk, &ifType);
        prlsdkCheckRetExit(pret, -1);
    }

    switch (ifType) {
    case PMS_IDE_DEVICE:
        *bus = VIR_DOMAIN_DISK_BUS_IDE;
        *dst = virIndexToDiskName(pos, "hd");
        break;
    case PMS_SCSI_DEVICE:
        *bus = VIR_DOMAIN_DISK_BUS_SCSI;
        *dst = virIndexToDiskName(pos, "sd");
        break;
    case PMS_SATA_DEVICE:
        *bus = VIR_DOMAIN_DISK_BUS_SATA;
        *dst = virIndexToDiskName(pos, "sd");
        break;
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown disk bus: %X"), ifType);
        return -1;
    }

587 588 589
    if (NULL == *dst)
        return -1;

590 591 592
    return 0;
}

593
static int
594
prlsdkGetDiskInfo(vzDriverPtr driver,
595
                  PRL_HANDLE prldisk,
D
Dmitry Guryanov 已提交
596
                  virDomainDiskDefPtr disk,
597 598
                  bool isCdrom,
                  bool isCt)
599 600 601 602
{
    char *buf = NULL;
    PRL_RESULT pret;
    PRL_UINT32 emulatedType;
603
    virDomainDeviceDriveAddressPtr address;
604
    int busIdx, devIdx;
605 606 607 608 609 610
    int ret = -1;

    pret = PrlVmDev_GetEmulatedType(prldisk, &emulatedType);
    prlsdkCheckRetGoto(pret, cleanup);
    if (emulatedType == PDT_USE_IMAGE_FILE) {
        virDomainDiskSetType(disk, VIR_STORAGE_TYPE_FILE);
611
        if (isCdrom) {
612
            virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_RAW);
613 614
        } else {
            if (isCt)
615
                virDomainDiskSetFormat(disk, driver->vzCaps.ctDiskFormat);
616
            else
617
                virDomainDiskSetFormat(disk, driver->vzCaps.vmDiskFormat);
618
        }
619 620
    } else {
        virDomainDiskSetType(disk, VIR_STORAGE_TYPE_BLOCK);
621
        virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_RAW);
622 623
    }

624
    if (isCdrom) {
D
Dmitry Guryanov 已提交
625
        disk->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
626 627
        disk->src->readonly = true;
    } else {
D
Dmitry Guryanov 已提交
628
        disk->device = VIR_DOMAIN_DISK_DEVICE_DISK;
629
    }
D
Dmitry Guryanov 已提交
630

631
    if (!(buf = prlsdkGetStringParamVar(PrlVmDev_GetFriendlyName, prldisk)))
632 633
        goto cleanup;

634
    if (*buf != '\0' && virDomainDiskSetSource(disk, buf) < 0)
635 636
        goto cleanup;

637
    if (prlsdkGetDiskId(prldisk, isCt, &disk->bus, &disk->dst) < 0)
638 639
        goto cleanup;

640
    if (virDiskNameToBusDeviceIndex(disk, &busIdx, &devIdx) < 0)
641
        goto cleanup;
642

643 644 645 646 647
    address = &disk->info.addr.drive;
    address->bus = busIdx;
    address->target = 0;
    address->unit = devIdx;

648 649 650 651 652 653 654 655 656
    disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;

    ret = 0;

 cleanup:
    VIR_FREE(buf);
    return ret;
}

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
static int
prlsdkGetFSInfo(PRL_HANDLE prldisk,
                virDomainFSDefPtr fs)
{
    char *buf = NULL;
    int ret = -1;

    fs->type = VIR_DOMAIN_FS_TYPE_FILE;
    fs->fsdriver = VIR_DOMAIN_FS_DRIVER_TYPE_PLOOP;
    fs->accessmode = VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH;
    fs->wrpolicy = VIR_DOMAIN_FS_WRPOLICY_DEFAULT;
    fs->format = VIR_STORAGE_FILE_PLOOP;

    fs->readonly = false;
    fs->symlinksResolved = false;

673
    if (!(buf = prlsdkGetStringParamVar(PrlVmDev_GetImagePath, prldisk)))
674 675
        goto cleanup;

676
    fs->src->path = buf;
677 678
    buf = NULL;

679
    if (!(buf = prlsdkGetStringParamVar(PrlVmDevHd_GetMountPoint, prldisk)))
680 681 682 683 684 685 686 687 688 689 690 691
        goto cleanup;

    fs->dst = buf;
    buf = NULL;

    ret = 0;

 cleanup:
    VIR_FREE(buf);
    return ret;
}

692
static int
693
prlsdkAddDomainHardDisksInfo(vzDriverPtr driver, PRL_HANDLE sdkdom, virDomainDefPtr def)
694 695 696 697 698 699
{
    PRL_RESULT pret;
    PRL_UINT32 hddCount;
    PRL_UINT32 i;
    PRL_HANDLE hdd = PRL_INVALID_HANDLE;
    virDomainDiskDefPtr disk = NULL;
700
    virDomainFSDefPtr fs = NULL;
701 702 703 704 705

    pret = PrlVmCfg_GetHardDisksCount(sdkdom, &hddCount);
    prlsdkCheckRetGoto(pret, error);

    for (i = 0; i < hddCount; ++i) {
706 707 708

        PRL_UINT32 emulatedType;

709 710 711
        pret = PrlVmCfg_GetHardDisk(sdkdom, i, &hdd);
        prlsdkCheckRetGoto(pret, error);

712 713 714 715
        pret = PrlVmDev_GetEmulatedType(hdd, &emulatedType);
        prlsdkCheckRetGoto(pret, error);

        if (PDT_USE_REAL_DEVICE != emulatedType && IS_CT(def)) {
716

717
            if (!(fs = virDomainFSDefNew()))
718 719 720 721 722 723 724 725 726
                goto error;

            if (prlsdkGetFSInfo(hdd, fs) < 0)
                goto error;

            if (virDomainFSInsert(def, fs) < 0)
                goto error;

            fs = NULL;
727 728 729
            PrlHandle_Free(hdd);
            hdd = PRL_INVALID_HANDLE;
        } else {
730
            if (!(disk = virDomainDiskDefNew(NULL)))
731 732
                goto error;

733
            if (prlsdkGetDiskInfo(driver, hdd, disk, false, IS_CT(def)) < 0)
734 735
                goto error;

736
            if (virDomainDiskInsert(def, disk) < 0)
737
                goto error;
738 739 740 741

            disk = NULL;
            PrlHandle_Free(hdd);
            hdd = PRL_INVALID_HANDLE;
742 743 744 745 746 747 748 749
        }
    }

    return 0;

 error:
    PrlHandle_Free(hdd);
    virDomainDiskDefFree(disk);
750
    virDomainFSDefFree(fs);
751 752 753
    return -1;
}

D
Dmitry Guryanov 已提交
754
static int
755
prlsdkAddDomainOpticalDisksInfo(vzDriverPtr driver, PRL_HANDLE sdkdom, virDomainDefPtr def)
D
Dmitry Guryanov 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769
{
    PRL_RESULT pret;
    PRL_UINT32 cdromsCount;
    PRL_UINT32 i;
    PRL_HANDLE cdrom = PRL_INVALID_HANDLE;
    virDomainDiskDefPtr disk = NULL;

    pret = PrlVmCfg_GetOpticalDisksCount(sdkdom, &cdromsCount);
    prlsdkCheckRetGoto(pret, error);

    for (i = 0; i < cdromsCount; ++i) {
        pret = PrlVmCfg_GetOpticalDisk(sdkdom, i, &cdrom);
        prlsdkCheckRetGoto(pret, error);

770
        if (!(disk = virDomainDiskDefNew(NULL)))
D
Dmitry Guryanov 已提交
771 772
            goto error;

773
        if (prlsdkGetDiskInfo(driver, cdrom, disk, true, IS_CT(def)) < 0)
D
Dmitry Guryanov 已提交
774 775 776 777 778
            goto error;

        PrlHandle_Free(cdrom);
        cdrom = PRL_INVALID_HANDLE;

779
        if (virDomainDiskInsert(def, disk) < 0)
D
Dmitry Guryanov 已提交
780 781 782 783 784 785 786 787 788 789 790
            goto error;
    }

    return 0;

 error:
    PrlHandle_Free(cdrom);
    virDomainDiskDefFree(disk);
    return -1;
}

791
static virNetDevIPAddrPtr
792 793 794 795 796
prlsdkParseNetAddress(char *addr)
{
    char *maskstr = NULL;
    int nbits;
    virSocketAddr mask;
797
    virNetDevIPAddrPtr ip = NULL, ret = NULL;
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846

    if (!(maskstr = strchr(addr, '/')))
        goto cleanup;

    *maskstr = '\0';
    ++maskstr;

    if (VIR_ALLOC(ip) < 0)
        goto cleanup;

    if (virSocketAddrParse(&ip->address, addr, AF_UNSPEC) < 0)
        goto cleanup;

    if (virSocketAddrParse(&mask, maskstr, AF_UNSPEC) < 0)
        goto cleanup;

    if ((nbits = virSocketAddrGetNumNetmaskBits(&mask)) < 0)
        goto cleanup;
    ip->prefix = nbits;

    ret = ip;
    ip = NULL;

 cleanup:
    if (!ret)
        VIR_WARN("cannot parse network address '%s'", addr);

    VIR_FREE(ip);
    VIR_FREE(addr);

    return ret;
}

static int
prlsdkGetNetAddresses(PRL_HANDLE sdknet, virDomainNetDefPtr net)
{
    int ret = -1;
    PRL_HANDLE addrlist = PRL_INVALID_HANDLE;
    PRL_UINT32 num;
    size_t i;
    PRL_RESULT pret;

    pret = PrlVmDevNet_GetNetAddresses(sdknet, &addrlist);
    prlsdkCheckRetGoto(pret, cleanup);

    PrlStrList_GetItemsCount(addrlist, &num);
    prlsdkCheckRetGoto(pret, cleanup);

    for (i = 0; i < num; ++i) {
847
        virNetDevIPAddrPtr ip = NULL;
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
        PRL_UINT32 buflen = 0;
        char *addr;

        pret = PrlStrList_GetItem(addrlist, i, NULL, &buflen);
        prlsdkCheckRetGoto(pret, cleanup);

        if (VIR_ALLOC_N(addr, buflen) < 0)
            goto cleanup;

        pret = PrlStrList_GetItem(addrlist, i, addr, &buflen);
        prlsdkCheckRetGoto(pret, cleanup);

        if (!(ip = prlsdkParseNetAddress(addr)))
            continue;

863
        if (VIR_APPEND_ELEMENT(net->guestIP.ips, net->guestIP.nips, ip) < 0) {
864 865 866 867 868 869 870 871 872 873 874 875
            VIR_FREE(ip);
            goto cleanup;
        }
    }

    ret = 0;
 cleanup:

    PrlHandle_Free(addrlist);
    return ret;
}

876 877 878 879 880 881
static int
prlsdkGetRoutes(PRL_HANDLE sdknet, virDomainNetDefPtr net)
{
    int ret = -1;
    char *gw = NULL;
    char *gw6 = NULL;
882
    virNetDevIPRoutePtr route = NULL;
883 884 885 886 887 888 889 890

    if (!(gw = prlsdkGetStringParamVar(PrlVmDevNet_GetDefaultGateway, sdknet)))
        goto cleanup;

    if (!(gw6 = prlsdkGetStringParamVar(PrlVmDevNet_GetDefaultGatewayIPv6, sdknet)))
        goto cleanup;

    if (*gw != '\0') {
891 892

        if (!(route = virNetDevIPRouteCreate(_("Domain interface"),
893 894 895 896
                                               "ipv4", VIR_SOCKET_ADDR_IPV4_ALL,
                                               NULL, gw, 0, true, 0, false)))
            goto cleanup;

897
        if (VIR_APPEND_ELEMENT(net->guestIP.routes, net->guestIP.nroutes, route) < 0)
898 899 900 901
            goto cleanup;
    }

    if (*gw6 != '\0') {
902
        if (!(route = virNetDevIPRouteCreate(_("Domain interface"),
903 904 905 906
                                               "ipv6", VIR_SOCKET_ADDR_IPV6_ALL,
                                               NULL, gw6, 0, true, 0, false)))
            goto cleanup;

907
        if (VIR_APPEND_ELEMENT(net->guestIP.routes, net->guestIP.nroutes, route) < 0)
908 909 910 911 912 913
            goto cleanup;
    }

    ret = 0;

 cleanup:
914
    virNetDevIPRouteFree(route);
915 916 917 918 919 920
    VIR_FREE(gw);
    VIR_FREE(gw6);

    return ret;
}

921 922 923 924 925 926 927
static int
prlsdkGetNetInfo(PRL_HANDLE netAdapter, virDomainNetDefPtr net, bool isCt)
{
    char macstr[VIR_MAC_STRING_BUFLEN];
    PRL_UINT32 netAdapterIndex;
    PRL_UINT32 emulatedType;
    PRL_RESULT pret;
928
    PRL_BOOL isConnected, isMacFilter;
929 930 931 932
    int ret = -1;

    /* use device name, shown by prlctl as target device
     * for identifying network adapter in virDomainDefineXML */
933 934
    if (!(net->ifname = prlsdkGetStringParamVar(PrlVmDevNet_GetHostInterfaceName,
                                                netAdapter)))
935 936
        goto cleanup;

937 938 939
    pret = PrlVmDev_GetIndex(netAdapter, &netAdapterIndex);
    prlsdkCheckRetGoto(pret, cleanup);

940 941 942 943 944
    if (isCt && netAdapterIndex == (PRL_UINT32) -1) {
        /* venet devices don't have mac address and
         * always up */
        net->linkstate = VIR_DOMAIN_NET_INTERFACE_LINK_STATE_UP;
        if (VIR_STRDUP(net->data.network.name,
945
                       PARALLELS_DOMAIN_ROUTED_NETWORK_NAME) < 0)
946 947 948 949
            goto cleanup;
        return 0;
    }

950 951
    pret = prlsdkGetStringParamBuf(PrlVmDevNet_GetMacAddressCanonical,
                                   netAdapter, macstr, sizeof(macstr));
952 953 954 955 956
    prlsdkCheckRetGoto(pret, cleanup);

    if (virMacAddrParse(macstr, &net->mac) < 0)
        goto cleanup;

957 958 959
    if (prlsdkGetNetAddresses(netAdapter, net) < 0)
        goto cleanup;

960 961 962
    if (prlsdkGetRoutes(netAdapter, net) < 0)
        goto cleanup;

963 964 965 966 967
    pret = PrlVmDev_GetEmulatedType(netAdapter, &emulatedType);
    prlsdkCheckRetGoto(pret, cleanup);

    if (emulatedType == PNA_ROUTED) {
        if (VIR_STRDUP(net->data.network.name,
968
                       PARALLELS_DOMAIN_ROUTED_NETWORK_NAME) < 0)
969 970
            goto cleanup;
    } else {
971 972 973
        char *netid = NULL;

        if (!(netid =
974 975
              prlsdkGetStringParamVar(PrlVmDevNet_GetVirtualNetworkId,
                                      netAdapter)))
976 977
            goto cleanup;

978 979 980 981 982 983
        /*
         * We use VIR_DOMAIN_NET_TYPE_NETWORK for all network adapters
         * except those whose Virtual Network Id differ from Parallels
         * predefined ones such as PARALLELS_DOMAIN_BRIDGED_NETWORK_NAME
         * and PARALLELS_DONAIN_ROUTED_NETWORK_NAME
         */
984
        if (STRNEQ(netid, PARALLELS_DOMAIN_BRIDGED_NETWORK_NAME)) {
985
            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;
986 987 988 989 990
            net->data.network.name = netid;
        } else {
            net->type = VIR_DOMAIN_NET_TYPE_NETWORK;
            net->data.bridge.brname = netid;
        }
991

992 993
    }

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    if (!isCt) {
        PRL_VM_NET_ADAPTER_TYPE type;
        pret = PrlVmDevNet_GetAdapterType(netAdapter, &type);
        prlsdkCheckRetGoto(pret, cleanup);

        switch (type) {
        case PNT_RTL:
            if (VIR_STRDUP(net->model, "rtl8139") < 0)
                goto cleanup;
            break;
        case PNT_E1000:
            if (VIR_STRDUP(net->model, "e1000") < 0)
                goto cleanup;
            break;
        case PNT_VIRTIO:
            if (VIR_STRDUP(net->model, "virtio") < 0)
                goto cleanup;
            break;
        default:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown adapter type: %X"), type);
            goto cleanup;
        }
    }

1019 1020 1021 1022 1023 1024 1025 1026
    pret = PrlVmDev_IsConnected(netAdapter, &isConnected);
    prlsdkCheckRetGoto(pret, cleanup);

    if (isConnected)
        net->linkstate = VIR_DOMAIN_NET_INTERFACE_LINK_STATE_UP;
    else
        net->linkstate = VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN;

1027 1028 1029 1030 1031 1032
    pret = PrlVmDevNet_IsPktFilterPreventMacSpoof(netAdapter, &isMacFilter);
    prlsdkCheckRetGoto(pret, cleanup);

    net->trustGuestRxFilters = isMacFilter ? VIR_TRISTATE_BOOL_YES :
                                             VIR_TRISTATE_BOOL_NO;

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 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 1087 1088 1089 1090
    ret = 0;
 cleanup:
    return ret;
}

static int
prlsdkAddDomainNetInfo(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    virDomainNetDefPtr net = NULL;
    PRL_RESULT ret;
    PRL_HANDLE netAdapter;
    PRL_UINT32 netAdaptersCount;
    PRL_UINT32 i;

    ret = PrlVmCfg_GetNetAdaptersCount(sdkdom, &netAdaptersCount);
    prlsdkCheckRetGoto(ret, error);
    for (i = 0; i < netAdaptersCount; ++i) {
        ret = PrlVmCfg_GetNetAdapter(sdkdom, i, &netAdapter);
        prlsdkCheckRetGoto(ret, error);

        if (VIR_ALLOC(net) < 0)
            goto error;

        if (prlsdkGetNetInfo(netAdapter, net, IS_CT(def)) < 0)
            goto error;

        PrlHandle_Free(netAdapter);
        netAdapter = PRL_INVALID_HANDLE;

        if (VIR_APPEND_ELEMENT(def->nets, def->nnets, net) < 0)
            goto error;
    }

    return 0;

 error:
    PrlHandle_Free(netAdapter);
    virDomainNetDefFree(net);
    return -1;
}

static int
prlsdkGetSerialInfo(PRL_HANDLE serialPort, virDomainChrDefPtr chr)
{
    PRL_RESULT pret;
    PRL_UINT32 serialPortIndex;
    PRL_UINT32 emulatedType;
    char *friendlyName = NULL;

    chr->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;
    chr->targetTypeAttr = false;
    pret = PrlVmDev_GetIndex(serialPort, &serialPortIndex);
    prlsdkCheckRetGoto(pret, error);
    chr->target.port = serialPortIndex;

    pret = PrlVmDev_GetEmulatedType(serialPort, &emulatedType);
    prlsdkCheckRetGoto(pret, error);

1091 1092
    if (!(friendlyName = prlsdkGetStringParamVar(PrlVmDev_GetFriendlyName,
                                                 serialPort)))
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
        goto error;

    switch (emulatedType) {
    case PDT_USE_OUTPUT_FILE:
        chr->source.type = VIR_DOMAIN_CHR_TYPE_FILE;
        chr->source.data.file.path = friendlyName;
        break;
    case PDT_USE_SERIAL_PORT_SOCKET_MODE:
        chr->source.type = VIR_DOMAIN_CHR_TYPE_UNIX;
        chr->source.data.nix.path = friendlyName;
        break;
    case PDT_USE_REAL_DEVICE:
        chr->source.type = VIR_DOMAIN_CHR_TYPE_DEV;
        chr->source.data.file.path = friendlyName;
        break;
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown serial type: %X"), emulatedType);
        goto error;
        break;
    }

    return 0;
 error:
    VIR_FREE(friendlyName);
    return -1;
}


static int
prlsdkAddSerialInfo(PRL_HANDLE sdkdom,
                    virDomainChrDefPtr **serials,
                    size_t *nserials)
{
    PRL_RESULT ret;
    PRL_HANDLE serialPort;
    PRL_UINT32 serialPortsCount;
    PRL_UINT32 i;
    virDomainChrDefPtr chr = NULL;

    ret = PrlVmCfg_GetSerialPortsCount(sdkdom, &serialPortsCount);
    prlsdkCheckRetGoto(ret, cleanup);
    for (i = 0; i < serialPortsCount; ++i) {
        ret = PrlVmCfg_GetSerialPort(sdkdom, i, &serialPort);
        prlsdkCheckRetGoto(ret, cleanup);

        if (!(chr = virDomainChrDefNew()))
            goto cleanup;

        if (prlsdkGetSerialInfo(serialPort, chr))
            goto cleanup;

        PrlHandle_Free(serialPort);
        serialPort = PRL_INVALID_HANDLE;

        if (VIR_APPEND_ELEMENT(*serials, *nserials, chr) < 0)
            goto cleanup;
    }

    return 0;

 cleanup:
    PrlHandle_Free(serialPort);
    virDomainChrDefFree(chr);
    return -1;
}


static int
1162
prlsdkAddDomainHardware(vzDriverPtr driver, PRL_HANDLE sdkdom, virDomainDefPtr def)
1163
{
1164 1165
    if (IS_CT(def)) {
        if (prlsdkAddDomainVideoInfoCt(def) < 0)
1166
            goto error;
1167 1168 1169 1170
    } else {
        if (prlsdkAddDomainVideoInfoVm(sdkdom, def) < 0)
            goto error;
    }
1171

1172
    if (prlsdkAddDomainHardDisksInfo(driver, sdkdom, def) < 0)
1173 1174
        goto error;

1175
    if (prlsdkAddDomainOpticalDisksInfo(driver, sdkdom, def) < 0)
D
Dmitry Guryanov 已提交
1176 1177
        goto error;

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    if (prlsdkAddDomainNetInfo(sdkdom, def) < 0)
        goto error;

    if (prlsdkAddSerialInfo(sdkdom,
                            &def->serials,
                            &def->nserials) < 0)
        goto error;

    return 0;
 error:
    return -1;
}


static int
prlsdkAddVNCInfo(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    virDomainGraphicsDefPtr gr = NULL;
    PRL_VM_REMOTE_DISPLAY_MODE vncMode;
    PRL_UINT32 port;
    PRL_RESULT pret;
N
Nikolay Shirokovskiy 已提交
1199
    char *passwd = NULL;
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209

    pret = PrlVmCfg_GetVNCMode(sdkdom, &vncMode);
    prlsdkCheckRetGoto(pret, error);

    if (vncMode == PRD_DISABLED)
        return 0;

    if (VIR_ALLOC(gr) < 0)
        goto error;

N
Nikolay Shirokovskiy 已提交
1210 1211 1212 1213 1214 1215 1216 1217
    if (!(passwd = prlsdkGetStringParamVar(PrlVmCfg_GetVNCPassword, sdkdom)))
        goto error;

    if (*passwd != '\0') {
        gr->data.vnc.auth.passwd = passwd;
        passwd = NULL;
    }

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    pret = PrlVmCfg_GetVNCPort(sdkdom, &port);
    prlsdkCheckRetGoto(pret, error);

    gr->data.vnc.autoport = (vncMode == PRD_AUTO);
    gr->type = VIR_DOMAIN_GRAPHICS_TYPE_VNC;
    gr->data.vnc.port = port;

    if (VIR_ALLOC(gr->listens) < 0)
        goto error;

    gr->nListens = 1;

1230 1231
    if (!(gr->listens[0].address = prlsdkGetStringParamVar(PrlVmCfg_GetVNCHostName,
                                                           sdkdom)))
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        goto error;

    gr->listens[0].type = VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS;

    if (VIR_APPEND_ELEMENT(def->graphics, def->ngraphics, gr) < 0)
        goto error;

    return 0;

 error:
    virDomainGraphicsDefFree(gr);
N
Nikolay Shirokovskiy 已提交
1243
    VIR_FREE(passwd);
1244 1245 1246
    return -1;
}

M
Maxim Nestratov 已提交
1247
static void
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
prlsdkConvertDomainState(VIRTUAL_MACHINE_STATE domainState,
                         PRL_UINT32 envId,
                         virDomainObjPtr dom)
{
    switch (domainState) {
    case VMS_STOPPED:
    case VMS_MOUNTED:
        virDomainObjSetState(dom, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_SHUTDOWN);
        dom->def->id = -1;
        break;
    case VMS_STARTING:
    case VMS_COMPACTING:
    case VMS_RESETTING:
    case VMS_PAUSING:
    case VMS_RECONNECTING:
    case VMS_RUNNING:
        virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_BOOTED);
        dom->def->id = envId;
        break;
    case VMS_PAUSED:
        virDomainObjSetState(dom, VIR_DOMAIN_PAUSED,
                             VIR_DOMAIN_PAUSED_USER);
        dom->def->id = envId;
        break;
    case VMS_SUSPENDED:
    case VMS_DELETING_STATE:
    case VMS_SUSPENDING_SYNC:
        virDomainObjSetState(dom, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_SAVED);
        dom->def->id = -1;
        break;
    case VMS_STOPPING:
        virDomainObjSetState(dom, VIR_DOMAIN_SHUTDOWN,
                             VIR_DOMAIN_SHUTDOWN_USER);
        dom->def->id = envId;
        break;
    case VMS_SNAPSHOTING:
        virDomainObjSetState(dom, VIR_DOMAIN_PAUSED,
                             VIR_DOMAIN_PAUSED_SNAPSHOT);
        dom->def->id = envId;
        break;
    case VMS_MIGRATING:
        virDomainObjSetState(dom, VIR_DOMAIN_PAUSED,
                             VIR_DOMAIN_PAUSED_MIGRATION);
        dom->def->id = envId;
        break;
    case VMS_SUSPENDING:
        virDomainObjSetState(dom, VIR_DOMAIN_PAUSED,
                             VIR_DOMAIN_PAUSED_SAVE);
        dom->def->id = envId;
        break;
    case VMS_RESTORING:
        virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_RESTORED);
        dom->def->id = envId;
        break;
    case VMS_CONTINUING:
        virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
        dom->def->id = envId;
        break;
    case VMS_RESUMING:
        virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_RESTORED);
        dom->def->id = envId;
        break;
    case VMS_UNKNOWN:
M
Maxim Nestratov 已提交
1317
    default:
1318 1319
        virDomainObjSetState(dom, VIR_DOMAIN_NOSTATE,
                             VIR_DOMAIN_NOSTATE_UNKNOWN);
M
Maxim Nestratov 已提交
1320
        dom->def->id = -1;
1321 1322 1323 1324 1325 1326
        break;
    }
}

static int
prlsdkConvertCpuInfo(PRL_HANDLE sdkdom,
1327 1328
                     virDomainDefPtr def,
                     virDomainXMLOptionPtr xmlopt)
1329 1330 1331 1332 1333 1334 1335
{
    char *buf;
    int hostcpus;
    PRL_UINT32 cpuCount;
    PRL_RESULT pret;
    int ret = -1;

1336
    if ((hostcpus = virHostCPUGetCount()) < 0)
1337 1338 1339 1340 1341 1342 1343 1344 1345
        goto cleanup;

    /* get number of CPUs */
    pret = PrlVmCfg_GetCpuCount(sdkdom, &cpuCount);
    prlsdkCheckRetGoto(pret, cleanup);

    if (cpuCount > hostcpus)
        cpuCount = hostcpus;

1346
    if (virDomainDefSetVcpusMax(def, cpuCount, xmlopt) < 0)
1347 1348
        goto cleanup;

1349 1350
    if (virDomainDefSetVcpus(def, cpuCount) < 0)
        goto cleanup;
1351

1352
    if (!(buf = prlsdkGetStringParamVar(PrlVmCfg_GetCpuMask, sdkdom)))
1353 1354 1355
        goto cleanup;

    if (strlen(buf) == 0) {
M
Maxim Nestratov 已提交
1356
        if (!(def->cpumask = virBitmapNew(hostcpus)))
1357
            goto cleanup;
M
Maxim Nestratov 已提交
1358
        virBitmapSetAll(def->cpumask);
1359
    } else {
1360
        if (virBitmapParse(buf, &def->cpumask, hostcpus) < 0)
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
            goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(buf);
    return ret;
}

static int
prlsdkConvertDomainType(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    PRL_VM_TYPE domainType;
    PRL_RESULT pret;

    pret = PrlVmCfg_GetVmType(sdkdom, &domainType);
    prlsdkCheckRetGoto(pret, error);

    switch (domainType) {
    case PVT_VM:
1381
        def->os.type = VIR_DOMAIN_OSTYPE_HVM;
1382 1383
        break;
    case PVT_CT:
1384
        def->os.type = VIR_DOMAIN_OSTYPE_EXE;
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
        if (VIR_STRDUP(def->os.init, "/sbin/init") < 0)
            return -1;
        break;
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown domain type: %X"), domainType);
        return -1;
    }

    return 0;

 error:
    return -1;
}

static int
prlsdkConvertCpuMode(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    PRL_RESULT pret;
    PRL_CPU_MODE cpuMode;

    pret = PrlVmCfg_GetCpuMode(sdkdom, &cpuMode);
    prlsdkCheckRetGoto(pret, error);

    switch (cpuMode) {
    case PCM_CPU_MODE_32:
        def->os.arch = VIR_ARCH_I686;
        break;
    case PCM_CPU_MODE_64:
        def->os.arch = VIR_ARCH_X86_64;
        break;
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown CPU mode: %X"), cpuMode);
        return -1;
    }

    return 0;
 error:
    return -1;
}

1427
virDomainObjPtr
1428
prlsdkNewDomainByHandle(vzDriverPtr driver, PRL_HANDLE sdkdom)
1429 1430
{
    virDomainObjPtr dom = NULL;
1431 1432 1433
    unsigned char uuid[VIR_UUID_BUFLEN];
    char *name = NULL;

1434
    virObjectLock(driver);
1435 1436 1437
    if (prlsdkGetDomainIds(sdkdom, &name, uuid) < 0)
        goto cleanup;

1438
    /* we should make sure that there is no such a VM exists */
1439
    if ((dom = virDomainObjListFindByUUID(driver->domains, uuid)))
1440 1441
        goto cleanup;

1442
    if (!(dom = vzNewDomain(driver, name, uuid)))
1443 1444
        goto cleanup;

1445 1446
    if (prlsdkLoadDomain(driver, dom) < 0) {
        virDomainObjListRemove(driver->domains, dom);
1447 1448 1449 1450 1451
        dom = NULL;
        goto cleanup;
    }

 cleanup:
1452
    virObjectUnlock(driver);
1453 1454 1455 1456
    VIR_FREE(name);
    return dom;
}

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 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
static PRL_HANDLE
prlsdkGetDevByDevIndex(PRL_HANDLE sdkdom, PRL_DEVICE_TYPE type, PRL_UINT32 devIndex)
{
    PRL_RESULT pret;
    PRL_UINT32 index, num;
    PRL_HANDLE dev = PRL_INVALID_HANDLE;
    size_t i;

    pret = PrlVmCfg_GetDevsCountByType(sdkdom, type, &num);
    prlsdkCheckRetGoto(pret, error);

    for (i = 0; i < num; ++i) {
        pret = PrlVmCfg_GetDevByType(sdkdom, type, i, &dev);
        prlsdkCheckRetGoto(pret, error);

        pret = PrlVmDev_GetIndex(dev, &index);
        prlsdkCheckRetGoto(pret, error);

        if (index == devIndex)
            break;

        PrlHandle_Free(dev);
        dev = PRL_INVALID_HANDLE;
    }

    return dev;

 error:
    PrlHandle_Free(dev);
    return PRL_INVALID_HANDLE;
}

static virDomainDiskDefPtr
virFindDiskBootIndex(virDomainDefPtr def, virDomainDiskDevice type, int index)
{
    size_t i;
    int c = 0;

    for (i = 0; i < def->ndisks; ++i) {
        if (def->disks[i]->device != type)
            continue;
        if (c == index)
            return def->disks[i];
        ++c;
    }

    return NULL;
}

static int
prlsdkBootOrderCheck(PRL_HANDLE sdkdom, PRL_DEVICE_TYPE sdkType, int sdkIndex,
                     virDomainDefPtr def, int bootIndex)
{
    char *sdkName = NULL;
    PRL_HANDLE dev = PRL_INVALID_HANDLE;
    virDomainDiskDefPtr disk;
    virDomainDiskDevice device;
1514 1515
    int bus;
    char *dst = NULL;
1516 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
    int ret = -1;

    dev = prlsdkGetDevByDevIndex(sdkdom, sdkType, sdkIndex);
    if (dev == PRL_INVALID_HANDLE) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Can't find boot device of type: %d, device index: %d"),
                       sdkType, sdkIndex);
        return -1;
    }

    switch (sdkType) {
    case PDE_OPTICAL_DISK:
    case PDE_HARD_DISK:
        switch (sdkType) {
        case PDE_OPTICAL_DISK:
            device = VIR_DOMAIN_DISK_DEVICE_CDROM;
            break;
        case PDE_HARD_DISK:
            device = VIR_DOMAIN_DISK_DEVICE_DISK;
            break;
        default:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unsupported disk type %d"), sdkType);
            goto cleanup;
        }

        if (!(disk = virFindDiskBootIndex(def, device, bootIndex))) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
Y
Yuri Chornoivan 已提交
1544
                           _("Can't find boot device of type: %s, index: %d"),
1545 1546 1547 1548
                           virDomainDiskDeviceTypeToString(device), bootIndex);
            goto cleanup;
        }

1549 1550 1551 1552 1553
        if (prlsdkGetDiskId(dev, false, &bus, &dst) < 0)
            goto cleanup;

        if (!(bus == disk->bus && STREQ(disk->dst, dst)))
            VIR_WARN("Unrepresentable boot order configuration");
1554 1555 1556

        break;
    case PDE_GENERIC_NETWORK_ADAPTER:
1557 1558
        if (!(sdkName = prlsdkGetStringParamVar(PrlVmDevNet_GetHostInterfaceName,
                                                dev)))
1559 1560 1561 1562
            goto cleanup;

        if (bootIndex >= def->nnets) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
Y
Yuri Chornoivan 已提交
1563
                           _("Can't find network boot device for index: %d"),
1564 1565 1566 1567
                           bootIndex);
            goto cleanup;
        }

1568 1569
        if (STRNEQ(sdkName, def->nets[bootIndex]->ifname))
            VIR_WARN("Unrepresentable boot order configuration");
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583

        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Unexpected device type %d"), sdkType);
        goto cleanup;
    }

    ret = 0;

 cleanup:

    VIR_FREE(sdkName);
    PrlHandle_Free(dev);
1584
    VIR_FREE(dst);
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
    return ret;
}

static int
prlsdkConvertBootOrder(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    int ret = -1;
    PRL_RESULT pret;
    PRL_UINT32 bootNum;
    PRL_HANDLE bootDev = PRL_INVALID_HANDLE;
    PRL_BOOL inUse;
    PRL_DEVICE_TYPE sdkType;
    virDomainBootOrder type;
    PRL_UINT32 prevBootIndex = 0, bootIndex, sdkIndex;
    int bootUsage[VIR_DOMAIN_BOOT_LAST] = { 0 };
    size_t i;

    pret = PrlVmCfg_GetBootDevCount(sdkdom, &bootNum);
    prlsdkCheckRetExit(pret, -1);

    def->os.nBootDevs = 0;

    if (bootNum > VIR_DOMAIN_MAX_BOOT_DEVS) {
        bootNum = VIR_DOMAIN_MAX_BOOT_DEVS;
        VIR_WARN("Too many boot devices");
    }

    for (i = 0; i < bootNum; ++i) {
        pret = PrlVmCfg_GetBootDev(sdkdom, i, &bootDev);
        prlsdkCheckRetGoto(pret, cleanup);

        pret = PrlBootDev_IsInUse(bootDev, &inUse);
        prlsdkCheckRetGoto(pret, cleanup);

        if (!inUse) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Boot ordering with disabled items is not supported"));
            goto cleanup;
        }

        pret = PrlBootDev_GetSequenceIndex(bootDev, &bootIndex);
        prlsdkCheckRetGoto(pret, cleanup);

        /* bootIndex is started from 1 */
        if (bootIndex <= prevBootIndex) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Unsupported boot order configuration"));
            goto cleanup;
        }
        prevBootIndex = bootIndex;

        pret = PrlBootDev_GetType(bootDev, &sdkType);
        prlsdkCheckRetGoto(pret, cleanup);

        if (sdkType == PDE_FLOPPY_DISK) {
            VIR_WARN("Skipping floppy from boot order.");
            continue;
        }

        switch (sdkType) {
        case PDE_OPTICAL_DISK:
            type = VIR_DOMAIN_BOOT_CDROM;
            break;
        case PDE_HARD_DISK:
            type = VIR_DOMAIN_BOOT_DISK;
            break;
        case PDE_GENERIC_NETWORK_ADAPTER:
            type = VIR_DOMAIN_BOOT_NET;
            break;
        default:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unexpected boot device type %i"), sdkType);
            goto cleanup;
        }

        pret = PrlBootDev_GetIndex(bootDev, &sdkIndex);
        prlsdkCheckRetGoto(pret, cleanup);

        if (prlsdkBootOrderCheck(sdkdom, sdkType, sdkIndex, def, bootUsage[type]) < 0)
            goto cleanup;

        bootUsage[type]++;
        def->os.bootDevs[def->os.nBootDevs++] = type;

        PrlHandle_Free(bootDev);
        bootDev = PRL_INVALID_HANDLE;
    }

    ret = 0;

 cleanup:
    PrlHandle_Free(bootDev);
    return ret;
}

1680
int
1681
prlsdkLoadDomain(vzDriverPtr driver, virDomainObjPtr dom)
1682
{
1683
    virDomainDefPtr def = NULL;
1684
    vzDomObjPtr pdom = NULL;
1685 1686 1687 1688 1689 1690
    VIRTUAL_MACHINE_STATE domainState;

    PRL_RESULT pret;
    PRL_UINT32 ram;
    PRL_UINT32 envId;
    PRL_VM_AUTOSTART_OPTION autostart;
1691
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;
1692
    PRL_HANDLE job;
1693

1694 1695 1696
    virCheckNonNullArgGoto(dom, error);

    pdom = dom->privateData;
1697
    sdkdom = prlsdkSdkDomainLookupByUUID(driver, dom->def->uuid);
1698 1699
    if (sdkdom == PRL_INVALID_HANDLE)
        return -1;
1700

1701
    if (!(def = virDomainDefNew()))
1702 1703
        goto error;

1704 1705
    def->virtType = dom->def->virtType;
    def->id = dom->def->id;
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716

    if (prlsdkGetDomainIds(sdkdom, &def->name, def->uuid) < 0)
        goto error;

    def->onReboot = VIR_DOMAIN_LIFECYCLE_RESTART;
    def->onPoweroff = VIR_DOMAIN_LIFECYCLE_DESTROY;
    def->onCrash = VIR_DOMAIN_LIFECYCLE_CRASH_DESTROY;

    /* get RAM parameters */
    pret = PrlVmCfg_GetRamSize(sdkdom, &ram);
    prlsdkCheckRetGoto(pret, error);
1717
    virDomainDefSetMemoryTotal(def, ram << 10); /* RAM size obtained in Mbytes,
1718 1719
                                                     convert to Kbytes */
    def->mem.cur_balloon = ram << 10;
1720

1721
    if (prlsdkConvertCpuInfo(sdkdom, def, driver->xmlopt) < 0)
1722 1723 1724 1725 1726 1727 1728 1729
        goto error;

    if (prlsdkConvertCpuMode(sdkdom, def) < 0)
        goto error;

    if (prlsdkConvertDomainType(sdkdom, def) < 0)
        goto error;

1730 1731 1732 1733
    if (prlsdkAddVNCInfo(sdkdom, def) < 0)
        goto error;

    /* depends on prlsdkAddVNCInfo */
1734
    if (prlsdkAddDomainHardware(driver, sdkdom, def) < 0)
1735 1736
        goto error;

1737 1738 1739 1740
    /* depends on prlsdkAddDomainHardware */
    if (prlsdkConvertBootOrder(sdkdom, def) < 0)
        goto error;

1741 1742 1743
    pret = PrlVmCfg_GetEnvId(sdkdom, &envId);
    prlsdkCheckRetGoto(pret, error);

1744 1745
    pret = PrlVmCfg_GetAutoStart(sdkdom, &autostart);
    prlsdkCheckRetGoto(pret, error);
1746 1747 1748 1749 1750 1751
    if (autostart != PAO_VM_START_ON_LOAD &&
        autostart != PAO_VM_START_MANUAL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown autostart mode: %X"), autostart);
        goto error;
    }
1752 1753 1754 1755

    if (prlsdkGetDomainState(sdkdom, &domainState) < 0)
        goto error;

1756
    if (virDomainDefAddImplicitDevices(def) < 0)
1757 1758
        goto error;

1759
    if (def->ngraphics > 0) {
M
Michal Privoznik 已提交
1760 1761
        int bus = IS_CT(def) ? VIR_DOMAIN_INPUT_BUS_PARALLELS :
                               VIR_DOMAIN_INPUT_BUS_PS2;
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773

        if (virDomainDefMaybeAddInput(def,
                                      VIR_DOMAIN_INPUT_TYPE_MOUSE,
                                      bus) < 0)
            goto error;

        if (virDomainDefMaybeAddInput(def,
                                      VIR_DOMAIN_INPUT_TYPE_KBD,
                                      bus) < 0)
            goto error;
    }

1774 1775 1776 1777 1778 1779 1780 1781 1782
    if (!pdom->sdkdom) {
        job = PrlVm_SubscribeToPerfStats(sdkdom, NULL);
        if (PRL_FAILED(waitJob(job)))
            goto error;

        PrlHandle_AddRef(sdkdom);
        pdom->sdkdom = sdkdom;
    }

1783 1784 1785 1786 1787 1788 1789
    /* assign new virDomainDef without any checks
     * we can't use virDomainObjAssignDef, because it checks
     * for state and domain name */
    virDomainDefFree(dom->def);
    dom->def = def;
    pdom->id = envId;

M
Maxim Nestratov 已提交
1790 1791
    prlsdkConvertDomainState(domainState, envId, dom);

1792 1793 1794 1795
    if (autostart == PAO_VM_START_ON_LOAD)
        dom->autostart = 1;
    else
        dom->autostart = 0;
1796

1797 1798 1799 1800 1801 1802
    PrlHandle_Free(sdkdom);
    return 0;
 error:
    PrlHandle_Free(sdkdom);
    virDomainDefFree(def);
    return -1;
1803 1804 1805
}

int
1806
prlsdkLoadDomains(vzDriverPtr driver)
1807 1808 1809
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;
    PRL_HANDLE result;
1810
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;
1811 1812 1813 1814 1815
    PRL_UINT32 paramsCount;
    PRL_RESULT pret;
    size_t i = 0;
    virDomainObjPtr dom;

1816
    job = PrlSrv_GetVmListEx(driver->server, PVTF_VM | PVTF_CT);
1817

1818
    if (PRL_FAILED(getJobResult(job, &result)))
1819 1820 1821 1822 1823 1824 1825
        return -1;

    pret = PrlResult_GetParamsCount(result, &paramsCount);
    prlsdkCheckRetGoto(pret, error);

    for (i = 0; i < paramsCount; i++) {
        pret = PrlResult_GetParamByIndex(result, i, &sdkdom);
1826 1827
        prlsdkCheckRetGoto(pret, error);

1828 1829
        if ((dom = prlsdkNewDomainByHandle(driver, sdkdom)))
            virObjectUnlock(dom);
1830 1831

        PrlHandle_Free(sdkdom);
1832
        sdkdom = PRL_INVALID_HANDLE;
1833 1834 1835 1836 1837 1838
    }

    PrlHandle_Free(result);
    return 0;

 error:
1839
    PrlHandle_Free(sdkdom);
1840 1841 1842 1843
    PrlHandle_Free(result);
    return -1;
}

1844
int
1845
prlsdkUpdateDomain(vzDriverPtr driver, virDomainObjPtr dom)
1846 1847
{
    PRL_HANDLE job;
1848
    vzDomObjPtr pdom = dom->privateData;
1849 1850

    job = PrlVm_RefreshConfig(pdom->sdkdom);
1851
    if (waitJob(job))
1852 1853
        return -1;

1854
    return prlsdkLoadDomain(driver, dom);
1855 1856
}

1857
static int prlsdkSendEvent(vzDriverPtr driver,
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
                           virDomainObjPtr dom,
                           virDomainEventType lvEventType,
                           int lvEventTypeDetails)
{
    virObjectEventPtr event = NULL;

    event = virDomainEventLifecycleNewFromObj(dom,
                                              lvEventType,
                                              lvEventTypeDetails);
    if (!event)
        return -1;

1870
    virObjectEventStateQueue(driver->domainEventState, event);
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    return 0;
}

static void
prlsdkNewStateToEvent(VIRTUAL_MACHINE_STATE domainState,
                      virDomainEventType *lvEventType,
                      int *lvEventTypeDetails)
{
    /* We skip all intermediate states here, because
     * libvirt doesn't have correspoding event types for
     * them */
    switch (domainState) {
    case VMS_STOPPED:
    case VMS_MOUNTED:
        *lvEventType = VIR_DOMAIN_EVENT_STOPPED;
        *lvEventTypeDetails = VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN;
        break;
    case VMS_RUNNING:
        *lvEventType = VIR_DOMAIN_EVENT_STARTED;
        *lvEventTypeDetails = VIR_DOMAIN_EVENT_STARTED_BOOTED;
        break;
    case VMS_PAUSED:
        *lvEventType = VIR_DOMAIN_EVENT_SUSPENDED;
        *lvEventTypeDetails = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
        break;
    case VMS_SUSPENDED:
        *lvEventType = VIR_DOMAIN_EVENT_STOPPED;
        *lvEventTypeDetails = VIR_DOMAIN_EVENT_STOPPED_SAVED;
        break;
    default:
        VIR_DEBUG("Skip sending event about changing state to %X",
                  domainState);
        break;
    }
}

1907
static void
1908
prlsdkHandleVmStateEvent(vzDriverPtr driver,
1909 1910 1911 1912 1913 1914 1915
                         PRL_HANDLE prlEvent,
                         unsigned char *uuid)
{
    PRL_RESULT pret = PRL_ERR_FAILURE;
    PRL_HANDLE eventParam = PRL_INVALID_HANDLE;
    PRL_INT32 domainState;
    virDomainObjPtr dom = NULL;
1916
    vzDomObjPtr pdom;
1917 1918 1919
    virDomainEventType lvEventType = 0;
    int lvEventTypeDetails = 0;

1920
    dom = virDomainObjListFindByUUID(driver->domains, uuid);
1921 1922 1923
    if (dom == NULL)
        return;

1924 1925 1926 1927 1928 1929 1930
    pret = PrlEvent_GetParamByName(prlEvent, "vminfo_vm_state", &eventParam);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlEvtPrm_ToInt32(eventParam, &domainState);
    prlsdkCheckRetGoto(pret, cleanup);

    pdom = dom->privateData;
M
Maxim Nestratov 已提交
1931 1932

    prlsdkConvertDomainState(domainState, pdom->id, dom);
1933 1934 1935 1936 1937

    prlsdkNewStateToEvent(domainState,
                          &lvEventType,
                          &lvEventTypeDetails);

1938
    prlsdkSendEvent(driver, dom, lvEventType, lvEventTypeDetails);
1939 1940

 cleanup:
1941 1942
    virObjectUnlock(dom);
    return;
1943 1944
}

1945
static void
1946
prlsdkHandleVmConfigEvent(vzDriverPtr driver,
1947 1948 1949 1950
                          unsigned char *uuid)
{
    virDomainObjPtr dom = NULL;

1951
    dom = virDomainObjListFindByUUID(driver->domains, uuid);
1952 1953
    if (dom == NULL)
        return;
1954

1955
    if (prlsdkUpdateDomain(driver, dom) < 0)
1956 1957
        goto cleanup;

1958
    prlsdkSendEvent(driver, dom, VIR_DOMAIN_EVENT_DEFINED,
M
Michal Privoznik 已提交
1959
                    VIR_DOMAIN_EVENT_DEFINED_UPDATED);
1960 1961

 cleanup:
1962 1963
    virObjectUnlock(dom);
    return;
1964 1965
}

1966
static void
1967
prlsdkHandleVmAddedEvent(vzDriverPtr driver,
M
Michal Privoznik 已提交
1968
                         unsigned char *uuid)
1969 1970
{
    virDomainObjPtr dom = NULL;
1971
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;
1972

1973
    dom = virDomainObjListFindByUUID(driver->domains, uuid);
1974
    if (!dom) {
1975
        sdkdom = prlsdkSdkDomainLookupByUUID(driver, uuid);
1976 1977 1978
        if (sdkdom == PRL_INVALID_HANDLE)
            goto cleanup;

1979
        if (!(dom = prlsdkNewDomainByHandle(driver, sdkdom)))
1980 1981
            goto cleanup;
    }
1982

1983
    prlsdkSendEvent(driver, dom, VIR_DOMAIN_EVENT_DEFINED,
M
Michal Privoznik 已提交
1984
                    VIR_DOMAIN_EVENT_DEFINED_ADDED);
1985

1986 1987 1988 1989
 cleanup:
    if (dom)
        virObjectUnlock(dom);
    PrlHandle_Free(sdkdom);
1990
    return;
1991 1992
}

1993
static void
1994
prlsdkHandleVmRemovedEvent(vzDriverPtr driver,
1995 1996 1997 1998
                           unsigned char *uuid)
{
    virDomainObjPtr dom = NULL;

1999
    dom = virDomainObjListFindByUUID(driver->domains, uuid);
2000 2001 2002 2003
    /* domain was removed from the list from the libvirt
     * API function in current connection */
    if (dom == NULL)
        return;
2004

2005
    prlsdkSendEvent(driver, dom, VIR_DOMAIN_EVENT_UNDEFINED,
M
Michal Privoznik 已提交
2006
                    VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
2007

2008
    virDomainObjListRemove(driver->domains, dom);
2009
    return;
2010 2011
}

2012 2013
#define PARALLELS_STATISTICS_DROP_COUNT 3

2014
static void
2015
prlsdkHandlePerfEvent(vzDriverPtr driver,
M
Michal Privoznik 已提交
2016 2017
                      PRL_HANDLE event,
                      unsigned char *uuid)
2018 2019
{
    virDomainObjPtr dom = NULL;
2020
    vzDomObjPtr privdom = NULL;
2021

2022 2023
    if (!(dom = virDomainObjListFindByUUID(driver->domains, uuid)))
        return;
2024

2025 2026 2027
    privdom = dom->privateData;
    PrlHandle_Free(privdom->stats);
    privdom->stats = event;
2028

2029
    virObjectUnlock(dom);
2030 2031
}

2032 2033
static PRL_RESULT
prlsdkEventsHandler(PRL_HANDLE prlEvent, PRL_VOID_PTR opaque)
2034
{
2035
    vzDriverPtr driver = opaque;
2036
    PRL_RESULT pret = PRL_ERR_FAILURE;
2037
    PRL_HANDLE_TYPE handleType;
2038
    char uuidstr[VIR_UUID_STRING_BRACED_BUFLEN];
2039 2040 2041
    unsigned char uuid[VIR_UUID_BUFLEN];
    PRL_EVENT_TYPE prlEventType;

2042
    pret = PrlHandle_GetType(prlEvent, &handleType);
2043
    prlsdkCheckRetGoto(pret, cleanup);
2044

2045 2046 2047 2048
    /* Currently, there is no need to handle anything but events */
    if (handleType != PHT_EVENT)
        goto cleanup;

2049
    if (driver == NULL)
2050 2051
        goto cleanup;

2052 2053
    pret = prlsdkGetStringParamBuf(PrlEvent_GetIssuerId,
                                   prlEvent, uuidstr, sizeof(uuidstr));
2054
    prlsdkCheckRetGoto(pret, cleanup);
2055

2056 2057 2058
    pret = PrlEvent_GetType(prlEvent, &prlEventType);
    prlsdkCheckRetGoto(pret, cleanup);

2059 2060
    if (prlsdkUUIDParse(uuidstr, uuid) < 0) {
        VIR_DEBUG("Skipping event type %d", prlEventType);
2061
        goto cleanup;
2062
    }
2063 2064

    switch (prlEventType) {
M
Michal Privoznik 已提交
2065
    case PET_DSP_EVT_VM_STATE_CHANGED:
2066
        prlsdkHandleVmStateEvent(driver, prlEvent, uuid);
M
Michal Privoznik 已提交
2067 2068
        break;
    case PET_DSP_EVT_VM_CONFIG_CHANGED:
2069
        prlsdkHandleVmConfigEvent(driver, uuid);
M
Michal Privoznik 已提交
2070 2071 2072
        break;
    case PET_DSP_EVT_VM_CREATED:
    case PET_DSP_EVT_VM_ADDED:
2073
        prlsdkHandleVmAddedEvent(driver, uuid);
M
Michal Privoznik 已提交
2074 2075 2076
        break;
    case PET_DSP_EVT_VM_DELETED:
    case PET_DSP_EVT_VM_UNREGISTERED:
2077
        prlsdkHandleVmRemovedEvent(driver, uuid);
M
Michal Privoznik 已提交
2078 2079
        break;
    case PET_DSP_EVT_VM_PERFSTATS:
2080
        prlsdkHandlePerfEvent(driver, prlEvent, uuid);
M
Michal Privoznik 已提交
2081 2082 2083
        /* above function takes own of event */
        prlEvent = PRL_INVALID_HANDLE;
        break;
2084
    case PET_DSP_EVT_DISP_CONNECTION_CLOSED:
2085
        vzDestroyDriverConnection();
2086
        break;
M
Michal Privoznik 已提交
2087
    default:
2088
        VIR_DEBUG("Skipping event of type %d", prlEventType);
2089 2090 2091 2092
    }

 cleanup:
    PrlHandle_Free(prlEvent);
2093
    return PRL_ERR_SUCCESS;
2094 2095
}

2096
int prlsdkSubscribeToPCSEvents(vzDriverPtr driver)
2097 2098 2099
{
    PRL_RESULT pret = PRL_ERR_UNINITIALIZED;

2100
    pret = PrlSrv_RegEventHandler(driver->server,
M
Michal Privoznik 已提交
2101
                                  prlsdkEventsHandler,
2102
                                  driver);
2103 2104 2105 2106 2107 2108 2109
    prlsdkCheckRetGoto(pret, error);
    return 0;

 error:
    return -1;
}

2110
void prlsdkUnsubscribeFromPCSEvents(vzDriverPtr driver)
2111 2112
{
    PRL_RESULT ret = PRL_ERR_UNINITIALIZED;
2113
    ret = PrlSrv_UnregEventHandler(driver->server,
M
Michal Privoznik 已提交
2114
                                   prlsdkEventsHandler,
2115
                                   driver);
2116 2117 2118
    if (PRL_FAILED(ret))
        logPrlError(ret);
}
2119

2120
PRL_RESULT prlsdkStart(PRL_HANDLE sdkdom)
2121 2122 2123 2124
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_StartEx(sdkdom, PSM_VM_START, 0);
2125
    return waitJob(job);
2126 2127
}

2128
static PRL_RESULT prlsdkStopEx(PRL_HANDLE sdkdom, PRL_UINT32 mode)
2129 2130 2131 2132
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_StopEx(sdkdom, mode, 0);
2133
    return waitJob(job);
2134 2135
}

2136
PRL_RESULT prlsdkKill(PRL_HANDLE sdkdom)
2137
{
2138
    return prlsdkStopEx(sdkdom, PSM_KILL);
2139 2140
}

2141
PRL_RESULT prlsdkStop(PRL_HANDLE sdkdom)
2142
{
2143
    return prlsdkStopEx(sdkdom, PSM_SHUTDOWN);
2144 2145
}

2146
PRL_RESULT prlsdkPause(PRL_HANDLE sdkdom)
2147 2148 2149 2150
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_Pause(sdkdom, false);
2151
    return waitJob(job);
2152 2153
}

2154
PRL_RESULT prlsdkResume(PRL_HANDLE sdkdom)
2155 2156 2157 2158
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_Resume(sdkdom);
2159
    return waitJob(job);
2160 2161
}

2162
PRL_RESULT prlsdkSuspend(PRL_HANDLE sdkdom)
2163 2164 2165 2166
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_Suspend(sdkdom);
2167
    return waitJob(job);
2168 2169
}

2170 2171 2172 2173 2174 2175 2176 2177
PRL_RESULT prlsdkRestart(PRL_HANDLE sdkdom)
{
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_Restart(sdkdom);
    return waitJob(job);
}

2178
int
2179
prlsdkDomainChangeStateLocked(vzDriverPtr driver,
2180 2181
                              virDomainObjPtr dom,
                              prlsdkChangeStateFunc chstate)
2182
{
2183
    vzDomObjPtr pdom;
2184 2185
    PRL_RESULT pret;
    virErrorNumber virerr;
2186 2187

    pdom = dom->privateData;
2188
    pret = chstate(pdom->sdkdom);
2189 2190 2191 2192 2193 2194
    if (PRL_FAILED(pret)) {
        virResetLastError();

        switch (pret) {
        case PRL_ERR_DISP_VM_IS_NOT_STARTED:
        case PRL_ERR_DISP_VM_IS_NOT_STOPPED:
2195
        case PRL_ERR_INVALID_ACTION_REQUESTED:
2196
        case PRL_ERR_UNIMPLEMENTED:
2197 2198 2199 2200 2201 2202 2203
            virerr = VIR_ERR_OPERATION_INVALID;
            break;
        default:
            virerr = VIR_ERR_OPERATION_FAILED;
        }

        virReportError(virerr, "%s", _("Can't change domain state."));
2204
        return -1;
2205
    }
2206

2207
    return prlsdkUpdateDomain(driver, dom);
2208
}
2209

2210 2211 2212 2213
int
prlsdkDomainChangeState(virDomainPtr domain,
                        prlsdkChangeStateFunc chstate)
{
2214
    vzConnPtr privconn = domain->conn->privateData;
2215 2216 2217
    virDomainObjPtr dom;
    int ret = -1;

2218
    if (!(dom = vzDomObjFromDomain(domain)))
2219 2220
        return -1;

2221
    ret = prlsdkDomainChangeStateLocked(privconn->driver, dom, chstate);
2222 2223 2224
    virObjectUnlock(dom);
    return ret;
}
2225 2226 2227 2228 2229 2230 2231

static int
prlsdkCheckUnsupportedParams(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    size_t i;
    PRL_VM_TYPE vmType;
    PRL_RESULT pret;
2232
    virDomainNumatuneMemMode memMode;
2233 2234
    int bus = IS_CT(def) ? VIR_DOMAIN_INPUT_BUS_PARALLELS :
                           VIR_DOMAIN_INPUT_BUS_PS2;
2235 2236 2237

    if (def->title) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2238
                       _("titles are not supported by vz driver"));
2239 2240 2241 2242 2243 2244
        return -1;
    }

    if (def->blkio.ndevices > 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("blkio parameters are not supported "
2245
                         "by vz driver"));
2246 2247 2248
        return -1;
    }

2249
    if (virDomainDefGetMemoryTotal(def) != def->mem.cur_balloon) {
2250
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
M
Michal Privoznik 已提交
2251 2252 2253
                       _("changing balloon parameters is not supported "
                         "by vz driver"));
        return -1;
2254 2255
    }

2256
    if (virDomainDefGetMemoryTotal(def) % (1 << 10) != 0) {
2257
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
M
Michal Privoznik 已提交
2258
                       _("Memory size should be multiple of 1Mb."));
2259 2260 2261 2262
        return -1;
    }

    if (def->mem.nhugepages ||
2263 2264
        virMemoryLimitIsSet(def->mem.hard_limit) ||
        virMemoryLimitIsSet(def->mem.soft_limit) ||
2265
        def->mem.min_guarantee ||
2266
        virMemoryLimitIsSet(def->mem.swap_hard_limit)) {
2267 2268 2269

        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Memory parameter is not supported "
2270
                         "by vz driver"));
2271 2272 2273
        return -1;
    }

2274
    if (virDomainDefHasVcpusOffline(def)) {
2275
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
M
Michal Privoznik 已提交
2276
                       _("current vcpus must be equal to maxvcpus"));
2277 2278 2279 2280 2281 2282
        return -1;
    }

    if (def->placement_mode) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("changing cpu placement mode is not supported "
2283
                         "by vz driver"));
2284 2285 2286 2287 2288 2289
        return -1;
    }

    if (def->cputune.shares ||
        def->cputune.sharesSpecified ||
        def->cputune.period ||
2290
        def->cputune.quota) {
2291 2292

        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2293
                       _("cputune is not supported by vz driver"));
2294 2295 2296
        return -1;
    }

2297
    for (i = 0; i < virDomainDefGetVcpusMax(def); i++) {
2298
        virDomainVcpuDefPtr vcpu = virDomainDefGetVcpu(def, i);
2299 2300 2301 2302 2303 2304

        if (vcpu->cpumask &&
            !virBitmapEqual(def->cpumask, vcpu->cpumask)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("vcpupin cpumask differs from default cpumask"));
            return -1;
2305 2306 2307
        }
    }

2308 2309 2310 2311 2312 2313

    /*
     * Though we don't support NUMA configuration at the moment
     * virDomainDefPtr always contain non zero NUMA configuration
     * So, just make sure this configuration does't differ from auto generated.
     */
2314 2315
    if ((virDomainNumatuneGetMode(def->numa, -1, &memMode) == 0 &&
         memMode == VIR_DOMAIN_NUMATUNE_MEM_STRICT) ||
M
Michal Privoznik 已提交
2316
        virDomainNumatuneHasPerNodeBinding(def->numa)) {
2317
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
M
Michal Privoznik 已提交
2318 2319
                       _("numa parameters are not supported "
                         "by vz driver"));
2320 2321 2322 2323 2324 2325 2326 2327 2328
        return -1;
    }

    if (def->onReboot != VIR_DOMAIN_LIFECYCLE_RESTART ||
        def->onPoweroff != VIR_DOMAIN_LIFECYCLE_DESTROY ||
        def->onCrash != VIR_DOMAIN_LIFECYCLE_CRASH_DESTROY) {

        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("on_reboot, on_poweroff and on_crash parameters "
2329
                         "are not supported by vz driver"));
2330 2331 2332
        return -1;
    }

2333
    /* we fill only type and arch fields in vzLoadDomain for
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
     * hvm type and also init for containers, so we can check that all
     * other paramenters are null and boot devices config is default */

    if (def->os.machine != NULL || def->os.bootmenu != 0 ||
        def->os.kernel != NULL || def->os.initrd != NULL ||
        def->os.cmdline != NULL || def->os.root != NULL ||
        def->os.loader != NULL || def->os.bootloader != NULL ||
        def->os.bootloaderArgs != NULL || def->os.smbios_mode != 0 ||
        def->os.bios.useserial != 0) {

        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("changing OS parameters is not supported "
2346
                         "by vz driver"));
2347 2348 2349 2350 2351 2352 2353 2354 2355
        return -1;
    }

    pret = PrlVmCfg_GetVmType(sdkdom, &vmType);
    if (PRL_FAILED(pret)) {
        logPrlError(pret);
        return -1;
    }

2356 2357
    if (!(vmType == PVT_VM && !IS_CT(def)) &&
        !(vmType == PVT_CT && IS_CT(def))) {
2358 2359 2360

        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("changing OS type is not supported "
2361
                         "by vz driver"));
2362 2363 2364
        return -1;
    }

2365
    if (!IS_CT(def)) {
2366
        if (def->os.init != NULL || def->os.initargv != NULL) {
2367
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2368
                           _("unsupported OS parameters"));
2369 2370 2371 2372
            return -1;
        }
    } else {
        if (def->os.nBootDevs != 0 ||
2373
            STRNEQ_NULLABLE(def->os.init, "/sbin/init") ||
2374 2375 2376
            (def->os.initargv != NULL && def->os.initargv[0] != NULL)) {

            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2377
                           _("unsupported OS parameters"));
2378 2379 2380 2381 2382 2383 2384
            return -1;
        }
    }

    if (def->emulator) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("changing emulator is not supported "
2385
                         "by vz driver"));
2386 2387 2388 2389 2390 2391 2392
        return -1;
    }

    for (i = 0; i < VIR_DOMAIN_FEATURE_LAST; i++) {
        if (def->features[i]) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("changing features is not supported "
2393
                             "by vz driver"));
2394 2395 2396 2397 2398 2399 2400 2401 2402
            return -1;
        }
    }

    if (def->clock.offset != VIR_DOMAIN_CLOCK_OFFSET_UTC ||
        def->clock.ntimers != 0) {

        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("changing clock parameters is not supported "
2403
                         "by vz driver"));
2404 2405 2406
        return -1;
    }

2407 2408 2409
    if (!IS_CT(def) && def->nfss != 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Filesystems in VMs are not supported "
2410
                         "by vz driver"));
2411 2412 2413 2414
        return -1;
    }

    if (def->nsounds != 0 || def->nhostdevs != 0 ||
2415 2416 2417 2418 2419 2420
        def->nredirdevs != 0 || def->nsmartcards != 0 ||
        def->nparallels || def->nchannels != 0 ||
        def->nleases != 0 || def->nhubs != 0) {

        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("changing devices parameters is not supported "
2421
                         "by vz driver"));
2422 2423 2424
        return -1;
    }

2425 2426 2427 2428 2429 2430 2431 2432
    /* check we have only default input devices */
    if (def->ngraphics > 0) {
        if (def->ninputs != 2 ||
            def->inputs[0]->bus != bus ||
            def->inputs[1]->bus != bus ||
            !((def->inputs[0]->type == VIR_DOMAIN_INPUT_TYPE_MOUSE &&
               def->inputs[1]->type == VIR_DOMAIN_INPUT_TYPE_KBD) ||
              (def->inputs[0]->type == VIR_DOMAIN_INPUT_TYPE_KBD &&
2433
               def->inputs[1]->type == VIR_DOMAIN_INPUT_TYPE_MOUSE))) {
2434

2435 2436 2437 2438 2439
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("unsupported input device configuration"));
            return -1;
        }
    } else if (def->ninputs != 0) {
2440
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2441
                       _("input devices without vnc are not supported"));
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
        return -1;
    }

    return 0;
}

static int prlsdkClearDevices(PRL_HANDLE sdkdom)
{
    PRL_RESULT pret;
    PRL_UINT32 n, i;
    PRL_HANDLE devList;
    PRL_HANDLE dev;
    int ret = -1;

    pret = PrlVmCfg_GetAllDevices(sdkdom, &devList);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlHndlList_GetItemsCount(devList, &n);
    prlsdkCheckRetGoto(pret, cleanup);

    for (i = 0; i < n; i++) {
        pret = PrlHndlList_GetItem(devList, i, &dev);
        prlsdkCheckRetGoto(pret, cleanup);

        pret = PrlVmDev_Remove(dev);
        PrlHandle_Free(dev);
    }

    ret = 0;
 cleanup:
    PrlHandle_Free(devList);
    return ret;
}

2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
static int
prlsdkRemoveBootDevices(PRL_HANDLE sdkdom)
{
    PRL_RESULT pret;
    PRL_UINT32 i, devCount;
    PRL_HANDLE dev = PRL_INVALID_HANDLE;
    PRL_DEVICE_TYPE devType;

    pret = PrlVmCfg_GetBootDevCount(sdkdom, &devCount);
    prlsdkCheckRetGoto(pret, error);

    for (i = 0; i < devCount; i++) {

        /* always get device by index 0, because device list resort after delete */
        pret = PrlVmCfg_GetBootDev(sdkdom, 0, &dev);
        prlsdkCheckRetGoto(pret, error);

        pret = PrlBootDev_GetType(dev, &devType);
        prlsdkCheckRetGoto(pret, error);

        pret = PrlBootDev_Remove(dev);
        prlsdkCheckRetGoto(pret, error);
    }

    return 0;

 error:
    return -1;
}

static int
prlsdkAddDeviceToBootList(PRL_HANDLE sdkdom,
                          PRL_UINT32 devIndex,
                          PRL_DEVICE_TYPE devType,
                          PRL_UINT32 bootSequence)
{
    PRL_RESULT pret;
    PRL_HANDLE bootDev = PRL_INVALID_HANDLE;

    pret = PrlVmCfg_CreateBootDev(sdkdom, &bootDev);
    prlsdkCheckRetGoto(pret, error);

    pret = PrlBootDev_SetIndex(bootDev, devIndex);
    prlsdkCheckRetGoto(pret, error);

    pret = PrlBootDev_SetType(bootDev, devType);
    prlsdkCheckRetGoto(pret, error);

    pret = PrlBootDev_SetSequenceIndex(bootDev, bootSequence);
    prlsdkCheckRetGoto(pret, error);

    pret = PrlBootDev_SetInUse(bootDev, PRL_TRUE);
    prlsdkCheckRetGoto(pret, error);

    return 0;

 error:
    if (bootDev != PRL_INVALID_HANDLE)
        PrlBootDev_Remove(bootDev);

    return -1;
}

2539 2540 2541 2542
static int prlsdkCheckVideoUnsupportedParams(virDomainDefPtr def)
{
    virDomainVideoDefPtr v;

2543
    if (IS_CT(def)) {
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
        if (def->nvideos == 0) {
            return 0;
        } else {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Video adapters are not supported "
                             "int containers."));
            return -1;
        }
    } else {
        if (def->nvideos != 1) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2555
                           _("vz driver supports "
2556 2557 2558 2559 2560 2561 2562 2563 2564
                             "only one video adapter."));
            return -1;
        }
    }

    v = def->videos[0];

    if (v->type != VIR_DOMAIN_VIDEO_TYPE_VGA) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2565
                       _("vz driver supports "
2566 2567 2568 2569 2570 2571
                         "only VGA video adapters."));
        return -1;
    }

    if (v->heads != 1) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2572
                       _("vz driver doesn't support "
2573 2574 2575 2576
                         "multihead video adapters."));
        return -1;
    }

2577
    if (v->accel != NULL && (v->accel->accel2d || v->accel->accel3d)) {
2578
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2579
                       _("vz driver doesn't support "
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
                         "setting video acceleration parameters."));
        return -1;
    }

    return 0;
}

static int prlsdkCheckSerialUnsupportedParams(virDomainChrDefPtr chr)
{
    if (chr->deviceType != VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Specified character device type is not supported "
2592
                         "by vz driver."));
2593 2594 2595 2596 2597 2598
        return -1;
    }

    if (chr->targetTypeAttr) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Specified character device target type is not "
2599
                         "supported by vz driver."));
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
        return -1;
    }

    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_DEV &&
        chr->source.type != VIR_DOMAIN_CHR_TYPE_FILE &&
        chr->source.type != VIR_DOMAIN_CHR_TYPE_UNIX) {


        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Specified character device source type is not "
2610
                         "supported by vz driver."));
2611 2612 2613 2614 2615 2616
        return -1;
    }

    if (chr->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting device info for character devices is not "
2617
                         "supported by vz driver."));
2618 2619 2620 2621 2622 2623
        return -1;
    }

    if (chr->nseclabels > 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting security labels is not "
2624
                         "supported by vz driver."));
2625 2626 2627 2628 2629 2630 2631 2632
        return -1;
    }

    return 0;
}

static int prlsdkCheckNetUnsupportedParams(virDomainNetDefPtr net)
{
2633 2634
    if (net->type != VIR_DOMAIN_NET_TYPE_NETWORK &&
        net->type != VIR_DOMAIN_NET_TYPE_BRIDGE) {
2635 2636
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Specified network adapter type is not "
2637
                         "supported by vz driver."));
2638 2639 2640 2641 2642 2643
        return -1;
    }

    if (net->backend.tap || net->backend.vhost) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Interface backend parameters are not "
2644
                         "supported by vz driver."));
2645 2646 2647 2648 2649 2650
        return -1;
    }

    if (net->data.network.portgroup) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Virtual network portgroups are not "
2651
                         "supported by vz driver."));
2652 2653 2654 2655 2656 2657
        return -1;
    }

    if (net->tune.sndbuf_specified) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting interface sndbuf is not "
2658
                         "supported by vz driver."));
2659 2660 2661 2662 2663 2664
        return -1;
    }

    if (net->script) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting interface script is not "
2665
                         "supported by vz driver."));
2666 2667 2668
        return -1;
    }

2669
    if (net->ifname_guest) {
2670 2671
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting guest interface name is not "
2672
                         "supported by vz driver."));
2673 2674 2675 2676 2677 2678
        return -1;
    }

    if (net->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting device info for network devices is not "
2679
                         "supported by vz driver."));
2680 2681 2682 2683 2684 2685
        return -1;
    }

    if (net->filter) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting network filter is not "
2686
                         "supported by vz driver."));
2687 2688 2689 2690 2691 2692
        return -1;
    }

    if (net->bandwidth) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting network bandwidth is not "
2693
                         "supported by vz driver."));
2694 2695 2696 2697 2698 2699
        return -1;
    }

    if (net->vlan.trunk) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting up vlans is not "
2700
                         "supported by vz driver."));
2701 2702 2703 2704 2705 2706
        return -1;
    }

    return 0;
}

2707 2708 2709 2710 2711
static int prlsdkCheckFSUnsupportedParams(virDomainFSDefPtr fs)
{
    if (fs->type != VIR_DOMAIN_FS_TYPE_FILE) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Only file based filesystems are "
2712
                         "supported by vz driver."));
2713 2714 2715 2716 2717 2718
        return -1;
    }

    if (fs->fsdriver != VIR_DOMAIN_FS_DRIVER_TYPE_PLOOP) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Only ploop fs driver is "
2719
                         "supported by vz driver."));
2720 2721 2722 2723 2724 2725
        return -1;
    }

    if (fs->accessmode != VIR_DOMAIN_FS_ACCESSMODE_PASSTHROUGH) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Changing fs access mode is not "
2726
                         "supported by vz driver."));
2727 2728 2729 2730 2731 2732
        return -1;
    }

    if (fs->wrpolicy != VIR_DOMAIN_FS_WRPOLICY_DEFAULT) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Changing fs write policy is not "
2733
                         "supported by vz driver."));
2734 2735 2736 2737 2738 2739
        return -1;
    }

    if (fs->format != VIR_STORAGE_FILE_PLOOP) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Only ploop disk images are "
2740
                         "supported by vz driver."));
2741 2742 2743 2744 2745 2746
        return -1;
    }

    if (fs->readonly) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting readonly for filesystems is "
2747
                         "not supported by vz driver."));
2748 2749 2750 2751 2752 2753
        return -1;
    }

    if (fs->space_hard_limit || fs->space_soft_limit) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Setting fs quotas is not "
2754
                         "supported by vz driver."));
2755 2756 2757 2758 2759 2760
        return -1;
    }

    return 0;
}

2761 2762
static int prlsdkApplyGraphicsParams(PRL_HANDLE sdkdom,
                                     virDomainGraphicsDefPtr gr)
2763
{
2764
    virDomainGraphicsListenDefPtr glisten;
2765 2766 2767
    PRL_RESULT pret;
    int ret  = -1;

2768 2769 2770
    if (!gr) {
        pret = PrlVmCfg_SetVNCMode(sdkdom, PRD_DISABLED);
        prlsdkCheckRetExit(pret, -1);
2771
        return 0;
2772
    }
2773

N
Nikolay Shirokovskiy 已提交
2774 2775 2776
    pret = PrlVmCfg_SetVNCPassword(sdkdom, gr->data.vnc.auth.passwd ? : "");
    prlsdkCheckRetExit(pret, -1);

2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
    if (gr->data.vnc.autoport) {
        pret = PrlVmCfg_SetVNCMode(sdkdom, PRD_AUTO);
        prlsdkCheckRetGoto(pret, cleanup);
    } else {
        pret = PrlVmCfg_SetVNCMode(sdkdom, PRD_MANUAL);
        prlsdkCheckRetGoto(pret, cleanup);

        pret = PrlVmCfg_SetVNCPort(sdkdom, gr->data.vnc.port);
        prlsdkCheckRetGoto(pret, cleanup);
    }

2788 2789 2790 2791
    glisten = virDomainGraphicsGetListen(gr, 0);
    pret = PrlVmCfg_SetVNCHostName(sdkdom, glisten && glisten->address ?
                                           glisten->address : "");
    prlsdkCheckRetGoto(pret, cleanup);
2792

2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
    ret = 0;
 cleanup:
    return ret;
}

static int prlsdkApplyVideoParams(PRL_HANDLE sdkdom ATTRIBUTE_UNUSED, virDomainDefPtr def)
{
    PRL_RESULT pret;

    if (def->nvideos == 0)
        return 0;

    if (IS_CT(def)) {
        /* ignore video parameters */
        return 0;
    }

    if (prlsdkCheckVideoUnsupportedParams(def))
        return -1;

    pret = PrlVmCfg_SetVideoRamSize(sdkdom, def->videos[0]->vram >> 10);
    prlsdkCheckRetGoto(pret, error);

    return 0;
 error:
    return -1;
}

static int prlsdkAddSerial(PRL_HANDLE sdkdom, virDomainChrDefPtr chr)
{
    PRL_RESULT pret;
    PRL_HANDLE sdkchr = PRL_INVALID_HANDLE;
    PRL_VM_DEV_EMULATION_TYPE emutype;
M
Michal Privoznik 已提交
2826
    PRL_SERIAL_PORT_SOCKET_OPERATION_MODE socket_mode = PSP_SERIAL_SOCKET_SERVER;
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854
    char *path;
    int ret = -1;

    if (prlsdkCheckSerialUnsupportedParams(chr) < 0)
        return -1;

    pret = PrlVmCfg_CreateVmDev(sdkdom, PDE_SERIAL_PORT, &sdkchr);
    prlsdkCheckRetGoto(pret, cleanup);

    switch (chr->source.type) {
    case VIR_DOMAIN_CHR_TYPE_DEV:
        emutype = PDT_USE_REAL_DEVICE;
        path = chr->source.data.file.path;
        break;
    case VIR_DOMAIN_CHR_TYPE_FILE:
        emutype = PDT_USE_OUTPUT_FILE;
        path = chr->source.data.file.path;
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
        emutype = PDT_USE_SERIAL_PORT_SOCKET_MODE;
        path = chr->source.data.nix.path;
        if (chr->source.data.nix.listen)
            socket_mode = PSP_SERIAL_SOCKET_SERVER;
        else
            socket_mode = PSP_SERIAL_SOCKET_CLIENT;
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
2855
                       _("vz driver doesn't support "
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
                         "specified serial source type."));
        goto cleanup;
    }

    pret = PrlVmDev_SetEmulatedType(sdkchr, emutype);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDev_SetSysName(sdkchr, path);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDev_SetFriendlyName(sdkchr, path);
    prlsdkCheckRetGoto(pret, cleanup);

    if (chr->source.type == VIR_DOMAIN_CHR_TYPE_UNIX) {
        pret = PrlVmDevSerial_SetSocketMode(sdkchr, socket_mode);
        prlsdkCheckRetGoto(pret, cleanup);
    }

    pret = PrlVmDev_SetEnabled(sdkchr, 1);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDev_SetIndex(sdkchr, chr->target.port);
    prlsdkCheckRetGoto(pret, cleanup);

    ret = 0;
 cleanup:
    PrlHandle_Free(sdkchr);
    return ret;
}

#define PRL_MAC_STRING_BUFNAME  13

static const char * prlsdkFormatMac(virMacAddrPtr mac, char *macstr)
{
    snprintf(macstr, PRL_MAC_STRING_BUFNAME,
             "%02X%02X%02X%02X%02X%02X",
             mac->addr[0], mac->addr[1], mac->addr[2],
             mac->addr[3], mac->addr[4], mac->addr[5]);
    macstr[PRL_MAC_STRING_BUFNAME - 1] = '\0';
    return macstr;
}

2898 2899 2900 2901
static int prlsdkConfigureGateways(PRL_HANDLE sdknet, virDomainNetDefPtr net)
{
    int ret = -1;
    size_t i;
2902
    virNetDevIPRoutePtr route4 = NULL, route6 = NULL;
2903 2904 2905
    char *gw4 = NULL, *gw6 = NULL;
    PRL_RESULT pret;

2906
    for (i = 0; i < net->guestIP.nroutes; i++) {
2907 2908 2909
        virSocketAddrPtr addrdst, gateway;
        virSocketAddr zero;

2910 2911
        addrdst = virNetDevIPRouteGetAddress(net->guestIP.routes[i]);
        gateway = virNetDevIPRouteGetGateway(net->guestIP.routes[i]);
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932

        ignore_value(virSocketAddrParse(&zero,
                                (VIR_SOCKET_ADDR_IS_FAMILY(addrdst, AF_INET)
                                 ? VIR_SOCKET_ADDR_IPV4_ALL
                                 : VIR_SOCKET_ADDR_IPV6_ALL),
                                VIR_SOCKET_ADDR_FAMILY(addrdst)));

        if (!virSocketAddrEqual(addrdst, &zero)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Support only default gateway"));
            return -1;
        }

        switch (VIR_SOCKET_ADDR_FAMILY(gateway)) {
        case AF_INET:
            if (route4) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Support only one IPv4 default gateway"));
                return -1;
            }

2933
            route4 = net->guestIP.routes[i];
2934 2935 2936 2937 2938 2939 2940 2941 2942

            break;
        case AF_INET6:
            if (route6) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                               _("Support only one IPv6 default gateway"));
                return -1;
            }

2943
            route6 = net->guestIP.routes[i];
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956

            break;
        default:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unsupported address family %d "
                             "Only IPv4 or IPv6 default gateway"),
                           VIR_SOCKET_ADDR_FAMILY(gateway));

            return -1;
        }
    }

    if (route4 &&
2957
        !(gw4 = virSocketAddrFormat(virNetDevIPRouteGetGateway(route4))))
2958 2959 2960 2961 2962 2963
        goto cleanup;

    pret = PrlVmDevNet_SetDefaultGateway(sdknet, gw4 ? : "");
    prlsdkCheckRetGoto(pret, cleanup);

    if (route6 &&
2964
        !(gw6 = virSocketAddrFormat(virNetDevIPRouteGetGateway(route6))))
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
        goto cleanup;

    pret = PrlVmDevNet_SetDefaultGatewayIPv6(sdknet, gw6 ? : "");
    prlsdkCheckRetGoto(pret, cleanup);

    ret = 0;

 cleanup:
    VIR_FREE(gw4);
    VIR_FREE(gw6);

    return ret;
}

N
Nikolay Shirokovskiy 已提交
2979 2980 2981 2982
static int prlsdkConfigureNet(vzDriverPtr driver,
                              PRL_HANDLE sdkdom,
                              virDomainNetDefPtr net,
                              bool isCt, bool create)
2983 2984 2985
{
    PRL_RESULT pret;
    PRL_HANDLE sdknet = PRL_INVALID_HANDLE;
2986 2987
    PRL_HANDLE vnet = PRL_INVALID_HANDLE;
    PRL_HANDLE job = PRL_INVALID_HANDLE;
2988 2989
    PRL_HANDLE addrlist = PRL_INVALID_HANDLE;
    size_t i;
2990 2991
    int ret = -1;
    char macstr[PRL_MAC_STRING_BUFNAME];
2992 2993 2994
    char *addrstr = NULL;
    bool ipv6present = false;
    bool ipv4present = false;
2995 2996 2997 2998

    if (prlsdkCheckNetUnsupportedParams(net) < 0)
        return -1;

N
Nikolay Shirokovskiy 已提交
2999 3000 3001 3002 3003 3004 3005 3006
    if (create) {
        pret = PrlVmCfg_CreateVmDev(sdkdom, PDE_GENERIC_NETWORK_ADAPTER, &sdknet);
        prlsdkCheckRetGoto(pret, cleanup);
    } else {
        sdknet = prlsdkFindNetByMAC(sdkdom, &net->mac);
        if (sdknet == PRL_INVALID_HANDLE)
            return -1;
    }
3007 3008 3009 3010

    pret = PrlVmDev_SetEnabled(sdknet, 1);
    prlsdkCheckRetGoto(pret, cleanup);

3011 3012 3013
    pret = PrlVmDev_SetConnected(sdknet, net->linkstate !=
                                 VIR_DOMAIN_NET_INTERFACE_LINK_STATE_DOWN);

3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
    prlsdkCheckRetGoto(pret, cleanup);

    if (net->ifname) {
        pret = PrlVmDevNet_SetHostInterfaceName(sdknet, net->ifname);
        prlsdkCheckRetGoto(pret, cleanup);
    }

    prlsdkFormatMac(&net->mac, macstr);
    pret = PrlVmDevNet_SetMacAddress(sdknet, macstr);
    prlsdkCheckRetGoto(pret, cleanup);

3025 3026 3027
    pret = PrlApi_CreateStringsList(&addrlist);
    prlsdkCheckRetGoto(pret, cleanup);

3028
    for (i = 0; i < net->guestIP.nips; i++) {
3029 3030
        char *tmpstr;

3031
        if (AF_INET == VIR_SOCKET_ADDR_FAMILY(&net->guestIP.ips[i]->address))
3032
            ipv4present = true;
3033
        else if (AF_INET6 == VIR_SOCKET_ADDR_FAMILY(&net->guestIP.ips[i]->address))
3034 3035 3036 3037
            ipv6present = true;
        else
            continue;

3038
        if (!(tmpstr = virSocketAddrFormat(&net->guestIP.ips[i]->address)))
3039 3040
            goto cleanup;

3041
        if (virAsprintf(&addrstr, "%s/%d", tmpstr, net->guestIP.ips[i]->prefix) < 0) {
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
            VIR_FREE(tmpstr);
            goto cleanup;
        }

        VIR_FREE(tmpstr);
        pret = PrlStrList_AddItem(addrlist, addrstr);
        prlsdkCheckRetGoto(pret, cleanup);

        VIR_FREE(addrstr);
    }

    if (ipv4present || ipv6present) {
        pret = PrlVmDevNet_SetNetAddresses(sdknet, addrlist);
        prlsdkCheckRetGoto(pret, cleanup);
    }

    pret = PrlVmDevNet_SetConfigureWithDhcp(sdknet, !ipv4present);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDevNet_SetConfigureWithDhcpIPv6(sdknet, !ipv6present);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDevNet_SetAutoApply(sdknet, true);
    prlsdkCheckRetGoto(pret, cleanup);

3067 3068
    if (prlsdkConfigureGateways(sdknet, net))
        goto cleanup;
3069

3070 3071
    if (isCt) {
        if (net->model)
M
Michal Privoznik 已提交
3072 3073
            VIR_WARN("Setting network adapter for containers is not "
                     "supported by vz driver.");
3074
    } else {
3075 3076 3077 3078 3079 3080 3081 3082
        if (STREQ(net->model, "rtl8139")) {
            pret = PrlVmDevNet_SetAdapterType(sdknet, PNT_RTL);
        } else if (STREQ(net->model, "e1000")) {
            pret = PrlVmDevNet_SetAdapterType(sdknet, PNT_E1000);
        } else if (STREQ(net->model, "virtio")) {
            pret = PrlVmDevNet_SetAdapterType(sdknet, PNT_VIRTIO);
        } else {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
M
Michal Privoznik 已提交
3083 3084
                           _("Specified network adapter model is not "
                             "supported by vz driver."));
3085 3086 3087
            goto cleanup;
        }
        prlsdkCheckRetGoto(pret, cleanup);
3088 3089
    }

3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
    if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
        if (STREQ(net->data.network.name, PARALLELS_DOMAIN_ROUTED_NETWORK_NAME)) {
            pret = PrlVmDev_SetEmulatedType(sdknet, PNA_ROUTED);
            prlsdkCheckRetGoto(pret, cleanup);
        } else if (STREQ(net->data.network.name, PARALLELS_DOMAIN_BRIDGED_NETWORK_NAME)) {
            pret = PrlVmDev_SetEmulatedType(sdknet, PNA_BRIDGED_ETHERNET);
            prlsdkCheckRetGoto(pret, cleanup);

            pret = PrlVmDevNet_SetVirtualNetworkId(sdknet, net->data.network.name);
            prlsdkCheckRetGoto(pret, cleanup);
        }
    } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
        /*
         * For this type of adapter we create a new
         * Virtual Network assuming that bridge with given name exists
         * Failing creating this means domain creation failure
         */
        pret = PrlVirtNet_Create(&vnet);
3108
        prlsdkCheckRetGoto(pret, cleanup);
3109

3110
        pret = PrlVirtNet_SetNetworkId(vnet, net->data.bridge.brname);
3111 3112 3113 3114 3115
        prlsdkCheckRetGoto(pret, cleanup);

        pret = PrlVirtNet_SetNetworkType(vnet, PVN_BRIDGED_ETHERNET);
        prlsdkCheckRetGoto(pret, cleanup);

3116
        job = PrlSrv_AddVirtualNetwork(driver->server,
3117 3118
                                       vnet,
                                       PRL_USE_VNET_NAME_FOR_BRIDGE_NAME);
3119
        if (PRL_FAILED(pret = waitJob(job)))
3120 3121 3122 3123 3124
            goto cleanup;

        pret = PrlVmDev_SetEmulatedType(sdknet, PNA_BRIDGED_ETHERNET);
        prlsdkCheckRetGoto(pret, cleanup);

3125
        pret = PrlVmDevNet_SetVirtualNetworkId(sdknet, net->data.bridge.brname);
3126 3127 3128
        prlsdkCheckRetGoto(pret, cleanup);
    }

3129 3130
    pret = PrlVmDevNet_SetPktFilterPreventMacSpoof(sdknet,
                net->trustGuestRxFilters == VIR_TRISTATE_BOOL_YES);
3131 3132 3133 3134
    prlsdkCheckRetGoto(pret, cleanup);

    ret = 0;
 cleanup:
3135 3136
    VIR_FREE(addrstr);
    PrlHandle_Free(addrlist);
3137
    PrlHandle_Free(vnet);
3138 3139 3140 3141
    PrlHandle_Free(sdknet);
    return ret;
}

3142
static void
3143
prlsdkCleanupBridgedNet(vzDriverPtr driver, virDomainNetDefPtr net)
3144 3145 3146 3147 3148
{
    PRL_RESULT pret;
    PRL_HANDLE vnet = PRL_INVALID_HANDLE;
    PRL_HANDLE job = PRL_INVALID_HANDLE;

3149 3150
    if (net->type != VIR_DOMAIN_NET_TYPE_BRIDGE)
        return;
3151 3152 3153 3154 3155 3156 3157

    pret = PrlVirtNet_Create(&vnet);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVirtNet_SetNetworkId(vnet, net->data.network.name);
    prlsdkCheckRetGoto(pret, cleanup);

3158
    job = PrlSrv_DeleteVirtualNetwork(driver->server, vnet, 0);
3159
    if (PRL_FAILED(pret = waitJob(job)))
3160 3161 3162 3163 3164 3165
        goto cleanup;

 cleanup:
    PrlHandle_Free(vnet);
}

3166 3167
static PRL_HANDLE
prlsdkFindNetByMAC(PRL_HANDLE sdkdom, virMacAddrPtr mac)
3168 3169 3170 3171 3172 3173 3174
{
    PRL_RESULT pret;
    PRL_UINT32 adaptersCount;
    PRL_UINT32 i;
    PRL_HANDLE adapter = PRL_INVALID_HANDLE;
    char adapterMac[PRL_MAC_STRING_BUFNAME];
    char expectedMac[PRL_MAC_STRING_BUFNAME];
3175
    char virMac[VIR_MAC_STRING_BUFLEN];
3176

3177 3178
    prlsdkFormatMac(mac, expectedMac);

3179 3180 3181 3182 3183 3184 3185
    pret = PrlVmCfg_GetNetAdaptersCount(sdkdom, &adaptersCount);
    prlsdkCheckRetGoto(pret, cleanup);

    for (i = 0; i < adaptersCount; ++i) {
        pret = PrlVmCfg_GetNetAdapter(sdkdom, i, &adapter);
        prlsdkCheckRetGoto(pret, cleanup);

3186 3187
        pret = prlsdkGetStringParamBuf(PrlVmDevNet_GetMacAddress,
                                       adapter, adapterMac, sizeof(adapterMac));
3188 3189
        prlsdkCheckRetGoto(pret, cleanup);

3190
        if (STREQ(adapterMac, expectedMac))
3191
            return adapter;
3192

3193 3194
        PrlHandle_Free(adapter);
        adapter = PRL_INVALID_HANDLE;
3195 3196
    }

3197 3198 3199
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("No net with mac '%s'"), virMacAddrFormat(mac, virMac));

3200 3201
 cleanup:
    PrlHandle_Free(adapter);
3202
    return adapter;
3203 3204
}

N
Nikolay Shirokovskiy 已提交
3205 3206 3207 3208 3209
static int prlsdkConfigureDisk(vzDriverPtr driver,
                               PRL_HANDLE sdkdom,
                               virDomainDiskDefPtr disk,
                               bool isCt,
                               bool create)
3210 3211 3212 3213 3214 3215
{
    PRL_RESULT pret;
    PRL_HANDLE sdkdisk = PRL_INVALID_HANDLE;
    int ret = -1;
    PRL_VM_DEV_EMULATION_TYPE emutype;
    PRL_MASS_STORAGE_INTERFACE_TYPE sdkbus;
3216 3217
    int idx;
    virDomainDeviceDriveAddressPtr drive;
3218
    PRL_DEVICE_TYPE devType;
M
Mikhail Feoktistov 已提交
3219
    PRL_CLUSTERED_DEVICE_SUBTYPE scsiModel;
3220
    const char *path = disk->src->path ? : "";
3221

D
Dmitry Guryanov 已提交
3222
    if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
3223
        devType = PDE_HARD_DISK;
D
Dmitry Guryanov 已提交
3224
    else
3225 3226
        devType = PDE_OPTICAL_DISK;

N
Nikolay Shirokovskiy 已提交
3227 3228 3229 3230 3231 3232 3233 3234
    if (create) {
        pret = PrlVmCfg_CreateVmDev(sdkdom, devType, &sdkdisk);
        prlsdkCheckRetGoto(pret, cleanup);
    } else {
        sdkdisk = prlsdkGetDisk(sdkdom, disk, isCt);
        if (sdkdisk == PRL_INVALID_HANDLE)
            return -1;
    }
3235 3236 3237 3238 3239 3240 3241

    pret = PrlVmDev_SetEnabled(sdkdisk, 1);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDev_SetConnected(sdkdisk, 1);
    prlsdkCheckRetGoto(pret, cleanup);

3242
    if (disk->src->type == VIR_STORAGE_TYPE_FILE)
3243
        emutype = PDT_USE_IMAGE_FILE;
3244
    else
3245 3246 3247 3248 3249
        emutype = PDT_USE_REAL_DEVICE;

    pret = PrlVmDev_SetEmulatedType(sdkdisk, emutype);
    prlsdkCheckRetGoto(pret, cleanup);

3250 3251
    pret = PrlVmDev_SetSysName(sdkdisk, path);
    prlsdkCheckRetGoto(pret, cleanup);
3252

3253 3254
    pret = PrlVmDev_SetFriendlyName(sdkdisk, path);
    prlsdkCheckRetGoto(pret, cleanup);
3255

3256 3257
    drive = &disk->info.addr.drive;

3258 3259 3260
    switch (disk->bus) {
    case VIR_DOMAIN_DISK_BUS_IDE:
        sdkbus = PMS_IDE_DEVICE;
3261
        idx = 2 * drive->bus + drive->unit;
3262 3263 3264
        break;
    case VIR_DOMAIN_DISK_BUS_SCSI:
        sdkbus = PMS_SCSI_DEVICE;
3265
        idx = drive->unit;
3266 3267 3268
        break;
    case VIR_DOMAIN_DISK_BUS_SATA:
        sdkbus = PMS_SATA_DEVICE;
3269
        idx = drive->unit;
3270 3271 3272 3273
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Specified disk bus is not "
3274
                         "supported by vz driver."));
3275 3276 3277
        goto cleanup;
    }

M
Mikhail Feoktistov 已提交
3278
    if (disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
3279
        if (vzGetDefaultSCSIModel(driver, &scsiModel) < 0)
M
Mikhail Feoktistov 已提交
3280 3281 3282 3283 3284
            goto cleanup;
        pret = PrlVmDev_SetSubType(sdkdisk, scsiModel);
        prlsdkCheckRetGoto(pret, cleanup);
    }

3285 3286 3287
    pret = PrlVmDev_SetIfaceType(sdkdisk, sdkbus);
    prlsdkCheckRetGoto(pret, cleanup);

3288
    pret = PrlVmDev_SetStackIndex(sdkdisk, idx);
3289 3290 3291 3292 3293 3294 3295 3296
    prlsdkCheckRetGoto(pret, cleanup);

    return 0;
 cleanup:
    PrlHandle_Free(sdkdisk);
    return ret;
}

3297 3298 3299 3300
static PRL_HANDLE
prlsdkGetDisk(PRL_HANDLE sdkdom, virDomainDiskDefPtr disk, bool isCt)
{
    PRL_RESULT pret;
3301
    PRL_UINT32 num;
3302
    size_t i;
3303
    PRL_HANDLE sdkdisk = PRL_INVALID_HANDLE;
3304 3305
    int bus;
    char *dst = NULL;
3306
    PRL_DEVICE_TYPE devType;
3307

3308 3309 3310 3311 3312 3313
    if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
        devType = PDE_HARD_DISK;
    else
        devType = PDE_OPTICAL_DISK;

    pret = PrlVmCfg_GetDevsCountByType(sdkdom, devType, &num);
3314 3315
    prlsdkCheckRetGoto(pret, error);

3316 3317
    for (i = 0; i < num; ++i) {
        pret = PrlVmCfg_GetDevByType(sdkdom, devType, i, &sdkdisk);
3318 3319
        prlsdkCheckRetGoto(pret, error);

3320
        if (prlsdkGetDiskId(sdkdisk, isCt, &bus, &dst) < 0)
3321 3322 3323 3324
            goto error;

        if (disk->bus == bus && STREQ(disk->dst, dst)) {
            VIR_FREE(dst);
3325
            return sdkdisk;
3326 3327
        }

3328 3329
        PrlHandle_Free(sdkdisk);
        sdkdisk = PRL_INVALID_HANDLE;
3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
        VIR_FREE(dst);
    }

    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("No disk with bus '%s' and target '%s'"),
                   virDomainDiskBusTypeToString(disk->bus), disk->dst);
    return PRL_INVALID_HANDLE;

 error:
    VIR_FREE(dst);
3340
    PrlHandle_Free(sdkdisk);
3341 3342 3343
    return PRL_INVALID_HANDLE;
}

3344
int
3345
prlsdkAttachDevice(vzDriverPtr driver,
M
Mikhail Feoktistov 已提交
3346
                   virDomainObjPtr dom,
3347
                   virDomainDeviceDefPtr dev)
3348
{
3349
    vzDomObjPtr privdom = dom->privateData;
3350 3351 3352
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_BeginEdit(privdom->sdkdom);
3353
    if (PRL_FAILED(waitJob(job)))
3354
        return -1;
3355

3356 3357
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
N
Nikolay Shirokovskiy 已提交
3358 3359
        if (prlsdkConfigureDisk(driver, privdom->sdkdom,
                                dev->data.disk, IS_CT(dom->def), true) < 0)
3360 3361 3362 3363 3364 3365 3366 3367
            return -1;

        break;
    case VIR_DOMAIN_DEVICE_NET:
        if (!IS_CT(dom->def)) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                           _("attaching network device to VM is unsupported"));
            return -1;
3368
        }
3369

N
Nikolay Shirokovskiy 已提交
3370 3371
        if (prlsdkConfigureNet(driver, privdom->sdkdom, dev->data.net,
                               IS_CT(dom->def), true) < 0)
3372 3373
            return -1;

3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        if (dom->def->ngraphics > 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("domain already has VNC graphics"));
            return -1;
        }

        if (prlsdkApplyGraphicsParams(privdom->sdkdom, dev->data.graphics) < 0)
            return -1;

3385 3386 3387 3388 3389 3390
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("attaching device type '%s' is unsupported"),
                       virDomainDeviceTypeToString(dev->type));
        return -1;
3391 3392
    }

3393 3394 3395 3396 3397
    job = PrlVm_CommitEx(privdom->sdkdom, PVCF_DETACH_HDD_BUNDLE);
    if (PRL_FAILED(waitJob(job)))
        return -1;

    return 0;
3398 3399
}

3400
int
3401 3402 3403
prlsdkDetachDevice(vzDriverPtr driver,
                   virDomainObjPtr dom,
                   virDomainDeviceDefPtr dev)
3404
{
3405
    int ret = -1;
3406
    vzDomObjPtr privdom = dom->privateData;
3407
    PRL_HANDLE job = PRL_INVALID_HANDLE;
3408
    PRL_HANDLE sdkdev = PRL_INVALID_HANDLE;
3409
    PRL_RESULT pret;
3410 3411

    job = PrlVm_BeginEdit(privdom->sdkdom);
3412
    if (PRL_FAILED(waitJob(job)))
3413 3414
        goto cleanup;

3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
        sdkdev = prlsdkGetDisk(privdom->sdkdom, dev->data.disk, IS_CT(dom->def));
        if (sdkdev == PRL_INVALID_HANDLE)
            goto cleanup;

        pret = PrlVmDev_Remove(sdkdev);
        prlsdkCheckRetGoto(pret, cleanup);

        break;
    case VIR_DOMAIN_DEVICE_NET:
        if (!IS_CT(dom->def)) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                           _("detaching network device from VM is unsupported"));
            goto cleanup;
        }

        sdkdev = prlsdkFindNetByMAC(privdom->sdkdom, &dev->data.net->mac);
        if (sdkdev == PRL_INVALID_HANDLE)
            goto cleanup;

        prlsdkCleanupBridgedNet(driver, dev->data.net);

        pret = PrlVmDev_Remove(sdkdev);
        prlsdkCheckRetGoto(pret, cleanup);

3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        if (dom->def->ngraphics < 1) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("cannot find VNC graphics device"));
            goto cleanup;
        }

        if (prlsdkApplyGraphicsParams(privdom->sdkdom, NULL) < 0)
            goto cleanup;

3452 3453 3454 3455 3456 3457 3458
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("detaching device type '%s' is unsupported"),
                       virDomainDeviceTypeToString(dev->type));
        goto cleanup;
    }
3459 3460 3461 3462 3463 3464

    job = PrlVm_CommitEx(privdom->sdkdom, PVCF_DETACH_HDD_BUNDLE);
    if (PRL_FAILED(waitJob(job)))
        goto cleanup;

    ret = 0;
3465 3466

 cleanup:
3467

3468
    PrlHandle_Free(sdkdev);
3469 3470 3471
    return ret;
}

N
Nikolay Shirokovskiy 已提交
3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495
int
prlsdkUpdateDevice(vzDriverPtr driver,
                   virDomainObjPtr dom,
                   virDomainDeviceDefPtr dev)
{
    vzDomObjPtr privdom = dom->privateData;
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_BeginEdit(privdom->sdkdom);
    if (PRL_FAILED(waitJob(job)))
        return -1;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
        if (prlsdkConfigureDisk(driver, privdom->sdkdom, dev->data.disk,
                                IS_CT(dom->def), false) < 0)
            return -1;

        break;
    case VIR_DOMAIN_DEVICE_NET:
        if (prlsdkConfigureNet(driver, privdom->sdkdom, dev->data.net,
                               IS_CT(dom->def), false) < 0)
            return -1;

3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
        break;
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        if (dom->def->ngraphics < 1) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("cannot find VNC graphics device"));
            return -1;
        }

        if (prlsdkApplyGraphicsParams(privdom->sdkdom, dev->data.graphics) < 0)
            return -1;

N
Nikolay Shirokovskiy 已提交
3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("updating device type '%s' is unsupported"),
                       virDomainDeviceTypeToString(dev->type));
        return -1;
    }

    job = PrlVm_CommitEx(privdom->sdkdom, PVCF_DETACH_HDD_BUNDLE);
    if (PRL_FAILED(waitJob(job)))
        return -1;

    return 0;
}

3522 3523 3524 3525 3526 3527 3528
static int
prlsdkAddFS(PRL_HANDLE sdkdom, virDomainFSDefPtr fs)
{
    PRL_RESULT pret;
    PRL_HANDLE sdkdisk = PRL_INVALID_HANDLE;
    int ret = -1;

3529 3530 3531
    if (fs->type == VIR_DOMAIN_FS_TYPE_TEMPLATE)
        return 0;

3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546
    if (prlsdkCheckFSUnsupportedParams(fs) < 0)
        return -1;

    pret = PrlVmCfg_CreateVmDev(sdkdom, PDE_HARD_DISK, &sdkdisk);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDev_SetEnabled(sdkdisk, 1);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDev_SetConnected(sdkdisk, 1);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDev_SetEmulatedType(sdkdisk, PDT_USE_IMAGE_FILE);
    prlsdkCheckRetGoto(pret, cleanup);

3547
    pret = PrlVmDev_SetSysName(sdkdisk, fs->src->path);
3548 3549
    prlsdkCheckRetGoto(pret, cleanup);

3550
    pret = PrlVmDev_SetImagePath(sdkdisk, fs->src->path);
3551 3552
    prlsdkCheckRetGoto(pret, cleanup);

3553
    pret = PrlVmDev_SetFriendlyName(sdkdisk, fs->src->path);
3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmDevHd_SetMountPoint(sdkdisk, fs->dst);
    prlsdkCheckRetGoto(pret, cleanup);

    ret = 0;

 cleanup:
    PrlHandle_Free(sdkdisk);
    return ret;
}
3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637

static int
prlsdkSetBootOrderCt(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    size_t i;
    PRL_HANDLE hdd = PRL_INVALID_HANDLE;
    PRL_RESULT pret;
    int ret = -1;

    /* if we have root mounted we don't need to explicitly set boot order */
    for (i = 0; i < def->nfss; i++) {
        if (STREQ(def->fss[i]->dst, "/"))
            return 0;
    }

    /* else set first hard disk as boot device */
    pret = prlsdkAddDeviceToBootList(sdkdom, 0, PDE_HARD_DISK, 0);
    prlsdkCheckRetExit(pret, -1);

    pret = PrlVmCfg_GetHardDisk(sdkdom, 0, &hdd);
    prlsdkCheckRetExit(pret, -1);

    PrlVmDevHd_SetMountPoint(hdd, "/");
    prlsdkCheckRetGoto(pret, cleanup);

    ret = 0;

 cleanup:
    PrlHandle_Free(hdd);
    return ret;
}

static int
prlsdkSetBootOrderVm(PRL_HANDLE sdkdom, virDomainDefPtr def)
{
    size_t i;
    int idx[VIR_DOMAIN_BOOT_LAST] = { 0 };
    int bootIndex = 0;
    PRL_RESULT pret;
    PRL_UINT32 num;
    int sdkType;
    virDomainBootOrder virType;

    for (i = 0; i < def->os.nBootDevs; ++i) {
        virType = def->os.bootDevs[i];

        switch (virType) {
        case VIR_DOMAIN_BOOT_CDROM:
            sdkType = PDE_OPTICAL_DISK;
            break;
        case VIR_DOMAIN_BOOT_DISK:
            sdkType = PDE_HARD_DISK;
            break;
        case VIR_DOMAIN_BOOT_NET:
            sdkType = PDE_GENERIC_NETWORK_ADAPTER;
            break;
        default:
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Unsupported boot device type: '%s'"),
                           virDomainBootTypeToString(virType));
            return -1;
        }

        pret = PrlVmCfg_GetDevsCountByType(sdkdom, sdkType, &num);
        prlsdkCheckRetExit(pret, -1);

        pret = prlsdkAddDeviceToBootList(sdkdom, idx[virType]++, sdkType, bootIndex++);
        prlsdkCheckRetExit(pret, -1);
    }

    return 0;
}

3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668
int
prlsdkDomainSetUserPassword(virDomainObjPtr dom,
                            const char *user,
                            const char *password)
{
    int ret = -1;
    vzDomObjPtr privdom = dom->privateData;
    PRL_HANDLE job = PRL_INVALID_HANDLE;

    job = PrlVm_BeginEdit(privdom->sdkdom);
    if (PRL_FAILED(waitJob(job)))
        goto cleanup;

    job = PrlVm_SetUserPasswd(privdom->sdkdom,
                              user,
                              password,
                              0);

    if (PRL_FAILED(waitJob(job)))
        goto cleanup;

    job = PrlVm_CommitEx(privdom->sdkdom, 0);
    if (PRL_FAILED(waitJob(job)))
        goto cleanup;

    ret = 0;

 cleanup:
    return ret;
}

3669
static int
3670
prlsdkDoApplyConfig(vzDriverPtr driver,
3671
                    PRL_HANDLE sdkdom,
3672 3673
                    virDomainDefPtr def,
                    virDomainDefPtr olddef)
3674 3675 3676
{
    PRL_RESULT pret;
    size_t i;
3677
    char uuidstr[VIR_UUID_STRING_BRACED_BUFLEN];
M
Maxim Nestratov 已提交
3678
    char *mask = NULL;
3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699

    if (prlsdkCheckUnsupportedParams(sdkdom, def) < 0)
        return -1;

    if (def->description) {
        pret = PrlVmCfg_SetDescription(sdkdom, def->description);
        prlsdkCheckRetGoto(pret, error);
    }

    if (def->name) {
        pret = PrlVmCfg_SetName(sdkdom, def->name);
        prlsdkCheckRetGoto(pret, error);
    }

    if (def->uuid) {
        prlsdkUUIDFormat(def->uuid, uuidstr);

        pret = PrlVmCfg_SetUuid(sdkdom, uuidstr);
        prlsdkCheckRetGoto(pret, error);
    }

3700
    pret = PrlVmCfg_SetRamSize(sdkdom, virDomainDefGetMemoryTotal(def) >> 10);
3701 3702
    prlsdkCheckRetGoto(pret, error);

3703
    pret = PrlVmCfg_SetCpuCount(sdkdom, virDomainDefGetVcpus(def));
3704 3705
    prlsdkCheckRetGoto(pret, error);

M
Maxim Nestratov 已提交
3706 3707 3708 3709 3710 3711 3712
    if (!(mask = virBitmapFormat(def->cpumask)))
        goto error;

    pret = PrlVmCfg_SetCpuMask(sdkdom, mask);
    prlsdkCheckRetGoto(pret, error);
    VIR_FREE(mask);

3713
    switch (def->os.arch) {
M
Michal Privoznik 已提交
3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724
    case VIR_ARCH_X86_64:
        pret = PrlVmCfg_SetCpuMode(sdkdom, PCM_CPU_MODE_64);
        break;
    case VIR_ARCH_I686:
        pret = PrlVmCfg_SetCpuMode(sdkdom, PCM_CPU_MODE_32);
        break;
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown CPU mode: %s"),
                       virArchToString(def->os.arch));
        goto error;
3725 3726 3727
    }
    prlsdkCheckRetGoto(pret, error);

3728 3729 3730
    if (prlsdkClearDevices(sdkdom) < 0)
        goto error;

3731 3732 3733
    if (prlsdkRemoveBootDevices(sdkdom) < 0)
        goto error;

3734 3735
    if (olddef) {
        for (i = 0; i < olddef->nnets; i++)
3736
            prlsdkCleanupBridgedNet(driver, olddef->nets[i]);
3737 3738 3739
    }

    for (i = 0; i < def->nnets; i++) {
N
Nikolay Shirokovskiy 已提交
3740 3741
        if (prlsdkConfigureNet(driver, sdkdom, def->nets[i],
                               IS_CT(def), true) < 0)
M
Michal Privoznik 已提交
3742
            goto error;
3743 3744
    }

3745 3746 3747 3748 3749 3750 3751 3752
    if (def->ngraphics > 1) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("vz driver supports only VNC graphics"));
        goto error;
    }

    if (prlsdkApplyGraphicsParams(sdkdom,
                                  def->ngraphics == 1 ? def->graphics[0] : NULL) < 0)
3753 3754 3755 3756 3757 3758
        goto error;

    if (prlsdkApplyVideoParams(sdkdom, def) < 0)
        goto error;

    for (i = 0; i < def->nserials; i++) {
M
Mikhail Feoktistov 已提交
3759 3760
        if (prlsdkAddSerial(sdkdom, def->serials[i]) < 0)
            goto error;
3761 3762
    }

3763 3764 3765 3766 3767
    for (i = 0; i < def->nfss; i++) {
        if (prlsdkAddFS(sdkdom, def->fss[i]) < 0)
            goto error;
    }

3768
    for (i = 0; i < def->ndisks; i++) {
N
Nikolay Shirokovskiy 已提交
3769 3770
        if (prlsdkConfigureDisk(driver, sdkdom, def->disks[i],
                                IS_CT(def), true) < 0)
3771 3772
            goto error;
    }
3773

3774 3775 3776 3777 3778
    if (IS_CT(def)) {
        if (prlsdkSetBootOrderCt(sdkdom, def) < 0)
            goto error;
    } else {
        if (prlsdkSetBootOrderVm(sdkdom, def) < 0)
M
Mikhail Feoktistov 已提交
3779
            goto error;
3780 3781 3782 3783 3784
    }

    return 0;

 error:
M
Maxim Nestratov 已提交
3785 3786
    VIR_FREE(mask);

3787
    for (i = 0; i < def->nnets; i++)
3788
        prlsdkCleanupBridgedNet(driver, def->nets[i]);
3789

M
Michal Privoznik 已提交
3790
    return -1;
3791 3792 3793
}

int
3794
prlsdkApplyConfig(vzDriverPtr driver,
3795 3796 3797 3798 3799 3800 3801
                  virDomainObjPtr dom,
                  virDomainDefPtr new)
{
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;
    PRL_HANDLE job = PRL_INVALID_HANDLE;
    int ret;

3802
    sdkdom = prlsdkSdkDomainLookupByUUID(driver, dom->def->uuid);
3803 3804 3805 3806
    if (sdkdom == PRL_INVALID_HANDLE)
        return -1;

    job = PrlVm_BeginEdit(sdkdom);
3807
    if (PRL_FAILED(waitJob(job)))
3808 3809
        return -1;

3810
    ret = prlsdkDoApplyConfig(driver, sdkdom, new, dom->def);
3811 3812

    if (ret == 0) {
3813
        job = PrlVm_CommitEx(sdkdom, PVCF_DETACH_HDD_BUNDLE);
3814
        if (PRL_FAILED(waitJob(job)))
3815
            ret = -1;
3816 3817 3818 3819 3820 3821
    }

    PrlHandle_Free(sdkdom);

    return ret;
}
3822 3823

int
3824
prlsdkCreateVm(vzDriverPtr driver, virDomainDefPtr def)
3825 3826 3827 3828 3829 3830 3831 3832
{
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;
    PRL_HANDLE job = PRL_INVALID_HANDLE;
    PRL_HANDLE result = PRL_INVALID_HANDLE;
    PRL_HANDLE srvconf = PRL_INVALID_HANDLE;
    PRL_RESULT pret;
    int ret = -1;

3833
    pret = PrlSrv_CreateVm(driver->server, &sdkdom);
3834 3835
    prlsdkCheckRetGoto(pret, cleanup);

3836
    job = PrlSrv_GetSrvConfig(driver->server);
3837
    if (PRL_FAILED(getJobResult(job, &result)))
3838 3839 3840 3841 3842 3843 3844 3845
        goto cleanup;

    pret = PrlResult_GetParamByIndex(result, 0, &srvconf);
    prlsdkCheckRetGoto(pret, cleanup);

    pret = PrlVmCfg_SetDefaultConfig(sdkdom, srvconf, PVS_GUEST_VER_LIN_REDHAT, 0);
    prlsdkCheckRetGoto(pret, cleanup);

3846 3847 3848
    pret = PrlVmCfg_SetOfflineManagementEnabled(sdkdom, 0);
    prlsdkCheckRetGoto(pret, cleanup);

3849
    ret = prlsdkDoApplyConfig(driver, sdkdom, def, NULL);
3850 3851 3852 3853
    if (ret)
        goto cleanup;

    job = PrlVm_Reg(sdkdom, "", 1);
3854
    if (PRL_FAILED(waitJob(job)))
3855
        ret = -1;
3856 3857 3858 3859 3860 3861 3862

 cleanup:
    PrlHandle_Free(sdkdom);
    return ret;
}

int
3863
prlsdkCreateCt(vzDriverPtr driver, virDomainDefPtr def)
3864 3865 3866 3867 3868 3869
{
    PRL_HANDLE sdkdom = PRL_INVALID_HANDLE;
    PRL_GET_VM_CONFIG_PARAM_DATA confParam;
    PRL_HANDLE job = PRL_INVALID_HANDLE;
    PRL_HANDLE result = PRL_INVALID_HANDLE;
    PRL_RESULT pret;
3870
    PRL_UINT32 flags;
3871
    int ret = -1;
3872 3873
    int useTemplate = 0;
    size_t i;
3874

3875 3876
    for (i = 0; i < def->nfss; i++) {
        if (useTemplate) {
3877
            virReportError(VIR_ERR_INVALID_ARG, "%s",
3878
                           _("Unsupported configuration"));
3879 3880
            return -1;
        }
3881 3882 3883 3884 3885 3886 3887 3888
        if (def->fss[i]->type == VIR_DOMAIN_FS_TYPE_TEMPLATE)
            useTemplate = 1;
    }

    if (useTemplate && def->nfss > 1) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Unsupported configuration"));
        return -1;
3889 3890 3891 3892 3893 3894
    }

    confParam.nVmType = PVT_CT;
    confParam.sConfigSample = "vswap.1024MB";
    confParam.nOsVersion = 0;

3895
    job = PrlSrv_GetDefaultVmConfig(driver->server, &confParam, 0);
3896
    if (PRL_FAILED(getJobResult(job, &result)))
3897 3898 3899 3900 3901
        goto cleanup;

    pret = PrlResult_GetParamByIndex(result, 0, &sdkdom);
    prlsdkCheckRetGoto(pret, cleanup);

3902
    if (useTemplate) {
3903
        pret = PrlVmCfg_SetOsTemplate(sdkdom, def->fss[0]->src->path);
3904
        prlsdkCheckRetGoto(pret, cleanup);
3905

3906 3907
    }

3908
    if (prlsdkDoApplyConfig(driver, sdkdom, def, NULL) < 0)
3909 3910
        goto cleanup;

3911 3912 3913 3914
    flags = PACF_NON_INTERACTIVE_MODE;
    if (!useTemplate)
        flags |= PRNVM_PRESERVE_DISK;
    job = PrlVm_RegEx(sdkdom, "", flags);
3915
    if (PRL_FAILED(waitJob(job)))
3916 3917 3918
        goto cleanup;

    ret = 0;
3919 3920 3921

 cleanup:
    PrlHandle_Free(sdkdom);
3922
    return ret;
3923
}
3924

3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939
/**
 * prlsdkDetachDomainHardDisks:
 *
 * @sdkdom: domain handle
 *
 * Returns 0 if hard disks were successfully detached or not detected.
 */
static int
prlsdkDetachDomainHardDisks(PRL_HANDLE sdkdom)
{
    int ret = -1;
    PRL_RESULT pret;
    PRL_UINT32 hddCount;
    PRL_UINT32 i;
    PRL_HANDLE job;
3940
    PRL_HANDLE sdkdisk = PRL_INVALID_HANDLE;
3941 3942 3943 3944 3945 3946 3947 3948 3949

    job = PrlVm_BeginEdit(sdkdom);
    if (PRL_FAILED(waitJob(job)))
        goto cleanup;

    pret = PrlVmCfg_GetHardDisksCount(sdkdom, &hddCount);
    prlsdkCheckRetGoto(pret, cleanup);

    for (i = 0; i < hddCount; ++i) {
M
Mikhail Feoktistov 已提交
3950
        pret = PrlVmCfg_GetHardDisk(sdkdom, 0, &sdkdisk);
3951 3952 3953 3954 3955 3956 3957
        prlsdkCheckRetGoto(pret, cleanup);

        pret = PrlVmDev_Remove(sdkdisk);
        prlsdkCheckRetGoto(pret, cleanup);

        PrlHandle_Free(sdkdisk);
        sdkdisk = PRL_INVALID_HANDLE;
3958 3959 3960 3961
    }

    job = PrlVm_CommitEx(sdkdom, PVCF_DETACH_HDD_BUNDLE);
    if (PRL_FAILED(waitJob(job)))
3962
        goto cleanup;
3963

3964
    ret = 0;
3965

3966 3967
 cleanup:
    PrlHandle_Free(sdkdisk);
3968 3969 3970
    return ret;
}

3971
int
3972
prlsdkUnregisterDomain(vzDriverPtr driver, virDomainObjPtr dom, unsigned int flags)
3973
{
3974
    vzDomObjPtr privdom = dom->privateData;
3975
    PRL_HANDLE job;
3976
    size_t i;
3977
    virDomainSnapshotObjListPtr snapshots = NULL;
3978
    VIRTUAL_MACHINE_STATE domainState;
3979 3980
    int ret = -1;
    int num;
3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993

    if (prlsdkGetDomainState(privdom->sdkdom, &domainState) < 0)
        return -1;

    if (VMS_SUSPENDED == domainState &&
        !(flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE)) {

        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Refusing to undefine while domain managed "
                         "save image exists"));
        return -1;
    }

3994
    if (!(snapshots = prlsdkLoadSnapshots(dom)))
3995
        return -1;
3996

3997 3998 3999 4000
    if ((num = virDomainSnapshotObjListNum(snapshots, NULL, 0)) < 0)
        goto cleanup;

    if (num > 0 && !(flags & VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA)) {
4001 4002
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while snapshots exist"));
4003
        goto cleanup;
4004
    }
4005

4006
    if (prlsdkDetachDomainHardDisks(privdom->sdkdom))
4007
        goto cleanup;
4008 4009

    job = PrlVm_Delete(privdom->sdkdom, PRL_INVALID_HANDLE);
4010
    if (PRL_FAILED(waitJob(job)))
4011
        goto cleanup;
4012

4013
    for (i = 0; i < dom->def->nnets; i++)
4014
        prlsdkCleanupBridgedNet(driver, dom->def->nets[i]);
4015

4016
    if (prlsdkSendEvent(driver, dom, VIR_DOMAIN_EVENT_UNDEFINED,
4017
                        VIR_DOMAIN_EVENT_UNDEFINED_REMOVED) < 0)
4018
        goto cleanup;
4019

4020
    virDomainObjListRemove(driver->domains, dom);
4021 4022 4023 4024 4025 4026

    ret = 0;
 cleanup:

    virDomainSnapshotObjListFree(snapshots);
    return ret;
4027
}
4028 4029

int
4030
prlsdkDomainManagedSaveRemove(virDomainObjPtr dom)
4031
{
4032
    vzDomObjPtr privdom = dom->privateData;
4033 4034 4035
    PRL_HANDLE job;

    job = PrlVm_DropSuspendedState(privdom->sdkdom);
4036
    if (PRL_FAILED(waitJob(job)))
4037 4038 4039 4040
        return -1;

    return 0;
}
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 4070 4071 4072

static int
prlsdkExtractStatsParam(PRL_HANDLE sdkstats, const char *name, long long *val)
{
    PRL_HANDLE param = PRL_INVALID_HANDLE;
    PRL_RESULT pret;
    PRL_INT64 pval = 0;
    int ret = -1;

    pret = PrlEvent_GetParamByName(sdkstats, name, &param);
    if (pret == PRL_ERR_NO_DATA) {
        *val = -1;
        ret = 0;
        goto cleanup;
    } else if (PRL_FAILED(pret)) {
        logPrlError(pret);
        goto cleanup;
    }
    pret = PrlEvtPrm_ToInt64(param, &pval);
    prlsdkCheckRetGoto(pret, cleanup);

    *val = pval;
    ret = 0;

 cleanup:
    PrlHandle_Free(param);
    return ret;
}

#define PARALLELS_STATISTICS_TIMEOUT (60 * 1000)

int
4073 4074 4075
prlsdkGetBlockStats(PRL_HANDLE sdkstats,
                    virDomainDiskDefPtr disk,
                    virDomainBlockStatsPtr stats)
4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098
{
    virDomainDeviceDriveAddressPtr address;
    int idx;
    const char *prefix;
    int ret = -1;
    char *name = NULL;

    address = &disk->info.addr.drive;
    switch (disk->bus) {
    case VIR_DOMAIN_DISK_BUS_IDE:
        prefix = "ide";
        idx = address->bus * 2 + address->unit;
        break;
    case VIR_DOMAIN_DISK_BUS_SATA:
        prefix = "sata";
        idx = address->unit;
        break;
    case VIR_DOMAIN_DISK_BUS_SCSI:
        prefix = "scsi";
        idx = address->unit;
        break;
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR,
M
Michal Privoznik 已提交
4099
                       _("Unknown disk bus: %X"), disk->bus);
4100 4101 4102 4103 4104 4105 4106
        goto cleanup;
    }


#define PRLSDK_GET_STAT_PARAM(VAL, TYPE, NAME)                          \
    if (virAsprintf(&name, "devices.%s%d.%s", prefix, idx, NAME) < 0)   \
        goto cleanup;                                                   \
4107
    if (prlsdkExtractStatsParam(sdkstats, name, &stats->VAL) < 0)       \
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121
        goto cleanup;                                                   \
    VIR_FREE(name);

    PARALLELS_BLOCK_STATS_FOREACH(PRLSDK_GET_STAT_PARAM)

#undef PRLSDK_GET_STAT_PARAM

    ret = 0;

 cleanup:

    VIR_FREE(name);
    return ret;
}
4122

4123

4124
static PRL_HANDLE
4125
prlsdkFindNetByPath(PRL_HANDLE sdkdom, const char *path)
4126 4127 4128 4129 4130 4131 4132
{
    PRL_UINT32 count = 0;
    PRL_RESULT pret;
    size_t i;
    char *name = NULL;
    PRL_HANDLE net = PRL_INVALID_HANDLE;

4133
    pret = PrlVmCfg_GetNetAdaptersCount(sdkdom, &count);
4134 4135 4136
    prlsdkCheckRetGoto(pret, error);

    for (i = 0; i < count; ++i) {
4137
        pret = PrlVmCfg_GetNetAdapter(sdkdom, i, &net);
4138 4139
        prlsdkCheckRetGoto(pret, error);

4140 4141
        if (!(name = prlsdkGetStringParamVar(PrlVmDevNet_GetHostInterfaceName,
                                             net)))
4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163
            goto error;

        if (STREQ(name, path))
            break;

        VIR_FREE(name);
        PrlHandle_Free(net);
        net = PRL_INVALID_HANDLE;
    }

    if (net == PRL_INVALID_HANDLE)
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid path, '%s' is not a known interface"), path);
    return net;

 error:
    VIR_FREE(name);
    PrlHandle_Free(net);
    return PRL_INVALID_HANDLE;
}

int
4164
prlsdkGetNetStats(PRL_HANDLE sdkstats, PRL_HANDLE sdkdom, const char *path,
4165 4166 4167 4168 4169 4170 4171 4172
                  virDomainInterfaceStatsPtr stats)
{
    int ret = -1;
    PRL_UINT32 net_index = -1;
    char *name = NULL;
    PRL_RESULT pret;
    PRL_HANDLE net = PRL_INVALID_HANDLE;

4173
    net = prlsdkFindNetByPath(sdkdom, path);
4174 4175 4176 4177 4178 4179 4180 4181 4182
    if (net == PRL_INVALID_HANDLE)
       goto cleanup;

    pret = PrlVmDev_GetIndex(net, &net_index);
    prlsdkCheckRetGoto(pret, cleanup);

#define PRLSDK_GET_NET_COUNTER(VAL, NAME)                           \
    if (virAsprintf(&name, "net.nic%d.%s", net_index, NAME) < 0)    \
        goto cleanup;                                               \
4183
    if (prlsdkExtractStatsParam(sdkstats, name, &stats->VAL) < 0)   \
4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204
        goto cleanup;                                               \
    VIR_FREE(name);

    PRLSDK_GET_NET_COUNTER(rx_bytes, "bytes_in")
    PRLSDK_GET_NET_COUNTER(rx_packets, "pkts_in")
    PRLSDK_GET_NET_COUNTER(tx_bytes, "bytes_out")
    PRLSDK_GET_NET_COUNTER(tx_packets, "pkts_out")
    stats->rx_errs = -1;
    stats->rx_drop = -1;
    stats->tx_errs = -1;
    stats->tx_drop = -1;

#undef PRLSDK_GET_NET_COUNTER
    ret = 0;

 cleanup:
    VIR_FREE(name);
    PrlHandle_Free(net);

    return ret;
}
N
Nikolay Shirokovskiy 已提交
4205 4206

int
4207
prlsdkGetVcpuStats(PRL_HANDLE sdkstats, int idx, unsigned long long *vtime)
N
Nikolay Shirokovskiy 已提交
4208 4209 4210 4211 4212 4213 4214
{
    char *name = NULL;
    long long ptime = 0;
    int ret = -1;

    if (virAsprintf(&name, "guest.vcpu%u.time", (unsigned int)idx) < 0)
        goto cleanup;
4215
    if (prlsdkExtractStatsParam(sdkstats, name, &ptime) < 0)
N
Nikolay Shirokovskiy 已提交
4216 4217 4218 4219 4220 4221 4222 4223
        goto cleanup;
    *vtime = ptime == -1 ? 0 : ptime;
    ret = 0;

 cleanup:
    VIR_FREE(name);
    return ret;
}
N
Nikolay Shirokovskiy 已提交
4224 4225

int
4226
prlsdkGetMemoryStats(PRL_HANDLE sdkstats,
N
Nikolay Shirokovskiy 已提交
4227 4228 4229 4230 4231 4232 4233 4234
                     virDomainMemoryStatPtr stats,
                     unsigned int nr_stats)
{
    int ret = -1;
    long long v = 0, t = 0, u = 0;
    size_t i = 0;

#define PRLSDK_GET_COUNTER(NAME, VALUE)                             \
4235
    if (prlsdkExtractStatsParam(sdkstats, NAME, &VALUE) < 0)        \
N
Nikolay Shirokovskiy 已提交
4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284
        goto cleanup;                                               \

#define PRLSDK_MEMORY_STAT_SET(TAG, VALUE)                          \
    if (i < nr_stats) {                                             \
        stats[i].tag = (TAG);                                       \
        stats[i].val = (VALUE);                                     \
        i++;                                                        \
    }

    i = 0;

    // count to kb
    PRLSDK_GET_COUNTER("guest.ram.swap_in", v)
    if (v != -1)
        PRLSDK_MEMORY_STAT_SET(VIR_DOMAIN_MEMORY_STAT_SWAP_IN, v << 12)

    PRLSDK_GET_COUNTER("guest.ram.swap_out", v)
    if (v != -1)
        PRLSDK_MEMORY_STAT_SET(VIR_DOMAIN_MEMORY_STAT_SWAP_OUT, v << 12)

    PRLSDK_GET_COUNTER("guest.ram.minor_fault", v)
    if (v != -1)
        PRLSDK_MEMORY_STAT_SET(VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT, v)

    PRLSDK_GET_COUNTER("guest.ram.major_fault", v)
    if (v != -1)
        PRLSDK_MEMORY_STAT_SET(VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT, v)

    PRLSDK_GET_COUNTER("guest.ram.total", v)
    if (v != -1)
        PRLSDK_MEMORY_STAT_SET(VIR_DOMAIN_MEMORY_STAT_AVAILABLE, v << 10)

    PRLSDK_GET_COUNTER("guest.ram.balloon_actual", v)
    if (v != -1)
        PRLSDK_MEMORY_STAT_SET(VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON, v << 10)

    PRLSDK_GET_COUNTER("guest.ram.usage", u)
    PRLSDK_GET_COUNTER("guest.ram.total", t)
    if (u != -1 && t != -1)
        PRLSDK_MEMORY_STAT_SET(VIR_DOMAIN_MEMORY_STAT_UNUSED, (t - u) << 10)

#undef PRLSDK_GET_COUNTER
#undef PRLSDK_MEMORY_STAT_SET

    ret = i;
 cleanup:

    return ret;
}
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308

/* memsize is in MiB */
int prlsdkSetMemsize(virDomainObjPtr dom, unsigned int memsize)
{
    vzDomObjPtr privdom = dom->privateData;
    PRL_HANDLE job;
    PRL_RESULT pret;

    job = PrlVm_BeginEdit(privdom->sdkdom);
    if (PRL_FAILED(waitJob(job)))
        goto error;

    pret = PrlVmCfg_SetRamSize(privdom->sdkdom, memsize);
    prlsdkCheckRetGoto(pret, error);

    job = PrlVm_CommitEx(privdom->sdkdom, 0);
    if (PRL_FAILED(waitJob(job)))
        goto error;

    return 0;

 error:
    return -1;
}
4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 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 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524

static long long
prlsdkParseDateTime(const char *str)
{
    struct tm tm;
    const char *tmp;

    tmp = strptime(str, "%Y-%m-%d %H:%M:%S", &tm);
    if (!tmp || *tmp != '\0') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected DateTime format: '%s'"), str);
        return -1;
    }

    return mktime(&tm);
}

static virDomainSnapshotObjListPtr
prlsdkParseSnapshotTree(const char *treexml)
{
    virDomainSnapshotObjListPtr ret = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr root;
    xmlNodePtr *nodes = NULL;
    virDomainSnapshotDefPtr def = NULL;
    virDomainSnapshotObjPtr snapshot;
    virDomainSnapshotObjPtr current = NULL;
    virDomainSnapshotObjListPtr snapshots = NULL;
    char *xmlstr = NULL;
    int n;
    size_t i;

    if (!(snapshots = virDomainSnapshotObjListNew()))
        return NULL;

    if (*treexml == '\0')
        return snapshots;

    if (!(xml = virXMLParse(NULL, treexml, _("(snapshot_tree)"))))
        goto cleanup;

    root = xmlDocGetRootElement(xml);
    if (!xmlStrEqual(root->name, BAD_CAST "ParallelsSavedStates")) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected root element: '%s'"), root->name);
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virReportOOMError();
        goto cleanup;
    }
    ctxt->node = root;

    if ((n = virXPathNodeSet("//SavedStateItem", ctxt, &nodes)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot extract snapshot nodes"));
        goto cleanup;
    }

    for (i = 0; i < n; i++) {
        if (nodes[i]->parent == root)
            continue;

        if (VIR_ALLOC(def) < 0)
            goto cleanup;

        ctxt->node = nodes[i];

        def->name = virXPathString("string(./@guid)", ctxt);
        if (!def->name) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing 'guid' attribute"));
            goto cleanup;
        }

        def->parent = virXPathString("string(../@guid)", ctxt);

        xmlstr = virXPathString("string(./DateTime)", ctxt);
        if (!xmlstr) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing 'DateTime' element"));
            goto cleanup;
        }
        if ((def->creationTime = prlsdkParseDateTime(xmlstr)) < 0)
            goto cleanup;
        VIR_FREE(xmlstr);

        def->description = virXPathString("string(./Description)", ctxt);

        def->memory = VIR_DOMAIN_SNAPSHOT_LOCATION_NONE;
        xmlstr = virXPathString("string(./@state)", ctxt);
        if (!xmlstr) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing 'state' attribute"));
            goto cleanup;
        } else if (STREQ(xmlstr, "poweron")) {
            def->state = VIR_DOMAIN_RUNNING;
            def->memory = VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL;
        } else if (STREQ(xmlstr, "pause")) {
            def->state = VIR_DOMAIN_PAUSED;
            def->memory = VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL;
        } else if (STREQ(xmlstr, "suspend")) {
            def->state = VIR_DOMAIN_SHUTOFF;
        } else if (STREQ(xmlstr, "poweroff")) {
            def->state = VIR_DOMAIN_SHUTOFF;
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected snapshot state: %s"), xmlstr);
        }
        VIR_FREE(xmlstr);

        xmlstr = virXPathString("string(./@current)", ctxt);
        def->current = xmlstr && STREQ("yes", xmlstr);
        VIR_FREE(xmlstr);

        if (!(snapshot = virDomainSnapshotAssignDef(snapshots, def)))
            goto cleanup;
        def = NULL;

        if (snapshot->def->current) {
            if (current) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("too many current snapshots"));
                goto cleanup;
            }
            current = snapshot;
        }
    }

    if (virDomainSnapshotUpdateRelations(snapshots) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("snapshots have inconsistent relations"));
        goto cleanup;
    }

    ret = snapshots;
    snapshots = NULL;

 cleanup:
    virDomainSnapshotObjListFree(snapshots);
    VIR_FREE(nodes);
    VIR_FREE(xmlstr);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    VIR_FREE(def);

    return ret;
}

virDomainSnapshotObjListPtr
prlsdkLoadSnapshots(virDomainObjPtr dom)
{
    virDomainSnapshotObjListPtr ret = NULL;
    PRL_HANDLE job;
    PRL_HANDLE result = PRL_INVALID_HANDLE;
    vzDomObjPtr privdom = dom->privateData;
    char *treexml = NULL;

    job = PrlVm_GetSnapshotsTreeEx(privdom->sdkdom, PGST_WITHOUT_SCREENSHOTS);
    if (PRL_FAILED(getJobResult(job, &result)))
        goto cleanup;

    if (!(treexml = prlsdkGetStringParamVar(PrlResult_GetParamAsString, result)))
        goto cleanup;

    ret = prlsdkParseSnapshotTree(treexml);
 cleanup:

    PrlHandle_Free(result);
    VIR_FREE(treexml);
    return ret;
}

int prlsdkCreateSnapshot(virDomainObjPtr dom, const char *description)
{
    vzDomObjPtr privdom = dom->privateData;
    PRL_HANDLE job;

    job = PrlVm_CreateSnapshot(privdom->sdkdom, "",
                               description ? : "");
    if (PRL_FAILED(waitJob(job)))
        return -1;

    return 0;
}

int prlsdkDeleteSnapshot(virDomainObjPtr dom, const char *uuid, bool children)
{
    vzDomObjPtr privdom = dom->privateData;
    PRL_HANDLE job;

    job = PrlVm_DeleteSnapshot(privdom->sdkdom, uuid, children);
    if (PRL_FAILED(waitJob(job)))
        return -1;

    return 0;
}

int prlsdkSwitchToSnapshot(virDomainObjPtr dom, const char *uuid, bool paused)
{
    vzDomObjPtr privdom = dom->privateData;
    PRL_HANDLE job;
    PRL_UINT32 flags = 0;

    if (paused)
        flags |= PSSF_SKIP_RESUME;

    job = PrlVm_SwitchToSnapshotEx(privdom->sdkdom, uuid, flags);
    if (PRL_FAILED(waitJob(job)))
        return -1;

    return 0;
}
4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542

/* high security is default choice for 2 reasons:
 * 1. as this is the highest set security we can't get
 * reject from server with high security settings
 * 2. this is on par with security level of driver
 * connection to dispatcher
 */

#define PRLSDK_MIGRATION_FLAGS (PSL_HIGH_SECURITY)

int prlsdkMigrate(virDomainObjPtr dom, virURIPtr uri,
                  const unsigned char *session_uuid,
                  const char *dname,
                  unsigned int flags)
{
    int ret = -1;
    vzDomObjPtr privdom = dom->privateData;
    PRL_HANDLE job = PRL_INVALID_HANDLE;
4543
    char uuidstr[VIR_UUID_STRING_BRACED_BUFLEN];
4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566
    PRL_UINT32 vzflags = PRLSDK_MIGRATION_FLAGS;

    if (flags & VIR_MIGRATE_PAUSED)
        vzflags |= PVMT_DONT_RESUME_VM;

    prlsdkUUIDFormat(session_uuid, uuidstr);
    job = PrlVm_MigrateWithRenameEx(privdom->sdkdom, uri->server,
                                    uri->port, uuidstr,
                                    dname == NULL ? "" : dname,
                                    "",
                                    vzflags,
                                    0,
                                    PRL_TRUE
                                    );

    if (PRL_FAILED(waitJob(job)))
        goto cleanup;

    ret = 0;

 cleanup:
    return ret;
}