libvirt.c 638.5 KB
Newer Older
D
Daniel P. Berrange 已提交
1
/*
2
 * libvirt.c: Main interfaces for the libvirt library to handle virtualization
D
Daniel Veillard 已提交
3 4
 *           domains from a process running in domain 0
 *
E
Eric Blake 已提交
5
 * Copyright (C) 2005-2006, 2008-2014 Red Hat, Inc.
D
Daniel Veillard 已提交
6
 *
O
Osier Yang 已提交
7 8 9 10 11 12 13 14 15 16 17
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
D
Daniel Veillard 已提交
20 21 22 23
 *
 * Daniel Veillard <veillard@redhat.com>
 */

24
#include <config.h>
D
Daniel Veillard 已提交
25

26
#include <stdio.h>
27
#include <stdlib.h>
28
#include <string.h>
29 30 31
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
E
Eric Blake 已提交
32
#include <sys/wait.h>
33
#include <time.h>
34

35 36
#include <libxml/parser.h>
#include <libxml/xpath.h>
37 38
#include "getpass.h"

39
#ifdef HAVE_WINSOCK2_H
40
# include <winsock2.h>
41
#endif
42

43
#ifdef WITH_CURL
44 45 46
# include <curl/curl.h>
#endif

47
#include "virerror.h"
48
#include "virlog.h"
49
#include "datatypes.h"
50
#include "driver.h"
51

52
#include "viruuid.h"
53
#include "viralloc.h"
54
#include "configmake.h"
55
#include "intprops.h"
56
#include "virconf.h"
57
#if WITH_GNUTLS
58 59 60
# if WITH_GNUTLS_GCRYPT
#  include <gcrypt.h>
# endif
61 62
# include "rpc/virnettlscontext.h"
#endif
63
#include "vircommand.h"
64
#include "virfile.h"
65
#include "virrandom.h"
M
Martin Kletzander 已提交
66
#include "viruri.h"
67
#include "virthread.h"
68
#include "virstring.h"
E
Eric Blake 已提交
69
#include "virutil.h"
70
#include "virtypedparam.h"
71

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
#ifdef WITH_TEST
# include "test/test_driver.h"
#endif
#ifdef WITH_REMOTE
# include "remote/remote_driver.h"
#endif
#ifdef WITH_OPENVZ
# include "openvz/openvz_driver.h"
#endif
#ifdef WITH_VMWARE
# include "vmware/vmware_driver.h"
#endif
#ifdef WITH_PHYP
# include "phyp/phyp_driver.h"
#endif
#ifdef WITH_ESX
# include "esx/esx_driver.h"
#endif
#ifdef WITH_HYPERV
# include "hyperv/hyperv_driver.h"
#endif
#ifdef WITH_XENAPI
# include "xenapi/xenapi_driver.h"
95
#endif
D
Dmitry Guryanov 已提交
96 97 98
#ifdef WITH_PARALLELS
# include "parallels/parallels_driver.h"
#endif
99

100 101
#define VIR_FROM_THIS VIR_FROM_NONE

D
Daniel Veillard 已提交
102 103 104
/*
 * TODO:
 * - use lock to protect against concurrent accesses ?
D
Daniel Veillard 已提交
105
 * - use reference counting to guarantee coherent pointer state ?
D
Daniel Veillard 已提交
106 107
 */

108
#define MAX_DRIVERS 20
109

110
static virDriverPtr virDriverTab[MAX_DRIVERS];
111
static int virDriverTabCount = 0;
112
static virNetworkDriverPtr virNetworkDriverTab[MAX_DRIVERS];
113
static int virNetworkDriverTabCount = 0;
D
Daniel Veillard 已提交
114 115
static virInterfaceDriverPtr virInterfaceDriverTab[MAX_DRIVERS];
static int virInterfaceDriverTabCount = 0;
116 117
static virStorageDriverPtr virStorageDriverTab[MAX_DRIVERS];
static int virStorageDriverTabCount = 0;
118 119
static virNodeDeviceDriverPtr virNodeDeviceDriverTab[MAX_DRIVERS];
static int virNodeDeviceDriverTabCount = 0;
120 121
static virSecretDriverPtr virSecretDriverTab[MAX_DRIVERS];
static int virSecretDriverTabCount = 0;
S
Stefan Berger 已提交
122 123
static virNWFilterDriverPtr virNWFilterDriverTab[MAX_DRIVERS];
static int virNWFilterDriverTabCount = 0;
A
Atsushi SAKAI 已提交
124
#ifdef WITH_LIBVIRTD
125 126
static virStateDriverPtr virStateDriverTab[MAX_DRIVERS];
static int virStateDriverTabCount = 0;
A
Atsushi SAKAI 已提交
127
#endif
128

129

130
#if defined(POLKIT_AUTH)
131 132 133
static int
virConnectAuthGainPolkit(const char *privilege)
{
E
Eric Blake 已提交
134 135 136
    virCommandPtr cmd;
    int status;
    int ret = -1;
137

138
    if (geteuid() == 0)
139 140
        return 0;

E
Eric Blake 已提交
141 142
    cmd = virCommandNewArgList(POLKIT_AUTH, "--obtain", privilege, NULL);
    if (virCommandRun(cmd, &status) < 0 ||
143
        status > 0)
E
Eric Blake 已提交
144
        goto cleanup;
145

E
Eric Blake 已提交
146 147 148 149
    ret = 0;
cleanup:
    virCommandFree(cmd);
    return ret;
150 151 152
}
#endif

153 154 155 156 157 158

static int
virConnectAuthCallbackDefault(virConnectCredentialPtr cred,
                              unsigned int ncred,
                              void *cbdata ATTRIBUTE_UNUSED)
{
159
    size_t i;
160

161
    for (i = 0; i < ncred; i++) {
162 163
        char buf[1024];
        char *bufptr = buf;
164
        size_t len;
165 166

        switch (cred[i].type) {
167 168 169 170
        case VIR_CRED_EXTERNAL: {
            if (STRNEQ(cred[i].challenge, "PolicyKit"))
                return -1;

171
#if defined(POLKIT_AUTH)
172
            if (virConnectAuthGainPolkit(cred[i].prompt) < 0)
173
                return -1;
174 175 176 177 178 179 180
#else
            /*
             * Ignore & carry on. Although we can't auth
             * directly, the user may have authenticated
             * themselves already outside context of libvirt
             */
#endif
181 182
            break;
        }
183

184 185 186 187
        case VIR_CRED_USERNAME:
        case VIR_CRED_AUTHNAME:
        case VIR_CRED_ECHOPROMPT:
        case VIR_CRED_REALM:
188
            if (printf("%s: ", cred[i].prompt) < 0)
189 190 191 192
                return -1;
            if (fflush(stdout) != 0)
                return -1;

193 194 195 196 197 198 199
            if (!fgets(buf, sizeof(buf), stdin)) {
                if (feof(stdin)) { /* Treat EOF as "" */
                    buf[0] = '\0';
                    break;
                }
                return -1;
            }
200 201 202
            len = strlen(buf);
            if (len != 0 && buf[len-1] == '\n')
                buf[len-1] = '\0';
203 204 205 206
            break;

        case VIR_CRED_PASSPHRASE:
        case VIR_CRED_NOECHOPROMPT:
207
            if (printf("%s: ", cred[i].prompt) < 0)
208 209 210 211
                return -1;
            if (fflush(stdout) != 0)
                return -1;

212 213 214 215
            bufptr = getpass("");
            if (!bufptr)
                return -1;
            break;
216 217 218

        default:
            return -1;
219 220
        }

D
Daniel P. Berrange 已提交
221
        if (cred[i].type != VIR_CRED_EXTERNAL) {
222 223 224
            if (VIR_STRDUP(cred[i].result,
                           STREQ(bufptr, "") && cred[i].defresult ?
                           cred[i].defresult : bufptr) < 0)
D
Daniel P. Berrange 已提交
225 226 227
                return -1;
            cred[i].resultlen = strlen(cred[i].result);
        }
228 229 230 231 232
    }

    return 0;
}

233

234 235 236 237 238 239 240 241 242 243
/* Don't typically want VIR_CRED_USERNAME. It enables you to authenticate
 * as one user, and act as another. It just results in annoying
 * prompts for the username twice & is very rarely what you want
 */
static int virConnectCredTypeDefault[] = {
    VIR_CRED_AUTHNAME,
    VIR_CRED_ECHOPROMPT,
    VIR_CRED_REALM,
    VIR_CRED_PASSPHRASE,
    VIR_CRED_NOECHOPROMPT,
244
    VIR_CRED_EXTERNAL,
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
};

static virConnectAuth virConnectAuthDefault = {
    virConnectCredTypeDefault,
    sizeof(virConnectCredTypeDefault)/sizeof(int),
    virConnectAuthCallbackDefault,
    NULL,
};

/*
 * virConnectAuthPtrDefault
 *
 * A default implementation of the authentication callbacks. This
 * implementation is suitable for command line based tools. It will
 * prompt for username, passwords, realm and one time keys as needed.
 * It will print on STDOUT, and read from STDIN. If this is not
 * suitable for the application's needs an alternative implementation
 * should be provided.
 */
virConnectAuthPtr virConnectAuthPtrDefault = &virConnectAuthDefault;

266 267
#if HAVE_WINSOCK2_H
static int
268
winsock_init(void)
269 270 271 272 273 274 275
{
    WORD winsock_version, err;
    WSADATA winsock_data;

    /* http://msdn2.microsoft.com/en-us/library/ms742213.aspx */
    winsock_version = MAKEWORD (2, 2);
    err = WSAStartup (winsock_version, &winsock_data);
J
Jim Meyering 已提交
276
    return err == 0 ? 0 : -1;
277 278 279
}
#endif

280

281
#ifdef WITH_GNUTLS_GCRYPT
282 283
static int
virTLSMutexInit(void **priv)
284
{
D
Daniel P. Berrange 已提交
285 286
    virMutexPtr lock = NULL;

287
    if (VIR_ALLOC_QUIET(lock) < 0)
D
Daniel P. Berrange 已提交
288 289 290 291 292 293 294 295 296 297 298
        return ENOMEM;

    if (virMutexInit(lock) < 0) {
        VIR_FREE(lock);
        return errno;
    }

    *priv = lock;
    return 0;
}

299 300 301

static int
virTLSMutexDestroy(void **priv)
D
Daniel P. Berrange 已提交
302 303 304 305 306 307 308
{
    virMutexPtr lock = *priv;
    virMutexDestroy(lock);
    VIR_FREE(lock);
    return 0;
}

309 310 311

static int
virTLSMutexLock(void **priv)
D
Daniel P. Berrange 已提交
312 313 314 315 316 317
{
    virMutexPtr lock = *priv;
    virMutexLock(lock);
    return 0;
}

318 319 320

static int
virTLSMutexUnlock(void **priv)
D
Daniel P. Berrange 已提交
321 322 323 324 325 326
{
    virMutexPtr lock = *priv;
    virMutexUnlock(lock);
    return 0;
}

327

D
Daniel P. Berrange 已提交
328
static struct gcry_thread_cbs virTLSThreadImpl = {
329
    /* GCRY_THREAD_OPTION_VERSION was added in gcrypt 1.4.2 */
330
# ifdef GCRY_THREAD_OPTION_VERSION
D
Daniel P. Berrange 已提交
331
    (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)),
332
# else
333
    GCRY_THREAD_OPTION_PTHREAD,
334
# endif
D
Daniel P. Berrange 已提交
335 336 337 338 339 340 341
    NULL,
    virTLSMutexInit,
    virTLSMutexDestroy,
    virTLSMutexLock,
    virTLSMutexUnlock,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};
342
#endif /* WITH_GNUTLS_GCRYPT */
D
Daniel P. Berrange 已提交
343

344

345 346
static bool virGlobalError = false;
static virOnceControl virGlobalOnce = VIR_ONCE_CONTROL_INITIALIZER;
347

348 349 350
static void
virGlobalInit(void)
{
351 352 353 354 355
    /* It would be nice if we could trace the use of this call, to
     * help diagnose in log files if a user calls something other than
     * virConnectOpen first.  But we can't rely on VIR_DEBUG working
     * until after initialization is complete, and since this is
     * one-shot, we never get here again.  */
356
    if (virThreadInitialize() < 0 ||
357
        virErrorInitialize() < 0)
358
        goto error;
359

360 361 362 363 364 365 366 367
#ifndef IN_VIRT_LOGIN_SHELL
    if (virIsSUID()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libvirt.so is not safe to use from setuid programs"));
        goto error;
    }
#endif

368
#ifdef WITH_GNUTLS_GCRYPT
369 370 371 372 373 374 375 376 377 378 379 380 381
    /*
     * This sequence of API calls it copied exactly from
     * gnutls 2.12.23 source lib/gcrypt/init.c, with
     * exception that GCRYCTL_ENABLE_QUICK_RANDOM, is
     * dropped
     */
    if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P) == 0) {
        gcry_control(GCRYCTL_SET_THREAD_CBS, &virTLSThreadImpl);
        gcry_check_version(NULL);

        gcry_control(GCRYCTL_DISABLE_SECMEM, NULL, 0);
        gcry_control(GCRYCTL_INITIALIZATION_FINISHED, NULL, 0);
    }
382
#endif
D
Daniel P. Berrange 已提交
383

384
    virLogSetFromEnv();
385

386
#ifdef WITH_GNUTLS
387
    virNetTLSInit();
388
#endif
389

390
#if WITH_CURL
391 392 393
    curl_global_init(CURL_GLOBAL_DEFAULT);
#endif

394
    VIR_DEBUG("register drivers");
395

396
#if HAVE_WINSOCK2_H
397
    if (winsock_init() == -1)
398
        goto error;
399 400
#endif

401
    if (!bindtextdomain(PACKAGE, LOCALEDIR))
402
        goto error;
403

404 405 406 407 408
    /*
     * Note we must avoid everything except 'remote' driver
     * for virt-login-shell usage
     */
#ifndef LIBVIRT_SETUID_RPC_CLIENT
409
    /*
410 411
     * Note that the order is important: the first ones have a higher
     * priority when calling virConnectOpen.
412
     */
413
# ifdef WITH_TEST
414 415
    if (testRegister() == -1)
        goto error;
416 417
# endif
# ifdef WITH_OPENVZ
418 419
    if (openvzRegister() == -1)
        goto error;
420 421
# endif
# ifdef WITH_VMWARE
422 423
    if (vmwareRegister() == -1)
        goto error;
424 425
# endif
# ifdef WITH_PHYP
426 427
    if (phypRegister() == -1)
        goto error;
428 429
# endif
# ifdef WITH_ESX
430 431
    if (esxRegister() == -1)
        goto error;
432 433
# endif
# ifdef WITH_HYPERV
434 435
    if (hypervRegister() == -1)
        goto error;
436 437
# endif
# ifdef WITH_XENAPI
438 439
    if (xenapiRegister() == -1)
        goto error;
440 441
# endif
# ifdef WITH_PARALLELS
442 443
    if (parallelsRegister() == -1)
        goto error;
444
# endif
D
Dmitry Guryanov 已提交
445
#endif
446
#ifdef WITH_REMOTE
447
    if (remoteRegister() == -1)
448
        goto error;
449
#endif
D
Daniel P. Berrange 已提交
450

451 452 453 454 455 456
    return;

error:
    virGlobalError = true;
}

457

458 459 460 461 462
/**
 * virInitialize:
 *
 * Initialize the library.
 *
463 464 465 466 467 468
 * This method is invoked automatically by any of the virConnectOpen() API
 * calls, and by virGetVersion(). Since release 1.0.0, there is no need to
 * call this method even in a multithreaded application, since
 * initialization is performed in a thread safe manner; but applications
 * using an older version of the library should manually call this before
 * setting up competing threads that attempt virConnectOpen in parallel.
469
 *
470 471 472 473 474
 * The only other time it would be necessary to call virInitialize is if the
 * application did not invoke virConnectOpen as its first API call, such
 * as when calling virEventRegisterImpl() before setting up connections,
 * or when using virSetErrorFunc() to alter error reporting of the first
 * connection attempt.
475 476 477 478 479 480 481 482 483 484 485
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
virInitialize(void)
{
    if (virOnce(&virGlobalOnce, virGlobalInit) < 0)
        return -1;

    if (virGlobalError)
        return -1;
486
    return 0;
487 488
}

489

490 491
#ifdef WIN32
BOOL WINAPI
492
DllMain(HINSTANCE instance, DWORD reason, LPVOID ignore);
493 494

BOOL WINAPI
495 496 497
DllMain(HINSTANCE instance ATTRIBUTE_UNUSED,
        DWORD reason,
        LPVOID ignore ATTRIBUTE_UNUSED)
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
{
    switch (reason) {
    case DLL_PROCESS_ATTACH:
        virInitialize();
        break;

    case DLL_THREAD_ATTACH:
        /* Nothing todo in libvirt yet */
        break;

    case DLL_THREAD_DETACH:
        /* Release per-thread local data */
        virThreadOnExit();
        break;

    case DLL_PROCESS_DETACH:
        /* Don't bother releasing per-thread data
           since (hopefully) windows cleans up
           everything on process exit */
        break;
    }

    return TRUE;
}
#endif
523

524

525
#define virLibConnError(code, ...)                                \
526
    virReportErrorHelper(VIR_FROM_NONE, code, __FILE__,           \
527 528
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibDomainError(code, ...)                              \
529
    virReportErrorHelper(VIR_FROM_DOM, code, __FILE__,            \
530 531
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibNetworkError(code, ...)                             \
532
    virReportErrorHelper(VIR_FROM_NETWORK, code, __FILE__,        \
533 534
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibStoragePoolError(code, ...)                         \
535
    virReportErrorHelper(VIR_FROM_STORAGE, code, __FILE__,        \
536 537
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibStorageVolError(code, ...)                          \
538
    virReportErrorHelper(VIR_FROM_STORAGE, code, __FILE__,        \
539 540
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibInterfaceError(code, ...)                           \
541
    virReportErrorHelper(VIR_FROM_INTERFACE, code, __FILE__,      \
542 543
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibNodeDeviceError(code, ...)                          \
544
    virReportErrorHelper(VIR_FROM_NODEDEV, code, __FILE__,        \
545 546
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibSecretError(code, ...)                              \
547
    virReportErrorHelper(VIR_FROM_SECRET, code, __FILE__,         \
548 549
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibStreamError(code, ...)                              \
550
    virReportErrorHelper(VIR_FROM_STREAMS, code, __FILE__,        \
551 552
                         __FUNCTION__, __LINE__, __VA_ARGS__)
#define virLibNWFilterError(code, ...)                            \
553
    virReportErrorHelper(VIR_FROM_NWFILTER, code, __FILE__,       \
554
                         __FUNCTION__, __LINE__, __VA_ARGS__)
555 556
#define virLibDomainSnapshotError(code, ...)                       \
    virReportErrorHelper(VIR_FROM_DOMAIN_SNAPSHOT, code, __FILE__, \
557
                         __FUNCTION__, __LINE__, __VA_ARGS__)
558

C
Chris Lalancette 已提交
559

560 561 562 563 564 565 566 567 568 569 570
/**
 * virRegisterNetworkDriver:
 * @driver: pointer to a network driver block
 *
 * Register a network virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterNetworkDriver(virNetworkDriverPtr driver)
{
571
    virCheckNonNullArgReturn(driver, -1);
572 573

    if (virNetworkDriverTabCount >= MAX_DRIVERS) {
574 575 576
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
577
        return -1;
578 579
    }

580
    VIR_DEBUG("registering %s as network driver %d",
581 582
           driver->name, virNetworkDriverTabCount);

583 584
    virNetworkDriverTab[virNetworkDriverTabCount] = driver;
    return virNetworkDriverTabCount++;
585 586
}

587

D
Daniel Veillard 已提交
588 589
/**
 * virRegisterInterfaceDriver:
L
Laine Stump 已提交
590
 * @driver: pointer to an interface driver block
D
Daniel Veillard 已提交
591
 *
L
Laine Stump 已提交
592
 * Register an interface virtualization driver
D
Daniel Veillard 已提交
593 594 595 596 597 598
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterInterfaceDriver(virInterfaceDriverPtr driver)
{
599
    virCheckNonNullArgReturn(driver, -1);
D
Daniel Veillard 已提交
600 601

    if (virInterfaceDriverTabCount >= MAX_DRIVERS) {
602 603 604
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
605
        return -1;
D
Daniel Veillard 已提交
606 607
    }

608
    VIR_DEBUG("registering %s as interface driver %d",
D
Daniel Veillard 已提交
609 610 611 612 613 614
           driver->name, virInterfaceDriverTabCount);

    virInterfaceDriverTab[virInterfaceDriverTabCount] = driver;
    return virInterfaceDriverTabCount++;
}

615

616 617 618 619 620 621 622 623 624 625 626
/**
 * virRegisterStorageDriver:
 * @driver: pointer to a storage driver block
 *
 * Register a storage virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterStorageDriver(virStorageDriverPtr driver)
{
627
    virCheckNonNullArgReturn(driver, -1);
628 629

    if (virStorageDriverTabCount >= MAX_DRIVERS) {
630 631 632
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
633
        return -1;
634 635
    }

636
    VIR_DEBUG("registering %s as storage driver %d",
637 638
           driver->name, virStorageDriverTabCount);

639 640 641 642
    virStorageDriverTab[virStorageDriverTabCount] = driver;
    return virStorageDriverTabCount++;
}

643

644
/**
645
 * virRegisterNodeDeviceDriver:
646 647 648 649 650 651 652
 * @driver: pointer to a device monitor block
 *
 * Register a device monitor
 *
 * Returns the driver priority or -1 in case of error.
 */
int
653
virRegisterNodeDeviceDriver(virNodeDeviceDriverPtr driver)
654
{
655
    virCheckNonNullArgReturn(driver, -1);
656

657
    if (virNodeDeviceDriverTabCount >= MAX_DRIVERS) {
658 659 660
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
661
        return -1;
662 663
    }

664
    VIR_DEBUG("registering %s as device driver %d",
665
           driver->name, virNodeDeviceDriverTabCount);
666

667 668
    virNodeDeviceDriverTab[virNodeDeviceDriverTabCount] = driver;
    return virNodeDeviceDriverTabCount++;
669 670
}

671

672 673 674 675 676 677 678 679 680 681 682
/**
 * virRegisterSecretDriver:
 * @driver: pointer to a secret driver block
 *
 * Register a secret driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterSecretDriver(virSecretDriverPtr driver)
{
683
    virCheckNonNullArgReturn(driver, -1);
684 685

    if (virSecretDriverTabCount >= MAX_DRIVERS) {
686 687 688
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
689
        return -1;
690 691
    }

692
    VIR_DEBUG("registering %s as secret driver %d",
693 694 695 696 697 698
           driver->name, virSecretDriverTabCount);

    virSecretDriverTab[virSecretDriverTabCount] = driver;
    return virSecretDriverTabCount++;
}

699

S
Stefan Berger 已提交
700 701 702 703 704 705 706 707 708 709 710
/**
 * virRegisterNWFilterDriver:
 * @driver: pointer to a network filter driver block
 *
 * Register a network filter virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterNWFilterDriver(virNWFilterDriverPtr driver)
{
711
    virCheckNonNullArgReturn(driver, -1);
S
Stefan Berger 已提交
712 713

    if (virNWFilterDriverTabCount >= MAX_DRIVERS) {
714 715 716
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
S
Stefan Berger 已提交
717 718 719
        return -1;
    }

720
    VIR_DEBUG("registering %s as network filter driver %d",
S
Stefan Berger 已提交
721 722 723 724 725 726 727
           driver->name, virNWFilterDriverTabCount);

    virNWFilterDriverTab[virNWFilterDriverTabCount] = driver;
    return virNWFilterDriverTabCount++;
}


728 729 730 731 732 733 734 735 736 737 738
/**
 * virRegisterDriver:
 * @driver: pointer to a driver block
 *
 * Register a virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterDriver(virDriverPtr driver)
{
739
    VIR_DEBUG("driver=%p name=%s", driver, driver ? NULLSTR(driver->name) : "(null)");
740

741
    virCheckNonNullArgReturn(driver, -1);
742 743

    if (virDriverTabCount >= MAX_DRIVERS) {
744 745 746
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
747
        return -1;
748 749
    }

750
    VIR_DEBUG("registering %s as driver %d",
751 752
           driver->name, virDriverTabCount);

753 754
    virDriverTab[virDriverTabCount] = driver;
    return virDriverTabCount++;
755 756
}

757

A
Atsushi SAKAI 已提交
758
#ifdef WITH_LIBVIRTD
759 760 761 762 763 764 765 766 767 768 769
/**
 * virRegisterStateDriver:
 * @driver: pointer to a driver block
 *
 * Register a virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterStateDriver(virStateDriverPtr driver)
{
770
    virCheckNonNullArgReturn(driver, -1);
771 772

    if (virStateDriverTabCount >= MAX_DRIVERS) {
773 774 775
        virLibConnError(VIR_ERR_INTERNAL_ERROR,
                        _("Too many drivers, cannot register %s"),
                        driver->name);
776
        return -1;
777 778 779 780 781 782
    }

    virStateDriverTab[virStateDriverTabCount] = driver;
    return virStateDriverTabCount++;
}

783

784 785
/**
 * virStateInitialize:
786
 * @privileged: set to true if running with root privilege, false otherwise
787 788
 * @callback: callback to invoke to inhibit shutdown of the daemon
 * @opaque: data to pass to @callback
789
 *
790 791 792 793 794
 * Initialize all virtualization drivers. Accomplished in two phases,
 * the first being state and structure initialization followed by any
 * auto start supported by the driver.  This is done to ensure dependencies
 * that some drivers may have on another driver having been initialized
 * will exist, such as the storage driver's need to use the secret driver.
795
 *
796
 * Returns 0 if all succeed, -1 upon any failure.
797
 */
798 799 800 801
int
virStateInitialize(bool privileged,
                   virStateInhibitCallback callback,
                   void *opaque)
802
{
803
    size_t i;
804 805 806 807

    if (virInitialize() < 0)
        return -1;

808
    for (i = 0; i < virStateDriverTabCount; i++) {
809
        if (virStateDriverTab[i]->stateInitialize) {
810
            VIR_DEBUG("Running global init for %s state driver",
811
                      virStateDriverTab[i]->name);
812 813 814
            if (virStateDriverTab[i]->stateInitialize(privileged,
                                                      callback,
                                                      opaque) < 0) {
815 816 817 818
                virErrorPtr err = virGetLastError();
                VIR_ERROR(_("Initialization of %s state driver failed: %s"),
                          virStateDriverTab[i]->name,
                          err && err->message ? err->message : _("Unknown problem"));
819 820
                return -1;
            }
821
        }
822
    }
823 824 825 826 827 828 829 830

    for (i = 0; i < virStateDriverTabCount; i++) {
        if (virStateDriverTab[i]->stateAutoStart) {
            VIR_DEBUG("Running global auto start for %s state driver",
                      virStateDriverTab[i]->name);
            virStateDriverTab[i]->stateAutoStart();
        }
    }
831
    return 0;
832 833
}

834

835 836 837 838 839
/**
 * virStateCleanup:
 *
 * Run each virtualization driver's cleanup method.
 *
840
 * Returns 0 if all succeed, -1 upon any failure.
841
 */
842 843 844
int
virStateCleanup(void)
{
845 846
    size_t i;
    int ret = 0;
847

848
    for (i = 0; i < virStateDriverTabCount; i++) {
849 850
        if (virStateDriverTab[i]->stateCleanup &&
            virStateDriverTab[i]->stateCleanup() < 0)
851 852 853 854 855
            ret = -1;
    }
    return ret;
}

856

857 858 859 860 861
/**
 * virStateReload:
 *
 * Run each virtualization driver's reload method.
 *
862
 * Returns 0 if all succeed, -1 upon any failure.
863
 */
864 865 866
int
virStateReload(void)
{
867 868
    size_t i;
    int ret = 0;
869

870
    for (i = 0; i < virStateDriverTabCount; i++) {
871 872
        if (virStateDriverTab[i]->stateReload &&
            virStateDriverTab[i]->stateReload() < 0)
873 874 875 876 877
            ret = -1;
    }
    return ret;
}

878

879 880 881 882 883 884 885
/**
 * virStateStop:
 *
 * Run each virtualization driver's "stop" method.
 *
 * Returns 0 if successful, -1 on failure
 */
886 887 888
int
virStateStop(void)
{
889 890
    size_t i;
    int ret = 0;
891

892
    for (i = 0; i < virStateDriverTabCount; i++) {
893 894
        if (virStateDriverTab[i]->stateStop &&
            virStateDriverTab[i]->stateStop())
895 896 897 898
            ret = 1;
    }
    return ret;
}
899
#endif /* WITH_LIBVIRTD */
900 901


902 903 904
/**
 * virGetVersion:
 * @libVer: return value for the library version (OUT)
905 906 907 908 909 910 911 912 913 914
 * @type: ignored; pass NULL
 * @typeVer: pass NULL; for historical purposes duplicates @libVer if
 * non-NULL
 *
 * Provides version information. @libVer is the version of the
 * library and will always be set unless an error occurs, in which case
 * an error code will be returned. @typeVer exists for historical
 * compatibility; if it is not NULL it will duplicate @libVer (it was
 * originally intended to return hypervisor information based on @type,
 * but due to the design of remote clients this is not reliable). To
915
 * get the version of the running hypervisor use the virConnectGetVersion()
916
 * function instead. To get the libvirt library version used by a
917 918 919
 * connection use the virConnectGetLibVersion() instead.
 *
 * This function includes a call to virInitialize() when necessary.
920 921 922 923 924
 *
 * Returns -1 in case of failure, 0 otherwise, and values for @libVer and
 *       @typeVer have the format major * 1,000,000 + minor * 1,000 + release.
 */
int
925
virGetVersion(unsigned long *libVer, const char *type ATTRIBUTE_UNUSED,
926 927
              unsigned long *typeVer)
{
928 929
    if (virInitialize() < 0)
        goto error;
930
    VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer, type, typeVer);
931

932
    virResetLastError();
933
    if (libVer == NULL)
934
        goto error;
935 936
    *libVer = LIBVIR_VERSION_NUMBER;

937
    if (typeVer != NULL)
938 939
        *typeVer = LIBVIR_VERSION_NUMBER;

940
    return 0;
941 942 943 944

error:
    virDispatchError(NULL);
    return -1;
945 946
}

947

948
static char *
949
virConnectGetConfigFilePath(void)
950 951 952 953 954
{
    char *path;
    if (geteuid() == 0) {
        if (virAsprintf(&path, "%s/libvirt/libvirt.conf",
                        SYSCONFDIR) < 0)
955
            return NULL;
956
    } else {
957
        char *userdir = virGetUserConfigDirectory();
958
        if (!userdir)
959
            return NULL;
960

961
        if (virAsprintf(&path, "%s/libvirt.conf",
962 963
                        userdir) < 0) {
            VIR_FREE(userdir);
964
            return NULL;
965 966
        }
        VIR_FREE(userdir);
967 968 969 970 971
    }

    return path;
}

972

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
static int
virConnectGetConfigFile(virConfPtr *conf)
{
    char *filename = NULL;
    int ret = -1;

    *conf = NULL;

    if (!(filename = virConnectGetConfigFilePath()))
        goto cleanup;

    if (!virFileExists(filename)) {
        ret = 0;
        goto cleanup;
    }

    VIR_DEBUG("Loading config file '%s'", filename);
    if (!(*conf = virConfReadFile(filename, 0)))
        goto cleanup;

    ret = 0;

cleanup:
    VIR_FREE(filename);
    return ret;
}

1000 1001
#define URI_ALIAS_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"

1002

1003
static int
1004 1005
virConnectOpenFindURIAliasMatch(virConfValuePtr value, const char *alias,
                                char **uri)
1006 1007
{
    virConfValuePtr entry;
W
Wen Ruo Lv 已提交
1008 1009
    size_t alias_len;

1010 1011 1012 1013 1014 1015 1016
    if (value->type != VIR_CONF_LIST) {
        virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("Expected a list for 'uri_aliases' config parameter"));
        return -1;
    }

    entry = value->list;
W
Wen Ruo Lv 已提交
1017
    alias_len = strlen(alias);
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    while (entry) {
        char *offset;
        size_t safe;

        if (entry->type != VIR_CONF_STRING) {
            virLibConnError(VIR_ERR_CONF_SYNTAX, "%s",
                            _("Expected a string for 'uri_aliases' config parameter list entry"));
            return -1;
        }

        if (!(offset = strchr(entry->str, '='))) {
            virLibConnError(VIR_ERR_CONF_SYNTAX,
                            _("Malformed 'uri_aliases' config entry '%s', expected 'alias=uri://host/path'"),
                            entry->str);
            return -1;
        }

        safe  = strspn(entry->str, URI_ALIAS_CHARS);
        if (safe < (offset - entry->str)) {
            virLibConnError(VIR_ERR_CONF_SYNTAX,
Y
Yuri Chornoivan 已提交
1038
                            _("Malformed 'uri_aliases' config entry '%s', aliases may only contain 'a-Z, 0-9, _, -'"),
1039 1040 1041 1042
                            entry->str);
            return -1;
        }

W
Wen Ruo Lv 已提交
1043 1044
        if (alias_len == (offset - entry->str) &&
            STREQLEN(entry->str, alias, alias_len)) {
1045 1046
            VIR_DEBUG("Resolved alias '%s' to '%s'",
                      alias, offset+1);
1047
            return VIR_STRDUP(*uri, offset+1);
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
        }

        entry = entry->next;
    }

    VIR_DEBUG("No alias found for '%s', passing through to drivers",
              alias);
    return 0;
}

1058

1059
static int
1060 1061
virConnectOpenResolveURIAlias(virConfPtr conf,
                              const char *alias, char **uri)
1062 1063 1064 1065 1066 1067
{
    int ret = -1;
    virConfValuePtr value = NULL;

    *uri = NULL;

1068
    if ((value = virConfGetValue(conf, "uri_aliases")))
1069 1070 1071 1072
        ret = virConnectOpenFindURIAliasMatch(value, alias, uri);
    else
        ret = 0;

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    return ret;
}


static int
virConnectGetDefaultURI(virConfPtr conf,
                        const char **name)
{
    int ret = -1;
    virConfValuePtr value = NULL;
1083
    const char *defname = virGetEnvBlockSUID("LIBVIRT_DEFAULT_URI");
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    if (defname && *defname) {
        VIR_DEBUG("Using LIBVIRT_DEFAULT_URI '%s'", defname);
        *name = defname;
    } else if ((value = virConfGetValue(conf, "uri_default"))) {
        if (value->type != VIR_CONF_STRING) {
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("Expected a string for 'uri_default' config parameter"));
            goto cleanup;
        }
        VIR_DEBUG("Using config file uri '%s'", value->str);
        *name = value->str;
    }

    ret = 0;
1098 1099 1100 1101
cleanup:
    return ret;
}

1102

1103
static virConnectPtr
1104 1105 1106
do_open(const char *name,
        virConnectAuthPtr auth,
        unsigned int flags)
1107
{
1108 1109
    size_t i;
    int res;
1110
    virConnectPtr ret;
1111
    virConfPtr conf = NULL;
1112 1113 1114 1115

    ret = virGetConnect();
    if (ret == NULL)
        return NULL;
1116

1117 1118 1119 1120 1121 1122
    if (virConnectGetConfigFile(&conf) < 0)
        goto failed;

    if (name && name[0] == '\0')
        name = NULL;

1123 1124 1125 1126 1127 1128
    if (!name && virIsSUID()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("An explicit URI must be provided when setuid"));
        goto failed;
    }

1129
    /*
E
Eric Blake 已提交
1130 1131 1132
     * If no URI is passed, then check for an environment string if not
     * available probe the compiled in drivers to find a default hypervisor
     * if detectable.
1133
     */
1134 1135 1136
    if (!name &&
        virConnectGetDefaultURI(conf, &name) < 0)
        goto failed;
1137

1138
    if (name) {
1139
        char *alias = NULL;
1140 1141 1142 1143 1144 1145 1146
        /* Convert xen -> xen:/// for back compat */
        if (STRCASEEQ(name, "xen"))
            name = "xen:///";

        /* Convert xen:// -> xen:/// because xmlParseURI cannot parse the
         * former.  This allows URIs such as xen://localhost to work.
         */
1147
        if (STREQ(name, "xen://"))
1148 1149
            name = "xen:///";

1150
        if (!(flags & VIR_CONNECT_NO_ALIASES) &&
1151
            virConnectOpenResolveURIAlias(conf, name, &alias) < 0)
1152 1153
            goto failed;

1154
        if (!(ret->uri = virURIParse(alias ? alias : name))) {
1155
            VIR_FREE(alias);
1156 1157
            goto failed;
        }
1158

1159
        VIR_DEBUG("name \"%s\" to URI components:\n"
1160 1161 1162 1163 1164 1165
                  "  scheme %s\n"
                  "  server %s\n"
                  "  user %s\n"
                  "  port %d\n"
                  "  path %s\n",
                  alias ? alias : name,
1166
                  NULLSTR(ret->uri->scheme), NULLSTR(ret->uri->server),
1167 1168 1169 1170
                  NULLSTR(ret->uri->user), ret->uri->port,
                  NULLSTR(ret->uri->path));

        VIR_FREE(alias);
1171
    } else {
1172
        VIR_DEBUG("no name, allowing driver auto-select");
1173 1174
    }

1175 1176 1177
    /* Cleansing flags */
    ret->flags = flags & VIR_CONNECT_RO;

1178
    for (i = 0; i < virDriverTabCount; i++) {
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        /* We're going to probe the remote driver next. So we have already
         * probed all other client-side-only driver before, but none of them
         * accepted the URI.
         * If the scheme corresponds to a known but disabled client-side-only
         * driver then report a useful error, instead of a cryptic one about
         * not being able to connect to libvirtd or not being able to find
         * certificates. */
        if (virDriverTab[i]->no == VIR_DRV_REMOTE &&
            ret->uri != NULL && ret->uri->scheme != NULL &&
            (
#ifndef WITH_PHYP
             STRCASEEQ(ret->uri->scheme, "phyp") ||
#endif
#ifndef WITH_ESX
1193
             STRCASEEQ(ret->uri->scheme, "vpx") ||
1194 1195
             STRCASEEQ(ret->uri->scheme, "esx") ||
             STRCASEEQ(ret->uri->scheme, "gsx") ||
M
Matthias Bolte 已提交
1196 1197 1198
#endif
#ifndef WITH_HYPERV
             STRCASEEQ(ret->uri->scheme, "hyperv") ||
1199 1200 1201
#endif
#ifndef WITH_XENAPI
             STRCASEEQ(ret->uri->scheme, "xenapi") ||
D
Dmitry Guryanov 已提交
1202 1203 1204
#endif
#ifndef WITH_PARALLELS
             STRCASEEQ(ret->uri->scheme, "parallels") ||
1205 1206
#endif
             false)) {
1207
            virReportErrorHelper(VIR_FROM_NONE, VIR_ERR_CONFIG_UNSUPPORTED,
1208 1209 1210 1211 1212 1213
                                 __FILE__, __FUNCTION__, __LINE__,
                                 _("libvirt was built without the '%s' driver"),
                                 ret->uri->scheme);
            goto failed;
        }

1214
        VIR_DEBUG("trying driver %zu (%s) ...", i, virDriverTab[i]->name);
1215
        ret->driver = virDriverTab[i];
1216
        res = virDriverTab[i]->connectOpen(ret, auth, flags);
1217
        VIR_DEBUG("driver %zu %s returned %s",
O
Osier Yang 已提交
1218 1219 1220 1221 1222 1223
                  i, virDriverTab[i]->name,
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
1224
            break;
O
Osier Yang 已提交
1225
        } else if (res == VIR_DRV_OPEN_ERROR) {
1226
            ret->driver = NULL;
O
Osier Yang 已提交
1227
            goto failed;
1228 1229
        } else {
            ret->driver = NULL;
1230
        }
1231 1232
    }

1233
    if (!ret->driver) {
1234
        /* If we reach here, then all drivers declined the connection. */
1235
        virLibConnError(VIR_ERR_NO_CONNECT,
1236
                        "%s",
1237
                        NULLSTR(name));
1238
        goto failed;
1239 1240
    }

1241
    for (i = 0; i < virNetworkDriverTabCount; i++) {
1242
        res = virNetworkDriverTab[i]->networkOpen(ret, auth, flags);
1243
        VIR_DEBUG("network driver %zu %s returned %s",
O
Osier Yang 已提交
1244 1245 1246 1247 1248 1249
                  i, virNetworkDriverTab[i]->name,
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
1250 1251
            ret->networkDriver = virNetworkDriverTab[i];
            break;
O
Osier Yang 已提交
1252 1253
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1254
        }
1255
    }
1256

D
Daniel Veillard 已提交
1257
    for (i = 0; i < virInterfaceDriverTabCount; i++) {
1258
        res = virInterfaceDriverTab[i]->interfaceOpen(ret, auth, flags);
1259
        VIR_DEBUG("interface driver %zu %s returned %s",
O
Osier Yang 已提交
1260 1261 1262 1263 1264 1265
                  i, virInterfaceDriverTab[i]->name,
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
D
Daniel Veillard 已提交
1266 1267
            ret->interfaceDriver = virInterfaceDriverTab[i];
            break;
O
Osier Yang 已提交
1268 1269
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
D
Daniel Veillard 已提交
1270 1271
        }
    }
1272 1273 1274

    /* Secondary driver for storage. Optional */
    for (i = 0; i < virStorageDriverTabCount; i++) {
1275
        res = virStorageDriverTab[i]->storageOpen(ret, auth, flags);
1276
        VIR_DEBUG("storage driver %zu %s returned %s",
O
Osier Yang 已提交
1277 1278 1279 1280 1281 1282
                  i, virStorageDriverTab[i]->name,
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
1283 1284
            ret->storageDriver = virStorageDriverTab[i];
            break;
O
Osier Yang 已提交
1285 1286
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1287 1288 1289
        }
    }

1290
    /* Node driver (optional) */
1291
    for (i = 0; i < virNodeDeviceDriverTabCount; i++) {
1292
        res = virNodeDeviceDriverTab[i]->nodeDeviceOpen(ret, auth, flags);
1293
        VIR_DEBUG("node driver %zu %s returned %s",
1294
                  i, virNodeDeviceDriverTab[i]->name,
O
Osier Yang 已提交
1295 1296 1297 1298 1299
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
1300
            ret->nodeDeviceDriver = virNodeDeviceDriverTab[i];
1301
            break;
O
Osier Yang 已提交
1302 1303
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1304 1305 1306
        }
    }

1307 1308
    /* Secret manipulation driver. Optional */
    for (i = 0; i < virSecretDriverTabCount; i++) {
1309
        res = virSecretDriverTab[i]->secretOpen(ret, auth, flags);
1310
        VIR_DEBUG("secret driver %zu %s returned %s",
O
Osier Yang 已提交
1311 1312 1313 1314 1315 1316
                  i, virSecretDriverTab[i]->name,
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
1317 1318
            ret->secretDriver = virSecretDriverTab[i];
            break;
O
Osier Yang 已提交
1319 1320
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1321 1322 1323
        }
    }

S
Stefan Berger 已提交
1324 1325
    /* Network filter driver. Optional */
    for (i = 0; i < virNWFilterDriverTabCount; i++) {
1326
        res = virNWFilterDriverTab[i]->nwfilterOpen(ret, auth, flags);
1327
        VIR_DEBUG("nwfilter driver %zu %s returned %s",
O
Osier Yang 已提交
1328 1329 1330 1331 1332 1333
                  i, virNWFilterDriverTab[i]->name,
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
S
Stefan Berger 已提交
1334 1335
            ret->nwfilterDriver = virNWFilterDriverTab[i];
            break;
O
Osier Yang 已提交
1336 1337
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
S
Stefan Berger 已提交
1338 1339 1340
        }
    }

1341 1342
    virConfFree(conf);

1343
    return ret;
1344 1345

failed:
1346
    virConfFree(conf);
1347
    virObjectUnref(ret);
1348

1349
    return NULL;
1350 1351
}

1352

1353 1354
/**
 * virConnectOpen:
1355
 * @name: (optional) URI of the hypervisor
1356
 *
1357
 * This function should be called first to get a connection to the
1358 1359
 * Hypervisor and xen store
 *
1360 1361 1362 1363 1364
 * If @name is NULL, if the LIBVIRT_DEFAULT_URI environment variable is set,
 * then it will be used. Otherwise if the client configuration file
 * has the "uri_default" parameter set, then it will be used. Finally
 * probing will be done to determine a suitable default driver to activate.
 * This involves trying each hypervisor in turn until one successfully opens.
1365 1366 1367 1368 1369 1370
 *
 * If connecting to an unprivileged hypervisor driver which requires
 * the libvirtd daemon to be active, it will automatically be launched
 * if not already running. This can be prevented by setting the
 * environment variable LIBVIRT_AUTOSTART=0
 *
1371
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1372 1373
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1374 1375
 */
virConnectPtr
1376
virConnectOpen(const char *name)
1377
{
1378
    virConnectPtr ret = NULL;
1379 1380 1381

    if (virInitialize() < 0)
        goto error;
1382

1383
    VIR_DEBUG("name=%s", NULLSTR(name));
1384
    virResetLastError();
1385
    ret = do_open(name, NULL, 0);
1386 1387 1388 1389 1390 1391 1392
    if (!ret)
        goto error;
    return ret;

error:
    virDispatchError(NULL);
    return NULL;
1393 1394
}

1395

1396
/**
1397
 * virConnectOpenReadOnly:
1398
 * @name: (optional) URI of the hypervisor
1399
 *
1400
 * This function should be called first to get a restricted connection to the
D
Daniel Veillard 已提交
1401
 * library functionalities. The set of APIs usable are then restricted
1402
 * on the available methods to control the domains.
1403
 *
1404 1405 1406
 * See virConnectOpen for notes about environment variables which can
 * have an effect on opening drivers
 *
1407
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1408 1409
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1410
 */
1411
virConnectPtr
1412 1413
virConnectOpenReadOnly(const char *name)
{
1414
    virConnectPtr ret = NULL;
1415 1416 1417

    if (virInitialize() < 0)
        goto error;
1418

1419
    VIR_DEBUG("name=%s", NULLSTR(name));
1420
    virResetLastError();
1421
    ret = do_open(name, NULL, VIR_CONNECT_RO);
1422 1423 1424 1425 1426 1427 1428
    if (!ret)
        goto error;
    return ret;

error:
    virDispatchError(NULL);
    return NULL;
1429 1430
}

1431

1432 1433
/**
 * virConnectOpenAuth:
1434
 * @name: (optional) URI of the hypervisor
1435
 * @auth: Authenticate callback parameters
1436
 * @flags: bitwise-OR of virConnectFlags
1437
 *
1438
 * This function should be called first to get a connection to the
1439
 * Hypervisor. If necessary, authentication will be performed fetching
1440 1441
 * credentials via the callback
 *
1442 1443 1444
 * See virConnectOpen for notes about environment variables which can
 * have an effect on opening drivers
 *
1445
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1446 1447
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1448 1449 1450 1451
 */
virConnectPtr
virConnectOpenAuth(const char *name,
                   virConnectAuthPtr auth,
1452
                   unsigned int flags)
1453
{
1454
    virConnectPtr ret = NULL;
1455 1456 1457

    if (virInitialize() < 0)
        goto error;
1458

1459
    VIR_DEBUG("name=%s, auth=%p, flags=%x", NULLSTR(name), auth, flags);
1460
    virResetLastError();
1461
    ret = do_open(name, auth, flags);
1462 1463 1464 1465 1466 1467 1468
    if (!ret)
        goto error;
    return ret;

error:
    virDispatchError(NULL);
    return NULL;
D
Daniel Veillard 已提交
1469 1470
}

1471

D
Daniel Veillard 已提交
1472
/**
1473
 * virConnectClose:
D
Daniel Veillard 已提交
1474 1475 1476 1477 1478 1479 1480
 * @conn: pointer to the hypervisor connection
 *
 * This function closes the connection to the Hypervisor. This should
 * not be called if further interaction with the Hypervisor are needed
 * especially if there is running domain which need further monitoring by
 * the application.
 *
1481 1482 1483 1484 1485 1486 1487 1488
 * Connections are reference counted; the count is explicitly
 * increased by the initial open (virConnectOpen, virConnectOpenAuth,
 * and the like) as well as virConnectRef; it is also temporarily
 * increased by other API that depend on the connection remaining
 * alive.  The open and every virConnectRef call should have a
 * matching virConnectClose, and all other references will be released
 * after the corresponding operation completes.
 *
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
 * Returns a positive number if at least 1 reference remains on
 * success. The returned value should not be assumed to be the total
 * reference count. A return of 0 implies no references remain and
 * the connection is closed and memory has been freed. A return of -1
 * implies a failure.
 *
 * It is possible for the last virConnectClose to return a positive
 * value if some other object still has a temporary reference to the
 * connection, but the application should not try to further use a
 * connection after the virConnectClose that matches the initial open.
D
Daniel Veillard 已提交
1499 1500
 */
int
1501 1502
virConnectClose(virConnectPtr conn)
{
1503
    VIR_DEBUG("conn=%p", conn);
1504

1505 1506
    virResetLastError();

1507
    virCheckConnectReturn(conn, -1);
1508

1509 1510 1511
    if (!virObjectUnref(conn))
        return 0;
    return 1;
D
Daniel Veillard 已提交
1512 1513
}

1514

1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
/**
 * virConnectRef:
 * @conn: the connection to hold a reference on
 *
 * Increment the reference count on the connection. For each
 * additional call to this method, there shall be a corresponding
 * call to virConnectClose to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
 * it. ie, each new thread using a connection would increment
 * the reference count.
D
Daniel Veillard 已提交
1529 1530
 *
 * Returns 0 in case of success, -1 in case of failure
1531 1532 1533 1534
 */
int
virConnectRef(virConnectPtr conn)
{
1535 1536
    VIR_DEBUG("conn=%p refs=%d", conn, conn ? conn->object.u.s.refs : 0);

1537 1538
    virResetLastError();

1539
    virCheckConnectReturn(conn, -1);
1540
    virObjectRef(conn);
1541 1542 1543
    return 0;
}

1544

D
Daniel Veillard 已提交
1545 1546
/*
 * Not for public use.  This function is part of the internal
1547 1548 1549
 * implementation of driver features in the remote case.
 */
int
1550
virConnectSupportsFeature(virConnectPtr conn, int feature)
1551
{
1552
    int ret;
1553
    VIR_DEBUG("conn=%p, feature=%d", conn, feature);
1554

1555 1556
    virResetLastError();

1557
    virCheckConnectReturn(conn, -1);
1558

1559
    if (!conn->driver->connectSupportsFeature)
1560 1561
        ret = 0;
    else
1562
        ret = conn->driver->connectSupportsFeature(conn, feature);
1563 1564

    if (ret < 0)
1565
        virDispatchError(conn);
1566

1567
    return ret;
1568 1569
}

1570

1571 1572 1573 1574
/**
 * virConnectGetType:
 * @conn: pointer to the hypervisor connection
 *
1575 1576 1577 1578 1579
 * Get the name of the Hypervisor driver used. This is merely the driver
 * name; for example, both KVM and QEMU guests are serviced by the
 * driver for the qemu:// URI, so a return of "QEMU" does not indicate
 * whether KVM acceleration is present.  For more details about the
 * hypervisor, use virConnectGetCapabilities().
1580 1581
 *
 * Returns NULL in case of error, a static zero terminated string otherwise.
1582 1583 1584
 *
 * See also:
 * http://www.redhat.com/archives/libvir-list/2007-February/msg00096.html
1585 1586
 */
const char *
1587 1588
virConnectGetType(virConnectPtr conn)
{
1589
    const char *ret;
1590
    VIR_DEBUG("conn=%p", conn);
1591

1592 1593
    virResetLastError();

1594
    virCheckConnectReturn(conn, NULL);
1595

1596 1597
    if (conn->driver->connectGetType) {
        ret = conn->driver->connectGetType(conn);
1598
        if (ret) return ret;
1599
    }
1600
    return conn->driver->name;
1601 1602
}

1603

D
Daniel Veillard 已提交
1604
/**
1605
 * virConnectGetVersion:
D
Daniel Veillard 已提交
1606
 * @conn: pointer to the hypervisor connection
1607
 * @hvVer: return value for the version of the running hypervisor (OUT)
D
Daniel Veillard 已提交
1608
 *
1609
 * Get the version level of the Hypervisor running. This may work only with
1610
 * hypervisor call, i.e. with privileged access to the hypervisor, not
1611
 * with a Read-Only connection.
D
Daniel Veillard 已提交
1612
 *
1613 1614 1615
 * Returns -1 in case of error, 0 otherwise. if the version can't be
 *    extracted by lack of capacities returns 0 and @hvVer is 0, otherwise
 *    @hvVer value is major * 1,000,000 + minor * 1,000 + release
D
Daniel Veillard 已提交
1616
 */
1617
int
1618 1619
virConnectGetVersion(virConnectPtr conn, unsigned long *hvVer)
{
1620
    VIR_DEBUG("conn=%p, hvVer=%p", conn, hvVer);
1621

1622 1623
    virResetLastError();

1624
    virCheckConnectReturn(conn, -1);
1625
    virCheckNonNullArgGoto(hvVer, error);
1626

1627 1628
    if (conn->driver->connectGetVersion) {
        int ret = conn->driver->connectGetVersion(conn, hvVer);
1629 1630 1631 1632
        if (ret < 0)
            goto error;
        return ret;
    }
D
Daniel P. Berrange 已提交
1633

1634
    virReportUnsupportedError();
1635 1636

error:
1637
    virDispatchError(conn);
1638
    return -1;
1639 1640
}

1641

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
/**
 * virConnectGetLibVersion:
 * @conn: pointer to the hypervisor connection
 * @libVer: returns the libvirt library version used on the connection (OUT)
 *
 * Provides @libVer, which is the version of libvirt used by the
 *   daemon running on the @conn host
 *
 * Returns -1 in case of failure, 0 otherwise, and values for @libVer have
 *      the format major * 1,000,000 + minor * 1,000 + release.
 */
int
virConnectGetLibVersion(virConnectPtr conn, unsigned long *libVer)
{
    int ret = -1;
1657
    VIR_DEBUG("conn=%p, libVir=%p", conn, libVer);
1658 1659 1660

    virResetLastError();

1661
    virCheckConnectReturn(conn, -1);
1662
    virCheckNonNullArgGoto(libVer, error);
1663

1664 1665
    if (conn->driver->connectGetLibVersion) {
        ret = conn->driver->connectGetLibVersion(conn, libVer);
1666 1667 1668 1669 1670
        if (ret < 0)
            goto error;
        return ret;
    }

1671 1672 1673
    *libVer = LIBVIR_VERSION_NUMBER;
    return 0;

1674
error:
1675
    virDispatchError(conn);
1676 1677 1678
    return ret;
}

1679

1680 1681 1682 1683
/**
 * virConnectGetHostname:
 * @conn: pointer to a hypervisor connection
 *
E
Eric Blake 已提交
1684 1685 1686 1687
 * This returns a system hostname on which the hypervisor is
 * running (based on the result of the gethostname system call, but
 * possibly expanded to a fully-qualified domain name via getaddrinfo).
 * If we are connected to a remote system, then this returns the
1688 1689 1690 1691 1692 1693
 * hostname of the remote system.
 *
 * Returns the hostname which must be freed by the caller, or
 * NULL if there was an error.
 */
char *
1694
virConnectGetHostname(virConnectPtr conn)
1695
{
1696
    VIR_DEBUG("conn=%p", conn);
1697

1698 1699
    virResetLastError();

1700
    virCheckConnectReturn(conn, NULL);
1701

1702 1703
    if (conn->driver->connectGetHostname) {
        char *ret = conn->driver->connectGetHostname(conn);
1704 1705 1706 1707
        if (!ret)
            goto error;
        return ret;
    }
1708

1709
    virReportUnsupportedError();
1710 1711

error:
1712
    virDispatchError(conn);
1713 1714 1715
    return NULL;
}

1716

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
/**
 * virConnectGetURI:
 * @conn: pointer to a hypervisor connection
 *
 * This returns the URI (name) of the hypervisor connection.
 * Normally this is the same as or similar to the string passed
 * to the virConnectOpen/virConnectOpenReadOnly call, but
 * the driver may make the URI canonical.  If name == NULL
 * was passed to virConnectOpen, then the driver will return
 * a non-NULL URI which can be used to connect to the same
 * hypervisor later.
 *
 * Returns the URI string which must be freed by the caller, or
 * NULL if there was an error.
 */
char *
1733
virConnectGetURI(virConnectPtr conn)
1734
{
1735
    char *name;
1736
    VIR_DEBUG("conn=%p", conn);
1737

1738 1739
    virResetLastError();

1740
    virCheckConnectReturn(conn, NULL);
1741

1742
    if (!(name = virURIFormat(conn->uri)))
1743
        goto error;
1744

1745
    return name;
1746 1747

error:
1748
    virDispatchError(conn);
1749
    return NULL;
1750 1751
}

1752

E
Eric Blake 已提交
1753 1754 1755
/**
 * virConnectGetSysinfo:
 * @conn: pointer to a hypervisor connection
1756
 * @flags: extra flags; not used yet, so callers should always pass 0
E
Eric Blake 已提交
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
 *
 * This returns the XML description of the sysinfo details for the
 * host on which the hypervisor is running, in the same format as the
 * <sysinfo> element of a domain XML.  This information is generally
 * available only for hypervisors running with root privileges.
 *
 * Returns the XML string which must be freed by the caller, or
 * NULL if there was an error.
 */
char *
1767
virConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
E
Eric Blake 已提交
1768
{
E
Eric Blake 已提交
1769
    VIR_DEBUG("conn=%p, flags=%x", conn, flags);
E
Eric Blake 已提交
1770 1771 1772

    virResetLastError();

1773
    virCheckConnectReturn(conn, NULL);
E
Eric Blake 已提交
1774

1775 1776
    if (conn->driver->connectGetSysinfo) {
        char *ret = conn->driver->connectGetSysinfo(conn, flags);
E
Eric Blake 已提交
1777 1778 1779 1780 1781
        if (!ret)
            goto error;
        return ret;
    }

1782
    virReportUnsupportedError();
E
Eric Blake 已提交
1783 1784 1785 1786 1787 1788

error:
    virDispatchError(conn);
    return NULL;
}

1789

1790 1791 1792 1793 1794
/**
 * virConnectGetMaxVcpus:
 * @conn: pointer to the hypervisor connection
 * @type: value of the 'type' attribute in the <domain> element
 *
1795
 * Provides the maximum number of virtual CPUs supported for a guest VM of a
1796 1797 1798 1799 1800 1801 1802 1803 1804
 * specific type. The 'type' parameter here corresponds to the 'type'
 * attribute in the <domain> element of the XML.
 *
 * Returns the maximum of virtual CPU or -1 in case of error.
 */
int
virConnectGetMaxVcpus(virConnectPtr conn,
                      const char *type)
{
1805
    VIR_DEBUG("conn=%p, type=%s", conn, type);
1806

1807 1808
    virResetLastError();

1809
    virCheckConnectReturn(conn, -1);
1810

1811 1812
    if (conn->driver->connectGetMaxVcpus) {
        int ret = conn->driver->connectGetMaxVcpus(conn, type);
1813 1814 1815 1816
        if (ret < 0)
            goto error;
        return ret;
    }
1817

1818
    virReportUnsupportedError();
1819
error:
1820
    virDispatchError(conn);
1821
    return -1;
1822 1823
}

1824

1825
/**
1826
 * virConnectListDomains:
1827 1828 1829 1830
 * @conn: pointer to the hypervisor connection
 * @ids: array to collect the list of IDs of active domains
 * @maxids: size of @ids
 *
1831
 * Collect the list of active domains, and store their IDs in array @ids
1832
 *
1833 1834 1835 1836 1837 1838 1839 1840
 * For inactive domains, see virConnectListDefinedDomains().  For more
 * control over the results, see virConnectListAllDomains().
 *
 * Returns the number of domains found or -1 in case of error.  Note that
 * this command is inherently racy; a domain can be started between a
 * call to virConnectNumOfDomains() and this call; you are only guaranteed
 * that all currently active domains were listed if the return is less
 * than @maxids.
1841 1842
 */
int
1843 1844
virConnectListDomains(virConnectPtr conn, int *ids, int maxids)
{
1845
    VIR_DEBUG("conn=%p, ids=%p, maxids=%d", conn, ids, maxids);
1846

1847 1848
    virResetLastError();

1849
    virCheckConnectReturn(conn, -1);
1850 1851
    virCheckNonNullArgGoto(ids, error);
    virCheckNonNegativeArgGoto(maxids, error);
1852

1853 1854
    if (conn->driver->connectListDomains) {
        int ret = conn->driver->connectListDomains(conn, ids, maxids);
1855 1856 1857 1858
        if (ret < 0)
            goto error;
        return ret;
    }
1859

1860
    virReportUnsupportedError();
1861
error:
1862
    virDispatchError(conn);
1863
    return -1;
D
Daniel Veillard 已提交
1864 1865
}

1866

K
 
Karel Zak 已提交
1867 1868 1869 1870
/**
 * virConnectNumOfDomains:
 * @conn: pointer to the hypervisor connection
 *
1871 1872
 * Provides the number of active domains.
 *
K
 
Karel Zak 已提交
1873 1874 1875
 * Returns the number of domain found or -1 in case of error
 */
int
1876 1877
virConnectNumOfDomains(virConnectPtr conn)
{
1878
    VIR_DEBUG("conn=%p", conn);
1879

1880 1881
    virResetLastError();

1882
    virCheckConnectReturn(conn, -1);
K
Karel Zak 已提交
1883

1884 1885
    if (conn->driver->connectNumOfDomains) {
        int ret = conn->driver->connectNumOfDomains(conn);
1886 1887 1888 1889
        if (ret < 0)
            goto error;
        return ret;
    }
1890

1891
    virReportUnsupportedError();
1892
error:
1893
    virDispatchError(conn);
1894
    return -1;
K
 
Karel Zak 已提交
1895 1896
}

1897

1898 1899 1900 1901
/**
 * virDomainGetConnect:
 * @dom: pointer to a domain
 *
1902
 * Provides the connection pointer associated with a domain.  The
1903 1904 1905
 * reference counter on the connection is not increased by this
 * call.
 *
1906 1907 1908 1909
 * WARNING: When writing libvirt bindings in other languages, do
 * not use this function.  Instead, store the connection and
 * the domain object together.
 *
1910 1911 1912
 * Returns the virConnectPtr or NULL in case of failure.
 */
virConnectPtr
1913
virDomainGetConnect(virDomainPtr dom)
1914
{
1915
    VIR_DOMAIN_DEBUG(dom);
1916

1917 1918
    virResetLastError();

1919
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
1920
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
1921
        virDispatchError(NULL);
1922 1923 1924 1925 1926
        return NULL;
    }
    return dom->conn;
}

1927

D
Daniel Veillard 已提交
1928
/**
1929
 * virDomainCreateXML:
D
Daniel Veillard 已提交
1930
 * @conn: pointer to the hypervisor connection
D
Daniel Veillard 已提交
1931
 * @xmlDesc: string containing an XML description of the domain
1932
 * @flags: bitwise-OR of supported virDomainCreateFlags
D
Daniel Veillard 已提交
1933
 *
1934
 * Launch a new guest domain, based on an XML description similar
1935
 * to the one returned by virDomainGetXMLDesc()
1936
 * This function may require privileged access to the hypervisor.
1937 1938 1939
 * The domain is not persistent, so its definition will disappear when it
 * is destroyed, or if the host is restarted (see virDomainDefineXML() to
 * define persistent domains).
1940
 *
1941 1942 1943 1944 1945 1946 1947
 * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain
 * will be started, but its CPUs will remain paused. The CPUs
 * can later be manually started using virDomainResume.
 *
 * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
 * domain will be automatically destroyed when the virConnectPtr
 * object is finally released. This will also happen if the
E
Eric Blake 已提交
1948
 * client application crashes / loses its connection to the
1949
 * libvirtd daemon. Any domains marked for auto destroy will
1950
 * block attempts at migration, save-to-file, or snapshots.
1951
 *
D
Daniel Veillard 已提交
1952 1953
 * Returns a new domain object or NULL in case of failure
 */
1954
virDomainPtr
1955 1956
virDomainCreateXML(virConnectPtr conn, const char *xmlDesc,
                   unsigned int flags)
1957
{
1958
    VIR_DEBUG("conn=%p, xmlDesc=%s, flags=%x", conn, xmlDesc, flags);
1959

1960 1961
    virResetLastError();

1962
    virCheckConnectReturn(conn, NULL);
1963
    virCheckNonNullArgGoto(xmlDesc, error);
1964
    virCheckReadOnlyGoto(conn->flags, error);
D
Daniel Veillard 已提交
1965

1966 1967
    if (conn->driver->domainCreateXML) {
        virDomainPtr ret;
1968
        ret = conn->driver->domainCreateXML(conn, xmlDesc, flags);
1969 1970 1971 1972
        if (!ret)
            goto error;
        return ret;
    }
1973

1974
    virReportUnsupportedError();
1975
error:
1976
    virDispatchError(conn);
1977
    return NULL;
D
Daniel Veillard 已提交
1978 1979
}

1980

1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
/**
 * virDomainCreateXMLWithFiles:
 * @conn: pointer to the hypervisor connection
 * @xmlDesc: string containing an XML description of the domain
 * @nfiles: number of file descriptors passed
 * @files: list of file descriptors passed
 * @flags: bitwise-OR of supported virDomainCreateFlags
 *
 * Launch a new guest domain, based on an XML description similar
 * to the one returned by virDomainGetXMLDesc()
 * This function may require privileged access to the hypervisor.
 * The domain is not persistent, so its definition will disappear when it
 * is destroyed, or if the host is restarted (see virDomainDefineXML() to
 * define persistent domains).
 *
 * @files provides an array of file descriptors which will be
 * made available to the 'init' process of the guest. The file
 * handles exposed to the guest will be renumbered to start
 * from 3 (ie immediately following stderr). This is only
 * supported for guests which use container based virtualization
 * technology.
 *
 * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain
 * will be started, but its CPUs will remain paused. The CPUs
 * can later be manually started using virDomainResume.
 *
 * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
 * domain will be automatically destroyed when the virConnectPtr
 * object is finally released. This will also happen if the
 * client application crashes / loses its connection to the
 * libvirtd daemon. Any domains marked for auto destroy will
 * block attempts at migration, save-to-file, or snapshots.
 *
 * Returns a new domain object or NULL in case of failure
 */
virDomainPtr
virDomainCreateXMLWithFiles(virConnectPtr conn, const char *xmlDesc,
                            unsigned int nfiles,
                            int *files,
                            unsigned int flags)
{
    VIR_DEBUG("conn=%p, xmlDesc=%s, nfiles=%u, files=%p, flags=%x",
              conn, xmlDesc, nfiles, files, flags);

    virResetLastError();

2027
    virCheckConnectReturn(conn, NULL);
2028
    virCheckNonNullArgGoto(xmlDesc, error);
2029
    virCheckReadOnlyGoto(conn->flags, error);
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040

    if (conn->driver->domainCreateXMLWithFiles) {
        virDomainPtr ret;
        ret = conn->driver->domainCreateXMLWithFiles(conn, xmlDesc,
                                                     nfiles, files,
                                                     flags);
        if (!ret)
            goto error;
        return ret;
    }

2041
    virReportUnsupportedError();
2042 2043 2044 2045 2046
error:
    virDispatchError(conn);
    return NULL;
}

2047

2048 2049 2050 2051
/**
 * virDomainCreateLinux:
 * @conn: pointer to the hypervisor connection
 * @xmlDesc: string containing an XML description of the domain
2052
 * @flags: extra flags; not used yet, so callers should always pass 0
2053 2054 2055
 *
 * Deprecated after 0.4.6.
 * Renamed to virDomainCreateXML() providing identical functionality.
2056
 * This existing name will left indefinitely for API compatibility.
2057 2058 2059 2060 2061 2062 2063
 *
 * Returns a new domain object or NULL in case of failure
 */
virDomainPtr
virDomainCreateLinux(virConnectPtr conn, const char *xmlDesc,
                     unsigned int flags)
{
2064
    return virDomainCreateXML(conn, xmlDesc, flags);
2065
}
2066

2067

2068
/**
2069
 * virDomainLookupByID:
2070 2071 2072 2073
 * @conn: pointer to the hypervisor connection
 * @id: the domain ID number
 *
 * Try to find a domain based on the hypervisor ID number
D
Daniel Veillard 已提交
2074 2075
 * Note that this won't work for inactive domains which have an ID of -1,
 * in that case a lookup based on the Name or UUId need to be done instead.
2076
 *
2077 2078
 * Returns a new domain object or NULL in case of failure.  If the
 * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
2079
 */
2080
virDomainPtr
2081 2082
virDomainLookupByID(virConnectPtr conn, int id)
{
2083
    VIR_DEBUG("conn=%p, id=%d", conn, id);
2084

2085 2086
    virResetLastError();

2087
    virCheckConnectReturn(conn, NULL);
2088
    virCheckNonNegativeArgGoto(id, error);
2089

2090 2091
    if (conn->driver->domainLookupByID) {
        virDomainPtr ret;
2092
        ret = conn->driver->domainLookupByID(conn, id);
2093 2094 2095 2096
        if (!ret)
            goto error;
        return ret;
    }
2097

2098
    virReportUnsupportedError();
2099 2100

error:
2101
    virDispatchError(conn);
2102
    return NULL;
2103 2104
}

2105

2106 2107 2108
/**
 * virDomainLookupByUUID:
 * @conn: pointer to the hypervisor connection
K
Karel Zak 已提交
2109
 * @uuid: the raw UUID for the domain
2110 2111 2112
 *
 * Try to lookup a domain on the given hypervisor based on its UUID.
 *
2113 2114
 * Returns a new domain object or NULL in case of failure.  If the
 * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
2115 2116
 */
virDomainPtr
2117 2118
virDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
2119
    VIR_UUID_DEBUG(conn, uuid);
2120

2121 2122
    virResetLastError();

2123
    virCheckConnectReturn(conn, NULL);
2124
    virCheckNonNullArgGoto(uuid, error);
2125

2126 2127
    if (conn->driver->domainLookupByUUID) {
        virDomainPtr ret;
2128
        ret = conn->driver->domainLookupByUUID(conn, uuid);
2129 2130 2131 2132
        if (!ret)
            goto error;
        return ret;
    }
2133

2134
    virReportUnsupportedError();
2135 2136

error:
2137
    virDispatchError(conn);
2138
    return NULL;
2139 2140
}

2141

K
Karel Zak 已提交
2142 2143 2144 2145 2146 2147 2148
/**
 * virDomainLookupByUUIDString:
 * @conn: pointer to the hypervisor connection
 * @uuidstr: the string UUID for the domain
 *
 * Try to lookup a domain on the given hypervisor based on its UUID.
 *
2149 2150
 * Returns a new domain object or NULL in case of failure.  If the
 * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
K
Karel Zak 已提交
2151 2152 2153 2154
 */
virDomainPtr
virDomainLookupByUUIDString(virConnectPtr conn, const char *uuidstr)
{
2155
    unsigned char uuid[VIR_UUID_BUFLEN];
2156
    VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr));
2157

2158 2159
    virResetLastError();

2160
    virCheckConnectReturn(conn, NULL);
2161
    virCheckNonNullArgGoto(uuidstr, error);
2162 2163

    if (virUUIDParse(uuidstr, uuid) < 0) {
2164 2165 2166
        virReportInvalidArg(uuidstr,
                            _("uuidstr in %s must be a valid UUID"),
                            __FUNCTION__);
2167
        goto error;
K
Karel Zak 已提交
2168
    }
2169

K
Karel Zak 已提交
2170
    return virDomainLookupByUUID(conn, &uuid[0]);
2171 2172

error:
2173
    virDispatchError(conn);
2174
    return NULL;
K
Karel Zak 已提交
2175 2176
}

2177

2178 2179 2180 2181 2182
/**
 * virDomainLookupByName:
 * @conn: pointer to the hypervisor connection
 * @name: name for the domain
 *
2183
 * Try to lookup a domain on the given hypervisor based on its name.
2184
 *
2185 2186
 * Returns a new domain object or NULL in case of failure.  If the
 * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
2187 2188
 */
virDomainPtr
2189 2190
virDomainLookupByName(virConnectPtr conn, const char *name)
{
2191
    VIR_DEBUG("conn=%p, name=%s", conn, name);
2192

2193 2194
    virResetLastError();

2195
    virCheckConnectReturn(conn, NULL);
2196
    virCheckNonNullArgGoto(name, error);
2197

2198 2199
    if (conn->driver->domainLookupByName) {
        virDomainPtr dom;
2200
        dom = conn->driver->domainLookupByName(conn, name);
2201 2202 2203 2204
        if (!dom)
            goto error;
        return dom;
    }
2205

2206
    virReportUnsupportedError();
2207 2208

error:
2209
    virDispatchError(conn);
2210
    return NULL;
2211 2212
}

2213

D
Daniel Veillard 已提交
2214
/**
2215
 * virDomainDestroy:
D
Daniel Veillard 已提交
2216 2217 2218
 * @domain: a domain object
 *
 * Destroy the domain object. The running instance is shutdown if not down
2219 2220
 * already and all resources used by it are given back to the hypervisor. This
 * does not free the associated virDomainPtr object.
2221
 * This function may require privileged access.
D
Daniel Veillard 已提交
2222
 *
2223 2224
 * virDomainDestroy first requests that a guest terminate
 * (e.g. SIGTERM), then waits for it to comply. After a reasonable
2225
 * timeout, if the guest still exists, virDomainDestroy will
2226 2227 2228 2229 2230 2231
 * forcefully terminate the guest (e.g. SIGKILL) if necessary (which
 * may produce undesirable results, for example unflushed disk cache
 * in the guest). To avoid this possibility, it's recommended to
 * instead call virDomainDestroyFlags, sending the
 * VIR_DOMAIN_DESTROY_GRACEFUL flag.
 *
2232 2233 2234 2235
 * If the domain is transient and has any snapshot metadata (see
 * virDomainSnapshotNum()), then that metadata will automatically
 * be deleted when the domain quits.
 *
D
Daniel Veillard 已提交
2236
 * Returns 0 in case of success and -1 in case of failure.
2237
 */
D
Daniel Veillard 已提交
2238
int
2239 2240
virDomainDestroy(virDomainPtr domain)
{
2241
    virConnectPtr conn;
2242

2243
    VIR_DOMAIN_DEBUG(domain);
2244

2245 2246
    virResetLastError();

D
Daniel Veillard 已提交
2247
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
2248
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
2249
        virDispatchError(NULL);
2250
        return -1;
D
Daniel Veillard 已提交
2251
    }
2252

2253
    conn = domain->conn;
2254
    virCheckReadOnlyGoto(conn->flags, error);
2255

2256 2257
    if (conn->driver->domainDestroy) {
        int ret;
2258
        ret = conn->driver->domainDestroy(domain);
2259 2260 2261 2262
        if (ret < 0)
            goto error;
        return ret;
    }
2263

2264
    virReportUnsupportedError();
2265 2266

error:
2267
    virDispatchError(conn);
2268
    return -1;
2269 2270
}

2271

2272 2273 2274
/**
 * virDomainDestroyFlags:
 * @domain: a domain object
2275
 * @flags: bitwise-OR of virDomainDestroyFlagsValues
2276 2277 2278 2279 2280 2281
 *
 * Destroy the domain object. The running instance is shutdown if not down
 * already and all resources used by it are given back to the hypervisor.
 * This does not free the associated virDomainPtr object.
 * This function may require privileged access.
 *
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
 * Calling this function with no @flags set (equal to zero) is
 * equivalent to calling virDomainDestroy, and after a reasonable
 * timeout will forcefully terminate the guest (e.g. SIGKILL) if
 * necessary (which may produce undesirable results, for example
 * unflushed disk cache in the guest). Including
 * VIR_DOMAIN_DESTROY_GRACEFUL in the flags will prevent the forceful
 * termination of the guest, and virDomainDestroyFlags will instead
 * return an error if the guest doesn't terminate by the end of the
 * timeout; at that time, the management application can decide if
 * calling again without VIR_DOMAIN_DESTROY_GRACEFUL is appropriate.
 *
 * Another alternative which may produce cleaner results for the
 * guest's disks is to use virDomainShutdown() instead, but that
 * depends on guest support (some hypervisor/guest combinations may
 * ignore the shutdown request).
 *
2298 2299 2300 2301 2302 2303 2304 2305 2306
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainDestroyFlags(virDomainPtr domain,
                      unsigned int flags)
{
    virConnectPtr conn;

E
Eric Blake 已提交
2307
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;
2318
    virCheckReadOnlyGoto(conn->flags, error);
2319 2320 2321 2322 2323 2324 2325 2326 2327

    if (conn->driver->domainDestroyFlags) {
        int ret;
        ret = conn->driver->domainDestroyFlags(domain, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

2328
    virReportUnsupportedError();
2329 2330 2331 2332 2333 2334

error:
    virDispatchError(conn);
    return -1;
}

2335

2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
/**
 * virDomainFree:
 * @domain: a domain object
 *
 * Free the domain object. The running instance is kept alive.
 * The data structure is freed and should not be used thereafter.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
2346 2347
virDomainFree(virDomainPtr domain)
{
2348
    VIR_DOMAIN_DEBUG(domain);
2349

2350 2351 2352
    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
2353
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
2354
        virDispatchError(NULL);
2355
        return -1;
D
Daniel Veillard 已提交
2356
    }
2357
    virObjectUnref(domain);
2358
    return 0;
D
Daniel Veillard 已提交
2359 2360
}

2361

2362 2363
/**
 * virDomainRef:
D
Daniel Veillard 已提交
2364
 * @domain: the domain to hold a reference on
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
 *
 * Increment the reference count on the domain. For each
 * additional call to this method, there shall be a corresponding
 * call to virDomainFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
 * it. ie, each new thread using a domain would increment
 * the reference count.
D
Daniel Veillard 已提交
2376 2377
 *
 * Returns 0 in case of success and -1 in case of failure.
2378 2379 2380 2381
 */
int
virDomainRef(virDomainPtr domain)
{
2382 2383
    VIR_DOMAIN_DEBUG(domain, "refs=%d", domain ? domain->object.u.s.refs : 0);

2384 2385
    virResetLastError();

2386
    if ((!VIR_IS_CONNECTED_DOMAIN(domain))) {
2387
        virLibConnError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
2388
        virDispatchError(NULL);
2389
        return -1;
2390
    }
2391 2392

    virObjectRef(domain);
2393 2394 2395 2396
    return 0;
}


D
Daniel Veillard 已提交
2397
/**
2398
 * virDomainSuspend:
D
Daniel Veillard 已提交
2399 2400 2401
 * @domain: a domain object
 *
 * Suspends an active domain, the process is frozen without further access
2402
 * to CPU resources and I/O but the memory used by the domain at the
2403
 * hypervisor level will stay allocated. Use virDomainResume() to reactivate
D
Daniel Veillard 已提交
2404
 * the domain.
2405
 * This function may require privileged access.
2406 2407
 * Moreover, suspend may not be supported if domain is in some
 * special state like VIR_DOMAIN_PMSUSPENDED.
D
Daniel Veillard 已提交
2408 2409 2410 2411
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
2412 2413
virDomainSuspend(virDomainPtr domain)
{
2414
    virConnectPtr conn;
2415

2416
    VIR_DOMAIN_DEBUG(domain);
2417

2418 2419
    virResetLastError();

D
Daniel Veillard 已提交
2420
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
2421
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
2422
        virDispatchError(NULL);
2423
        return -1;
D
Daniel Veillard 已提交
2424
    }
2425
    virCheckReadOnlyGoto(domain->conn->flags, error);
D
Daniel Veillard 已提交
2426

2427 2428
    conn = domain->conn;

2429 2430
    if (conn->driver->domainSuspend) {
        int ret;
2431
        ret = conn->driver->domainSuspend(domain);
2432 2433 2434 2435
        if (ret < 0)
            goto error;
        return ret;
    }
2436

2437
    virReportUnsupportedError();
2438 2439

error:
2440
    virDispatchError(domain->conn);
2441
    return -1;
D
Daniel Veillard 已提交
2442 2443
}

2444

D
Daniel Veillard 已提交
2445
/**
2446
 * virDomainResume:
D
Daniel Veillard 已提交
2447 2448
 * @domain: a domain object
 *
D
Dan Kenigsberg 已提交
2449
 * Resume a suspended domain, the process is restarted from the state where
2450
 * it was frozen by calling virDomainSuspend().
2451
 * This function may require privileged access
2452 2453
 * Moreover, resume may not be supported if domain is in some
 * special state like VIR_DOMAIN_PMSUSPENDED.
D
Daniel Veillard 已提交
2454 2455 2456 2457
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
2458 2459
virDomainResume(virDomainPtr domain)
{
2460
    virConnectPtr conn;
2461

2462
    VIR_DOMAIN_DEBUG(domain);
2463

2464 2465
    virResetLastError();

D
Daniel Veillard 已提交
2466
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
2467
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
2468
        virDispatchError(NULL);
2469
        return -1;
D
Daniel Veillard 已提交
2470
    }
2471
    virCheckReadOnlyGoto(domain->conn->flags, error);
D
Daniel Veillard 已提交
2472

2473 2474
    conn = domain->conn;

2475 2476
    if (conn->driver->domainResume) {
        int ret;
2477
        ret = conn->driver->domainResume(domain);
2478 2479 2480 2481
        if (ret < 0)
            goto error;
        return ret;
    }
2482

2483
    virReportUnsupportedError();
2484 2485

error:
2486
    virDispatchError(domain->conn);
2487
    return -1;
D
Daniel Veillard 已提交
2488 2489
}

2490

2491 2492 2493
/**
 * virDomainPMSuspendForDuration:
 * @dom: a domain object
2494 2495 2496
 * @target: a value from virNodeSuspendTarget
 * @duration: duration in seconds to suspend, or 0 for indefinite
 * @flags: extra flags; not used yet, so callers should always pass 0
2497
 *
2498 2499 2500 2501 2502
 * Attempt to have the guest enter the given @target power management
 * suspension level.  If @duration is non-zero, also schedule the guest to
 * resume normal operation after that many seconds, if nothing else has
 * resumed it earlier.  Some hypervisors require that @duration be 0, for
 * an indefinite suspension.
2503
 *
2504
 * Dependent on hypervisor used, this may require a
2505 2506
 * guest agent to be available, e.g. QEMU.
 *
2507 2508 2509 2510 2511 2512 2513
 * Beware that at least for QEMU, the domain's process will be terminated
 * when VIR_NODE_SUSPEND_TARGET_DISK is used and a new process will be
 * launched when libvirt is asked to wake up the domain. As a result of
 * this, any runtime changes, such as device hotplug or memory settings,
 * are lost unless such changes were made with VIR_DOMAIN_AFFECT_CONFIG
 * flag.
 *
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
 * Returns: 0 on success,
 *          -1 on failure.
 */
int
virDomainPMSuspendForDuration(virDomainPtr dom,
                              unsigned int target,
                              unsigned long long duration,
                              unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(dom, "target=%u duration=%llu flags=%x",
                     target, duration, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = dom->conn;

2538
    virCheckReadOnlyGoto(conn->flags, error);
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548

    if (conn->driver->domainPMSuspendForDuration) {
        int ret;
        ret = conn->driver->domainPMSuspendForDuration(dom, target,
                                                       duration, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

2549
    virReportUnsupportedError();
2550 2551 2552 2553 2554 2555

error:
    virDispatchError(conn);
    return -1;
}

2556

2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
/**
 * virDomainPMWakeup:
 * @dom: a domain object
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Inject a wakeup into the guest that previously used
 * virDomainPMSuspendForDuration, rather than waiting for the
 * previously requested duration (if any) to elapse.
 *
 * Returns: 0 on success,
 *          -1 on failure.
 */
int
virDomainPMWakeup(virDomainPtr dom,
                  unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(dom, "flags=%x", flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = dom->conn;

2587
    virCheckReadOnlyGoto(conn->flags, error);
2588 2589 2590 2591 2592 2593 2594 2595 2596

    if (conn->driver->domainPMWakeup) {
        int ret;
        ret = conn->driver->domainPMWakeup(dom, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

2597
    virReportUnsupportedError();
2598 2599 2600 2601 2602 2603

error:
    virDispatchError(conn);
    return -1;
}

2604

2605 2606 2607 2608 2609 2610
/**
 * virDomainSave:
 * @domain: a domain object
 * @to: path for the output file
 *
 * This method will suspend a domain and save its memory contents to
2611
 * a file on disk. After the call, if successful, the domain is not
2612
 * listed as running anymore (this ends the life of a transient domain).
2613
 * Use virDomainRestore() to restore a domain after saving.
2614
 *
2615 2616 2617
 * See virDomainSaveFlags() for more control.  Also, a save file can
 * be inspected or modified slightly with virDomainSaveImageGetXMLDesc()
 * and virDomainSaveImageDefineXML().
2618
 *
2619 2620 2621
 * Returns 0 in case of success and -1 in case of failure.
 */
int
2622 2623
virDomainSave(virDomainPtr domain, const char *to)
{
2624
    virConnectPtr conn;
2625 2626

    VIR_DOMAIN_DEBUG(domain, "to=%s", to);
2627

2628 2629
    virResetLastError();

D
Daniel Veillard 已提交
2630
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
2631
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
2632
        virDispatchError(NULL);
2633
        return -1;
D
Daniel Veillard 已提交
2634
    }
2635
    virCheckReadOnlyGoto(domain->conn->flags, error);
2636
    conn = domain->conn;
2637
    virCheckNonNullArgGoto(to, error);
2638

2639 2640 2641
    if (conn->driver->domainSave) {
        int ret;
        char *absolute_to;
2642

2643 2644
        /* We must absolutize the file path as the save is done out of process */
        if (virFileAbsPath(to, &absolute_to) < 0) {
2645
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
2646 2647 2648
                            _("could not build absolute output file path"));
            goto error;
        }
2649

2650 2651 2652
        ret = conn->driver->domainSave(domain, absolute_to);

        VIR_FREE(absolute_to);
2653

2654 2655 2656 2657
        if (ret < 0)
            goto error;
        return ret;
    }
2658

2659
    virReportUnsupportedError();
2660 2661

error:
2662
    virDispatchError(domain->conn);
2663
    return -1;
2664 2665
}

2666

2667 2668 2669 2670 2671 2672 2673 2674 2675
/**
 * virDomainSaveFlags:
 * @domain: a domain object
 * @to: path for the output file
 * @dxml: (optional) XML config for adjusting guest xml used on restore
 * @flags: bitwise-OR of virDomainSaveRestoreFlags
 *
 * This method will suspend a domain and save its memory contents to
 * a file on disk. After the call, if successful, the domain is not
2676
 * listed as running anymore (this ends the life of a transient domain).
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
 * Use virDomainRestore() to restore a domain after saving.
 *
 * If the hypervisor supports it, @dxml can be used to alter
 * host-specific portions of the domain XML that will be used when
 * restoring an image.  For example, it is possible to alter the
 * backing filename that is associated with a disk device, in order to
 * prepare for file renaming done as part of backing up the disk
 * device while the domain is stopped.
 *
 * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will
 * attempt to bypass the file system cache while creating the file, or
 * fail if it cannot do so for the given system; this can allow less
 * pressure on file system cache, but also risks slowing saves to NFS.
 *
2691 2692 2693 2694 2695 2696
 * Normally, the saved state file will remember whether the domain was
 * running or paused, and restore defaults to the same state.
 * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
 * @flags will override what state gets saved into the file.  These
 * two flags are mutually exclusive.
 *
2697 2698 2699
 * A save file can be inspected or modified slightly with
 * virDomainSaveImageGetXMLDesc() and virDomainSaveImageDefineXML().
 *
E
Eric Blake 已提交
2700 2701 2702 2703
 * Some hypervisors may prevent this operation if there is a current
 * block copy operation; in that case, use virDomainBlockJobAbort()
 * to stop the block copy first.
 *
2704 2705 2706 2707 2708 2709 2710 2711
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainSaveFlags(virDomainPtr domain, const char *to,
                   const char *dxml, unsigned int flags)
{
    virConnectPtr conn;

E
Eric Blake 已提交
2712
    VIR_DOMAIN_DEBUG(domain, "to=%s, dxml=%s, flags=%x",
2713 2714 2715 2716 2717 2718 2719 2720 2721
                     to, NULLSTR(dxml), flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
2722
    virCheckReadOnlyGoto(domain->conn->flags, error);
2723
    conn = domain->conn;
2724
    virCheckNonNullArgGoto(to, error);
2725

2726
    if ((flags & VIR_DOMAIN_SAVE_RUNNING) && (flags & VIR_DOMAIN_SAVE_PAUSED)) {
2727
        virReportInvalidArg(flags, "%s",
2728 2729
                            _("running and paused flags are mutually "
                              "exclusive"));
2730 2731 2732
        goto error;
    }

2733 2734 2735 2736 2737 2738
    if (conn->driver->domainSaveFlags) {
        int ret;
        char *absolute_to;

        /* We must absolutize the file path as the save is done out of process */
        if (virFileAbsPath(to, &absolute_to) < 0) {
2739
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
                            _("could not build absolute output file path"));
            goto error;
        }

        ret = conn->driver->domainSaveFlags(domain, absolute_to, dxml, flags);

        VIR_FREE(absolute_to);

        if (ret < 0)
            goto error;
        return ret;
    }

2753
    virReportUnsupportedError();
2754 2755 2756 2757 2758 2759

error:
    virDispatchError(domain->conn);
    return -1;
}

2760

2761 2762
/**
 * virDomainRestore:
2763
 * @conn: pointer to the hypervisor connection
2764
 * @from: path to the input file
2765 2766 2767
 *
 * This method will restore a domain saved to disk by virDomainSave().
 *
2768 2769
 * See virDomainRestoreFlags() for more control.
 *
2770 2771 2772
 * Returns 0 in case of success and -1 in case of failure.
 */
int
2773 2774
virDomainRestore(virConnectPtr conn, const char *from)
{
2775
    VIR_DEBUG("conn=%p, from=%s", conn, from);
2776

2777 2778
    virResetLastError();

2779
    virCheckConnectReturn(conn, -1);
2780
    virCheckReadOnlyGoto(conn->flags, error);
2781
    virCheckNonNullArgGoto(from, error);
D
Daniel Veillard 已提交
2782

2783 2784 2785
    if (conn->driver->domainRestore) {
        int ret;
        char *absolute_from;
2786

2787 2788
        /* We must absolutize the file path as the restore is done out of process */
        if (virFileAbsPath(from, &absolute_from) < 0) {
2789
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
2790
                            _("could not build absolute input file path"));
2791 2792
            goto error;
        }
2793

2794 2795 2796 2797
        ret = conn->driver->domainRestore(conn, absolute_from);

        VIR_FREE(absolute_from);

2798 2799 2800 2801
        if (ret < 0)
            goto error;
        return ret;
    }
2802

2803
    virReportUnsupportedError();
2804 2805

error:
2806
    virDispatchError(conn);
2807
    return -1;
D
Daniel Veillard 已提交
2808 2809
}

2810

2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
/**
 * virDomainRestoreFlags:
 * @conn: pointer to the hypervisor connection
 * @from: path to the input file
 * @dxml: (optional) XML config for adjusting guest xml used on restore
 * @flags: bitwise-OR of virDomainSaveRestoreFlags
 *
 * This method will restore a domain saved to disk by virDomainSave().
 *
 * If the hypervisor supports it, @dxml can be used to alter
 * host-specific portions of the domain XML that will be used when
 * restoring an image.  For example, it is possible to alter the
 * backing filename that is associated with a disk device, in order to
 * prepare for file renaming done as part of backing up the disk
 * device while the domain is stopped.
 *
 * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will
 * attempt to bypass the file system cache while restoring the file, or
 * fail if it cannot do so for the given system; this can allow less
2830
 * pressure on file system cache, but also risks slowing restores from NFS.
2831
 *
2832 2833 2834 2835 2836 2837
 * Normally, the saved state file will remember whether the domain was
 * running or paused, and restore defaults to the same state.
 * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
 * @flags will override the default read from the file.  These two
 * flags are mutually exclusive.
 *
2838 2839 2840 2841
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainRestoreFlags(virConnectPtr conn, const char *from, const char *dxml,
2842
                      unsigned int flags)
2843 2844 2845 2846 2847 2848
{
    VIR_DEBUG("conn=%p, from=%s, dxml=%s, flags=%x",
              conn, from, NULLSTR(dxml), flags);

    virResetLastError();

2849
    virCheckConnectReturn(conn, -1);
2850
    virCheckReadOnlyGoto(conn->flags, error);
2851
    virCheckNonNullArgGoto(from, error);
2852

2853
    if ((flags & VIR_DOMAIN_SAVE_RUNNING) && (flags & VIR_DOMAIN_SAVE_PAUSED)) {
2854
        virReportInvalidArg(flags, "%s",
2855 2856
                            _("running and paused flags are mutually "
                              "exclusive"));
2857 2858 2859
        goto error;
    }

2860 2861 2862 2863 2864 2865
    if (conn->driver->domainRestoreFlags) {
        int ret;
        char *absolute_from;

        /* We must absolutize the file path as the restore is done out of process */
        if (virFileAbsPath(from, &absolute_from) < 0) {
2866
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
                            _("could not build absolute input file path"));
            goto error;
        }

        ret = conn->driver->domainRestoreFlags(conn, absolute_from, dxml,
                                               flags);

        VIR_FREE(absolute_from);

        if (ret < 0)
            goto error;
        return ret;
    }

2881
    virReportUnsupportedError();
2882 2883 2884 2885 2886 2887

error:
    virDispatchError(conn);
    return -1;
}

2888

2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
/**
 * virDomainSaveImageGetXMLDesc:
 * @conn: pointer to the hypervisor connection
 * @file: path to saved state file
 * @flags: bitwise-OR of subset of virDomainXMLFlags
 *
 * This method will extract the XML describing the domain at the time
 * a saved state file was created.  @file must be a file created
 * previously by virDomainSave() or virDomainSaveFlags().
 *
 * No security-sensitive data will be included unless @flags contains
 * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only
 * connections.  For this API, @flags should not contain either
 * VIR_DOMAIN_XML_INACTIVE or VIR_DOMAIN_XML_UPDATE_CPU.
 *
 * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of
 * error.  The caller must free() the returned value.
 */
char *
virDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *file,
                             unsigned int flags)
{
    VIR_DEBUG("conn=%p, file=%s, flags=%x",
              conn, file, flags);

    virResetLastError();

2916
    virCheckConnectReturn(conn, NULL);
2917
    virCheckNonNullArgGoto(file, error);
2918 2919

    if ((conn->flags & VIR_CONNECT_RO) && (flags & VIR_DOMAIN_XML_SECURE)) {
2920
        virLibConnError(VIR_ERR_OPERATION_DENIED, "%s",
2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
                        _("virDomainSaveImageGetXMLDesc with secure flag"));
        goto error;
    }

    if (conn->driver->domainSaveImageGetXMLDesc) {
        char *ret;
        char *absolute_file;

        /* We must absolutize the file path as the read is done out of process */
        if (virFileAbsPath(file, &absolute_file) < 0) {
2931
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945
                            _("could not build absolute input file path"));
            goto error;
        }

        ret = conn->driver->domainSaveImageGetXMLDesc(conn, absolute_file,
                                                      flags);

        VIR_FREE(absolute_file);

        if (!ret)
            goto error;
        return ret;
    }

2946
    virReportUnsupportedError();
2947 2948 2949 2950 2951 2952

error:
    virDispatchError(conn);
    return NULL;
}

2953

2954 2955 2956 2957 2958
/**
 * virDomainSaveImageDefineXML:
 * @conn: pointer to the hypervisor connection
 * @file: path to saved state file
 * @dxml: XML config for adjusting guest xml used on restore
2959
 * @flags: bitwise-OR of virDomainSaveRestoreFlags
2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970
 *
 * This updates the definition of a domain stored in a saved state
 * file.  @file must be a file created previously by virDomainSave()
 * or virDomainSaveFlags().
 *
 * @dxml can be used to alter host-specific portions of the domain XML
 * that will be used when restoring an image.  For example, it is
 * possible to alter the backing filename that is associated with a
 * disk device, to match renaming done as part of backing up the disk
 * device while the domain is stopped.
 *
2971 2972 2973 2974 2975 2976 2977
 * Normally, the saved state file will remember whether the domain was
 * running or paused, and restore defaults to the same state.
 * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
 * @flags will override the default saved into the file; omitting both
 * leaves the file's default unchanged.  These two flags are mutually
 * exclusive.
 *
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainSaveImageDefineXML(virConnectPtr conn, const char *file,
                            const char *dxml, unsigned int flags)
{
    VIR_DEBUG("conn=%p, file=%s, dxml=%s, flags=%x",
              conn, file, dxml, flags);

    virResetLastError();

2989
    virCheckConnectReturn(conn, -1);
2990
    virCheckReadOnlyGoto(conn->flags, error);
2991 2992
    virCheckNonNullArgGoto(file, error);
    virCheckNonNullArgGoto(dxml, error);
2993

2994
    if ((flags & VIR_DOMAIN_SAVE_RUNNING) && (flags & VIR_DOMAIN_SAVE_PAUSED)) {
2995
        virReportInvalidArg(flags, "%s",
2996 2997
                            _("running and paused flags are mutually "
                              "exclusive"));
2998 2999 3000
        goto error;
    }

3001 3002 3003 3004 3005 3006
    if (conn->driver->domainSaveImageDefineXML) {
        int ret;
        char *absolute_file;

        /* We must absolutize the file path as the read is done out of process */
        if (virFileAbsPath(file, &absolute_file) < 0) {
3007
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
                            _("could not build absolute input file path"));
            goto error;
        }

        ret = conn->driver->domainSaveImageDefineXML(conn, absolute_file,
                                                     dxml, flags);

        VIR_FREE(absolute_file);

        if (ret < 0)
            goto error;
        return ret;
    }

3022
    virReportUnsupportedError();
3023 3024 3025 3026 3027 3028

error:
    virDispatchError(conn);
    return -1;
}

3029

D
Daniel Veillard 已提交
3030 3031 3032 3033
/**
 * virDomainCoreDump:
 * @domain: a domain object
 * @to: path for the core file
3034
 * @flags: bitwise-OR of virDomainCoreDumpFlags
D
Daniel Veillard 已提交
3035 3036 3037
 *
 * This method will dump the core of a domain on a given file for analysis.
 * Note that for remote Xen Daemon the file path will be interpreted in
3038 3039
 * the remote host. Hypervisors may require  the user to manually ensure
 * proper permissions on the file named by @to.
D
Daniel Veillard 已提交
3040
 *
3041 3042 3043 3044
 * If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with
 * a crashed state after the dump completes.  If @flags includes
 * VIR_DUMP_LIVE, then make the core dump while continuing to allow
 * the guest to run; otherwise, the guest is suspended during the dump.
3045 3046
 * VIR_DUMP_RESET flag forces reset of the quest after dump.
 * The above three flags are mutually exclusive.
3047 3048 3049 3050 3051 3052
 *
 * Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt
 * will attempt to bypass the file system cache while creating the file,
 * or fail if it cannot do so for the given system; this can allow less
 * pressure on file system cache, but also risks slowing saves to NFS.
 *
D
Daniel Veillard 已提交
3053 3054 3055
 * Returns 0 in case of success and -1 in case of failure.
 */
int
3056
virDomainCoreDump(virDomainPtr domain, const char *to, unsigned int flags)
D
Daniel Veillard 已提交
3057 3058
{
    virConnectPtr conn;
3059

3060
    VIR_DOMAIN_DEBUG(domain, "to=%s, flags=%x", to, flags);
D
Daniel Veillard 已提交
3061

3062 3063
    virResetLastError();

D
Daniel Veillard 已提交
3064
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3065
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3066
        virDispatchError(NULL);
3067
        return -1;
D
Daniel Veillard 已提交
3068
    }
3069
    virCheckReadOnlyGoto(domain->conn->flags, error);
D
Daniel Veillard 已提交
3070
    conn = domain->conn;
3071
    virCheckNonNullArgGoto(to, error);
D
Daniel Veillard 已提交
3072

3073
    if ((flags & VIR_DUMP_CRASH) && (flags & VIR_DUMP_LIVE)) {
3074 3075
        virReportInvalidArg(flags, "%s",
                            _("crash and live flags are mutually exclusive"));
3076 3077 3078
        goto error;
    }

3079
    if ((flags & VIR_DUMP_CRASH) && (flags & VIR_DUMP_RESET)) {
3080
        virReportInvalidArg(flags, "%s",
3081 3082 3083 3084 3085
                         _("crash and reset flags are mutually exclusive"));
        goto error;
    }

    if ((flags & VIR_DUMP_LIVE) && (flags & VIR_DUMP_RESET)) {
3086 3087
        virReportInvalidArg(flags, "%s",
                            _("live and reset flags are mutually exclusive"));
3088 3089 3090
        goto error;
    }

3091 3092 3093
    if (conn->driver->domainCoreDump) {
        int ret;
        char *absolute_to;
D
Daniel Veillard 已提交
3094

3095 3096
        /* We must absolutize the file path as the save is done out of process */
        if (virFileAbsPath(to, &absolute_to) < 0) {
3097
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
3098
                            _("could not build absolute core file path"));
3099 3100
            goto error;
        }
D
Daniel Veillard 已提交
3101

3102 3103 3104
        ret = conn->driver->domainCoreDump(domain, absolute_to, flags);

        VIR_FREE(absolute_to);
D
Daniel Veillard 已提交
3105

3106 3107 3108 3109
        if (ret < 0)
            goto error;
        return ret;
    }
3110

3111
    virReportUnsupportedError();
3112 3113

error:
3114
    virDispatchError(domain->conn);
3115
    return -1;
3116 3117
}

3118

3119 3120 3121 3122 3123
/**
 * virDomainScreenshot:
 * @domain: a domain object
 * @stream: stream to use as output
 * @screen: monitor ID to take screenshot from
3124
 * @flags: extra flags; not used yet, so callers should always pass 0
3125 3126 3127 3128 3129 3130 3131
 *
 * Take a screenshot of current domain console as a stream. The image format
 * is hypervisor specific. Moreover, some hypervisors supports multiple
 * displays per domain. These can be distinguished by @screen argument.
 *
 * This call sets up a stream; subsequent use of stream API is necessary
 * to transfer actual data, determine how much data is successfully
J
Ján Tomko 已提交
3132
 * transferred, and detect any errors.
3133 3134 3135 3136
 *
 * The screen ID is the sequential number of screen. In case of multiple
 * graphics cards, heads are enumerated before devices, e.g. having
 * two graphics cards, both with four heads, screen ID 5 addresses
3137
 * the second head on the second card.
3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
 *
 * Returns a string representing the mime-type of the image format, or
 * NULL upon error. The caller must free() the returned value.
 */
char *
virDomainScreenshot(virDomainPtr domain,
                    virStreamPtr stream,
                    unsigned int screen,
                    unsigned int flags)
{
E
Eric Blake 已提交
3148
    VIR_DOMAIN_DEBUG(domain, "stream=%p, flags=%x", stream, flags);
3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
    if (!VIR_IS_STREAM(stream)) {
        virLibConnError(VIR_ERR_INVALID_STREAM, __FUNCTION__);
        return NULL;
    }
3161
    virCheckReadOnlyGoto(domain->conn->flags | stream->conn->flags, error);
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172

    if (domain->conn->driver->domainScreenshot) {
        char * ret;
        ret = domain->conn->driver->domainScreenshot(domain, stream,
                                                     screen, flags);

        if (ret == NULL)
            goto error;
        return ret;
    }

3173
    virReportUnsupportedError();
3174 3175 3176 3177 3178 3179

error:
    virDispatchError(domain->conn);
    return NULL;
}

3180

3181 3182 3183 3184
/**
 * virDomainShutdown:
 * @domain: a domain object
 *
3185
 * Shutdown a domain, the domain object is still usable thereafter, but
3186
 * the domain OS is being stopped. Note that the guest OS may ignore the
3187 3188 3189
 * request. Additionally, the hypervisor may check and support the domain
 * 'on_poweroff' XML setting resulting in a domain that reboots instead of
 * shutting down. For guests that react to a shutdown request, the differences
3190 3191 3192 3193
 * from virDomainDestroy() are that the guests disk storage will be in a
 * stable state rather than having the (virtual) power cord pulled, and
 * this command returns as soon as the shutdown request is issued rather
 * than blocking until the guest is no longer running.
3194
 *
3195 3196 3197
 * If the domain is transient and has any snapshot metadata (see
 * virDomainSnapshotNum()), then that metadata will automatically
 * be deleted when the domain quits.
3198 3199 3200 3201
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
3202 3203
virDomainShutdown(virDomainPtr domain)
{
3204
    virConnectPtr conn;
3205

3206
    VIR_DOMAIN_DEBUG(domain);
3207

3208 3209
    virResetLastError();

D
Daniel Veillard 已提交
3210
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3211
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3212
        virDispatchError(NULL);
3213
        return -1;
D
Daniel Veillard 已提交
3214
    }
3215
    virCheckReadOnlyGoto(domain->conn->flags, error);
3216

3217 3218
    conn = domain->conn;

3219 3220
    if (conn->driver->domainShutdown) {
        int ret;
3221
        ret = conn->driver->domainShutdown(domain);
3222 3223 3224 3225
        if (ret < 0)
            goto error;
        return ret;
    }
3226

3227
    virReportUnsupportedError();
3228 3229

error:
3230
    virDispatchError(domain->conn);
3231
    return -1;
3232 3233
}

3234

3235 3236 3237 3238 3239 3240 3241
/**
 * virDomainShutdownFlags:
 * @domain: a domain object
 * @flags: bitwise-OR of virDomainShutdownFlagValues
 *
 * Shutdown a domain, the domain object is still usable thereafter but
 * the domain OS is being stopped. Note that the guest OS may ignore the
3242 3243 3244
 * request. Additionally, the hypervisor may check and support the domain
 * 'on_poweroff' XML setting resulting in a domain that reboots instead of
 * shutting down. For guests that react to a shutdown request, the differences
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255
 * from virDomainDestroy() are that the guest's disk storage will be in a
 * stable state rather than having the (virtual) power cord pulled, and
 * this command returns as soon as the shutdown request is issued rather
 * than blocking until the guest is no longer running.
 *
 * If the domain is transient and has any snapshot metadata (see
 * virDomainSnapshotNum()), then that metadata will automatically
 * be deleted when the domain quits.
 *
 * If @flags is set to zero, then the hypervisor will choose the
 * method of shutdown it considers best. To have greater control
3256 3257 3258
 * pass one or more of the virDomainShutdownFlagValues. The order
 * in which the hypervisor tries each shutdown method is undefined,
 * and a hypervisor is not required to support all methods.
3259 3260 3261 3262 3263 3264 3265 3266
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
{
    virConnectPtr conn;

3267
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
3268 3269 3270 3271 3272 3273 3274 3275

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
3276
    virCheckReadOnlyGoto(domain->conn->flags, error);
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287

    conn = domain->conn;

    if (conn->driver->domainShutdownFlags) {
        int ret;
        ret = conn->driver->domainShutdownFlags(domain, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

3288
    virReportUnsupportedError();
3289 3290 3291 3292 3293 3294

error:
    virDispatchError(domain->conn);
    return -1;
}

3295

3296 3297 3298
/**
 * virDomainReboot:
 * @domain: a domain object
3299
 * @flags: bitwise-OR of virDomainRebootFlagValues
3300
 *
3301
 * Reboot a domain, the domain object is still usable thereafter, but
3302 3303
 * the domain OS is being stopped for a restart.
 * Note that the guest OS may ignore the request.
3304 3305 3306
 * Additionally, the hypervisor may check and support the domain
 * 'on_reboot' XML setting resulting in a domain that shuts down instead
 * of rebooting.
3307
 *
3308 3309
 * If @flags is set to zero, then the hypervisor will choose the
 * method of shutdown it considers best. To have greater control
3310 3311 3312
 * pass one or more of the virDomainShutdownFlagValues. The order
 * in which the hypervisor tries each shutdown method is undefined,
 * and a hypervisor is not required to support all methods.
3313 3314 3315 3316
 *
 * To use guest agent (VIR_DOMAIN_REBOOT_GUEST_AGENT) the domain XML
 * must have <channel> configured.
 *
3317 3318 3319 3320 3321
 * Due to implementation limitations in some drivers (the qemu driver,
 * for instance) it is not advised to migrate or save a guest that is
 * rebooting as a result of this API. Migrating such a guest can lead
 * to a plain shutdown on the destination.
 *
3322 3323 3324 3325 3326
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainReboot(virDomainPtr domain, unsigned int flags)
{
3327
    virConnectPtr conn;
3328

3329
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
3330

3331 3332
    virResetLastError();

3333
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3334
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3335
        virDispatchError(NULL);
3336
        return -1;
3337
    }
3338
    virCheckReadOnlyGoto(domain->conn->flags, error);
3339

3340 3341
    conn = domain->conn;

3342 3343
    if (conn->driver->domainReboot) {
        int ret;
3344
        ret = conn->driver->domainReboot(domain, flags);
3345 3346 3347 3348
        if (ret < 0)
            goto error;
        return ret;
    }
3349

3350
    virReportUnsupportedError();
X
Xu He Jie 已提交
3351 3352 3353 3354 3355 3356

error:
    virDispatchError(domain->conn);
    return -1;
}

3357

X
Xu He Jie 已提交
3358 3359 3360
/**
 * virDomainReset:
 * @domain: a domain object
3361
 * @flags: extra flags; not used yet, so callers should always pass 0
X
Xu He Jie 已提交
3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385
 *
 * Reset a domain immediately without any guest OS shutdown.
 * Reset emulates the power reset button on a machine, where all
 * hardware sees the RST line set and reinitializes internal state.
 *
 * Note that there is a risk of data loss caused by reset without any
 * guest OS shutdown.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainReset(virDomainPtr domain, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
3386
    virCheckReadOnlyGoto(domain->conn->flags, error);
X
Xu He Jie 已提交
3387 3388 3389 3390 3391

    conn = domain->conn;

    if (conn->driver->domainReset) {
        int ret;
3392
        ret = conn->driver->domainReset(domain, flags);
X
Xu He Jie 已提交
3393 3394 3395 3396 3397
        if (ret < 0)
            goto error;
        return ret;
    }

3398
    virReportUnsupportedError();
3399 3400

error:
3401
    virDispatchError(domain->conn);
3402
    return -1;
3403 3404
}

3405

3406
/**
3407
 * virDomainGetName:
3408 3409 3410 3411 3412 3413 3414 3415
 * @domain: a domain object
 *
 * Get the public name for that domain
 *
 * Returns a pointer to the name or NULL, the string need not be deallocated
 * its lifetime will be the same as the domain object.
 */
const char *
3416 3417
virDomainGetName(virDomainPtr domain)
{
3418
    VIR_DEBUG("domain=%p", domain);
3419

3420 3421
    virResetLastError();

D
Daniel Veillard 已提交
3422
    if (!VIR_IS_DOMAIN(domain)) {
3423
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3424
        virDispatchError(NULL);
3425
        return NULL;
D
Daniel Veillard 已提交
3426
    }
3427
    return domain->name;
3428 3429
}

3430

3431 3432 3433
/**
 * virDomainGetUUID:
 * @domain: a domain object
3434
 * @uuid: pointer to a VIR_UUID_BUFLEN bytes array
3435 3436 3437 3438 3439 3440
 *
 * Get the UUID for a domain
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
3441 3442
virDomainGetUUID(virDomainPtr domain, unsigned char *uuid)
{
3443
    VIR_DOMAIN_DEBUG(domain, "uuid=%p", uuid);
3444

3445 3446
    virResetLastError();

D
Daniel Veillard 已提交
3447
    if (!VIR_IS_DOMAIN(domain)) {
3448
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3449
        virDispatchError(NULL);
3450
        return -1;
D
Daniel Veillard 已提交
3451
    }
3452
    virCheckNonNullArgGoto(uuid, error);
D
Daniel Veillard 已提交
3453

3454 3455
    memcpy(uuid, &domain->uuid[0], VIR_UUID_BUFLEN);

3456
    return 0;
3457 3458 3459 3460

error:
    virDispatchError(domain->conn);
    return -1;
3461 3462
}

3463

K
Karel Zak 已提交
3464 3465 3466
/**
 * virDomainGetUUIDString:
 * @domain: a domain object
3467
 * @buf: pointer to a VIR_UUID_STRING_BUFLEN bytes array
K
Karel Zak 已提交
3468
 *
3469
 * Get the UUID for a domain as string. For more information about
K
Karel Zak 已提交
3470 3471 3472 3473 3474 3475 3476
 * UUID see RFC4122.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virDomainGetUUIDString(virDomainPtr domain, char *buf)
{
3477
    VIR_DOMAIN_DEBUG(domain, "buf=%p", buf);
3478

3479 3480
    virResetLastError();

K
Karel Zak 已提交
3481
    if (!VIR_IS_DOMAIN(domain)) {
3482
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3483
        virDispatchError(NULL);
3484
        return -1;
K
Karel Zak 已提交
3485
    }
3486
    virCheckNonNullArgGoto(buf, error);
3487

E
Eric Blake 已提交
3488
    virUUIDFormat(domain->uuid, buf);
3489
    return 0;
3490 3491

error:
3492
    virDispatchError(domain->conn);
3493
    return -1;
K
Karel Zak 已提交
3494 3495
}

3496

3497
/**
3498
 * virDomainGetID:
3499 3500 3501 3502 3503 3504 3505
 * @domain: a domain object
 *
 * Get the hypervisor ID number for the domain
 *
 * Returns the domain ID number or (unsigned int) -1 in case of error
 */
unsigned int
3506 3507
virDomainGetID(virDomainPtr domain)
{
3508
    VIR_DOMAIN_DEBUG(domain);
3509

3510 3511
    virResetLastError();

D
Daniel Veillard 已提交
3512
    if (!VIR_IS_DOMAIN(domain)) {
3513
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3514
        virDispatchError(NULL);
3515
        return (unsigned int)-1;
D
Daniel Veillard 已提交
3516
    }
3517
    return domain->id;
3518 3519
}

3520

3521 3522 3523 3524 3525 3526
/**
 * virDomainGetOSType:
 * @domain: a domain object
 *
 * Get the type of domain operation system.
 *
3527 3528
 * Returns the new string or NULL in case of error, the string must be
 *         freed by the caller.
3529 3530
 */
char *
3531 3532
virDomainGetOSType(virDomainPtr domain)
{
3533
    virConnectPtr conn;
3534

3535
    VIR_DOMAIN_DEBUG(domain);
3536

3537 3538 3539
    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3540
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3541
        virDispatchError(NULL);
3542
        return NULL;
D
Daniel Veillard 已提交
3543
    }
3544

3545 3546
    conn = domain->conn;

3547 3548
    if (conn->driver->domainGetOSType) {
        char *ret;
3549
        ret = conn->driver->domainGetOSType(domain);
3550 3551 3552 3553
        if (!ret)
            goto error;
        return ret;
    }
3554

3555
    virReportUnsupportedError();
3556 3557

error:
3558
    virDispatchError(domain->conn);
3559
    return NULL;
3560 3561
}

3562

3563
/**
3564
 * virDomainGetMaxMemory:
3565
 * @domain: a domain object or NULL
3566
 *
3567 3568 3569 3570
 * Retrieve the maximum amount of physical memory allocated to a
 * domain. If domain is NULL, then this get the amount of memory reserved
 * to Domain0 i.e. the domain where the application runs.
 *
3571 3572
 * Returns the memory size in kibibytes (blocks of 1024 bytes), or 0 in
 * case of error.
3573 3574
 */
unsigned long
3575 3576
virDomainGetMaxMemory(virDomainPtr domain)
{
3577
    virConnectPtr conn;
3578

3579
    VIR_DOMAIN_DEBUG(domain);
3580

3581 3582
    virResetLastError();

D
Daniel Veillard 已提交
3583
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3584
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3585
        virDispatchError(NULL);
3586
        return 0;
D
Daniel Veillard 已提交
3587
    }
3588

3589 3590
    conn = domain->conn;

3591
    if (conn->driver->domainGetMaxMemory) {
3592
        unsigned long long ret;
3593
        ret = conn->driver->domainGetMaxMemory(domain);
3594 3595
        if (ret == 0)
            goto error;
3596 3597 3598 3599 3600
        if ((unsigned long) ret != ret) {
            virLibDomainError(VIR_ERR_OVERFLOW, _("result too large: %llu"),
                              ret);
            goto error;
        }
3601 3602
        return ret;
    }
3603

3604
    virReportUnsupportedError();
3605 3606

error:
3607
    virDispatchError(domain->conn);
3608
    return 0;
3609 3610
}

3611

D
Daniel Veillard 已提交
3612
/**
3613
 * virDomainSetMaxMemory:
D
Daniel Veillard 已提交
3614
 * @domain: a domain object or NULL
3615
 * @memory: the memory size in kibibytes (blocks of 1024 bytes)
3616
 *
D
Daniel Veillard 已提交
3617 3618 3619
 * Dynamically change the maximum amount of physical memory allocated to a
 * domain. If domain is NULL, then this change the amount of memory reserved
 * to Domain0 i.e. the domain where the application runs.
3620
 * This function may require privileged access to the hypervisor.
D
Daniel Veillard 已提交
3621
 *
3622 3623 3624
 * This command is hypervisor-specific for whether active, persistent,
 * or both configurations are changed; for more control, use
 * virDomainSetMemoryFlags().
3625
 *
D
Daniel Veillard 已提交
3626 3627 3628
 * Returns 0 in case of success and -1 in case of failure.
 */
int
3629 3630
virDomainSetMaxMemory(virDomainPtr domain, unsigned long memory)
{
3631
    virConnectPtr conn;
3632 3633

    VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory);
3634

3635 3636
    virResetLastError();

3637
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3638
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3639
        virDispatchError(NULL);
3640
        return -1;
3641
    }
3642
    virCheckReadOnlyGoto(domain->conn->flags, error);
3643 3644
    virCheckNonZeroArgGoto(memory, error);

3645
    conn = domain->conn;
3646

3647 3648
    if (conn->driver->domainSetMaxMemory) {
        int ret;
3649
        ret = conn->driver->domainSetMaxMemory(domain, memory);
3650 3651 3652 3653
        if (ret < 0)
            goto error;
        return ret;
    }
3654

3655
    virReportUnsupportedError();
3656 3657

error:
3658
    virDispatchError(domain->conn);
3659
    return -1;
3660
}
3661

3662

3663 3664 3665
/**
 * virDomainSetMemory:
 * @domain: a domain object or NULL
3666
 * @memory: the memory size in kibibytes (blocks of 1024 bytes)
3667
 *
3668 3669 3670
 * Dynamically change the target amount of physical memory allocated to a
 * domain. If domain is NULL, then this change the amount of memory reserved
 * to Domain0 i.e. the domain where the application runs.
3671
 * This function may require privileged access to the hypervisor.
3672
 *
3673 3674 3675
 * This command only changes the runtime configuration of the domain,
 * so can only be called on an active domain.
 *
3676 3677 3678 3679 3680 3681
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainSetMemory(virDomainPtr domain, unsigned long memory)
{
    virConnectPtr conn;
3682 3683

    VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory);
3684

3685 3686
    virResetLastError();

3687
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3688
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3689
        virDispatchError(NULL);
3690
        return -1;
3691
    }
3692
    virCheckReadOnlyGoto(domain->conn->flags, error);
3693
    virCheckNonZeroArgGoto(memory, error);
3694 3695

    conn = domain->conn;
3696

3697 3698
    if (conn->driver->domainSetMemory) {
        int ret;
3699
        ret = conn->driver->domainSetMemory(domain, memory);
3700 3701 3702 3703
        if (ret < 0)
            goto error;
        return ret;
    }
3704

3705
    virReportUnsupportedError();
3706 3707

error:
3708
    virDispatchError(domain->conn);
3709
    return -1;
D
Daniel Veillard 已提交
3710 3711
}

3712

3713
/**
3714
 * virDomainSetMemoryFlags:
3715
 * @domain: a domain object or NULL
3716
 * @memory: the memory size in kibibytes (blocks of 1024 bytes)
3717
 * @flags: bitwise-OR of virDomainMemoryModFlags
3718 3719 3720 3721
 *
 * Dynamically change the target amount of physical memory allocated to a
 * domain. If domain is NULL, then this change the amount of memory reserved
 * to Domain0 i.e. the domain where the application runs.
3722
 * This function may require privileged access to the hypervisor.
3723
 *
3724 3725
 * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
 * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects
3726
 * a running domain and will fail if domain is not active.
3727
 * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
3728
 * and will fail for transient domains. If neither flag is specified
3729
 * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain
3730 3731
 * modifies persistent setup, while an active domain is hypervisor-dependent
 * on whether just live or both live and persistent state is changed.
3732 3733
 * If VIR_DOMAIN_MEM_MAXIMUM is set, the change affects domain's maximum memory
 * size rather than current memory size.
3734
 * Not all hypervisors can support all flag combinations.
3735 3736 3737 3738 3739 3740 3741 3742 3743
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainSetMemoryFlags(virDomainPtr domain, unsigned long memory,
                        unsigned int flags)
{
    virConnectPtr conn;

E
Eric Blake 已提交
3744
    VIR_DOMAIN_DEBUG(domain, "memory=%lu, flags=%x", memory, flags);
3745 3746 3747 3748 3749 3750 3751 3752 3753

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

3754
    virCheckReadOnlyGoto(domain->conn->flags, error);
3755
    virCheckNonZeroArgGoto(memory, error);
3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766

    conn = domain->conn;

    if (conn->driver->domainSetMemoryFlags) {
        int ret;
        ret = conn->driver->domainSetMemoryFlags(domain, memory, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

3767
    virReportUnsupportedError();
3768

3769 3770 3771 3772 3773
error:
    virDispatchError(domain->conn);
    return -1;
}

3774

3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812
/**
 * virDomainSetMemoryStatsPeriod:
 * @domain: a domain object or NULL
 * @period: the period in seconds for stats collection
 * @flags: bitwise-OR of virDomainMemoryModFlags
 *
 * Dynamically change the domain memory balloon driver statistics collection
 * period. Use 0 to disable and a positive value to enable.
 *
 * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
 * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects
 * a running domain and will fail if domain is not active.
 * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
 * and will fail for transient domains. If neither flag is specified
 * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain
 * modifies persistent setup, while an active domain is hypervisor-dependent
 * on whether just live or both live and persistent state is changed.
 *
 * Not all hypervisors can support all flag combinations.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainSetMemoryStatsPeriod(virDomainPtr domain, int period,
                              unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "peroid=%d, flags=%x", period, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

3813
    virCheckReadOnlyGoto(domain->conn->flags, error);
3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827

    /* This must be positive to set the balloon collection period */
    virCheckNonNegativeArgGoto(period, error);

    conn = domain->conn;

    if (conn->driver->domainSetMemoryStatsPeriod) {
        int ret;
        ret = conn->driver->domainSetMemoryStatsPeriod(domain, period, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

3828
    virReportUnsupportedError();
3829 3830 3831 3832 3833 3834

error:
    virDispatchError(domain->conn);
    return -1;
}

3835

E
Eric Blake 已提交
3836 3837 3838
/* Helper function called to validate incoming client array on any
 * interface that sets typed parameters in the hypervisor.  */
static int
3839
virTypedParameterValidateSet(virConnectPtr conn,
E
Eric Blake 已提交
3840 3841 3842 3843
                             virTypedParameterPtr params,
                             int nparams)
{
    bool string_okay;
3844
    size_t i;
E
Eric Blake 已提交
3845

3846 3847
    string_okay = VIR_DRV_SUPPORTS_FEATURE(conn->driver,
                                           conn,
E
Eric Blake 已提交
3848 3849 3850 3851
                                           VIR_DRV_FEATURE_TYPED_PARAM_STRING);
    for (i = 0; i < nparams; i++) {
        if (strnlen(params[i].field, VIR_TYPED_PARAM_FIELD_LENGTH) ==
            VIR_TYPED_PARAM_FIELD_LENGTH) {
3852 3853 3854 3855
            virReportInvalidArg(params,
                                _("string parameter name '%.*s' too long"),
                                VIR_TYPED_PARAM_FIELD_LENGTH,
                                params[i].field);
E
Eric Blake 已提交
3856 3857 3858 3859 3860
            return -1;
        }
        if (params[i].type == VIR_TYPED_PARAM_STRING) {
            if (string_okay) {
                if (!params[i].value.s) {
3861 3862 3863
                    virReportInvalidArg(params,
                                        _("NULL string parameter '%s'"),
                                        params[i].field);
E
Eric Blake 已提交
3864 3865 3866
                    return -1;
                }
            } else {
3867 3868 3869
                virReportInvalidArg(params,
                                    _("string parameter '%s' unsupported"),
                                    params[i].field);
E
Eric Blake 已提交
3870 3871 3872 3873 3874 3875 3876
                return -1;
            }
        }
    }
    return 0;
}

3877

3878 3879 3880 3881
/**
 * virDomainSetMemoryParameters:
 * @domain: pointer to domain object
 * @params: pointer to memory parameter objects
3882
 * @nparams: number of memory parameter (this value can be the same or
3883
 *          less than the number of parameters supported)
3884
 * @flags: bitwise-OR of virDomainModificationImpact
3885
 *
3886
 * Change all or a subset of the memory tunables.
3887
 * This function may require privileged access to the hypervisor.
3888 3889 3890 3891 3892
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainSetMemoryParameters(virDomainPtr domain,
3893
                             virTypedParameterPtr params,
3894 3895 3896
                             int nparams, unsigned int flags)
{
    virConnectPtr conn;
3897

3898
    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x",
3899
                     params, nparams, flags);
3900
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
3901 3902 3903 3904

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3905
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3906 3907 3908
        virDispatchError(NULL);
        return -1;
    }
3909
    virCheckReadOnlyGoto(domain->conn->flags, error);
3910 3911 3912
    virCheckNonNullArgGoto(params, error);
    virCheckPositiveArgGoto(nparams, error);

3913
    if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0)
3914
        goto error;
E
Eric Blake 已提交
3915

3916 3917 3918 3919
    conn = domain->conn;

    if (conn->driver->domainSetMemoryParameters) {
        int ret;
3920
        ret = conn->driver->domainSetMemoryParameters(domain, params, nparams, flags);
3921 3922 3923 3924 3925
        if (ret < 0)
            goto error;
        return ret;
    }

3926
    virReportUnsupportedError();
3927 3928 3929 3930 3931 3932

error:
    virDispatchError(domain->conn);
    return -1;
}

3933

3934 3935 3936 3937 3938
/**
 * virDomainGetMemoryParameters:
 * @domain: pointer to domain object
 * @params: pointer to memory parameter object
 *          (return value, allocated by the caller)
3939
 * @nparams: pointer to number of memory parameters; input and output
E
Eric Blake 已提交
3940
 * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
3941
 *
3942 3943 3944 3945
 * Get all memory parameters.  On input, @nparams gives the size of the
 * @params array; on output, @nparams gives how many slots were filled
 * with parameter information, which might be less but will not exceed
 * the input value.
3946
 *
3947 3948 3949
 * As a special case, calling with @params as NULL and @nparams as 0 on
 * input will cause @nparams on output to contain the number of parameters
 * supported by the hypervisor. The caller should then allocate @params
3950
 * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
3951 3952
 * again.
 *
3953
 * Here is a sample code snippet:
3954
 *
3955 3956
 *   if (virDomainGetMemoryParameters(dom, NULL, &nparams, 0) == 0 &&
 *       nparams != 0) {
3957 3958 3959 3960 3961 3962
 *       if ((params = malloc(sizeof(*params) * nparams)) == NULL)
 *           goto error;
 *       memset(params, 0, sizeof(*params) * nparams);
 *       if (virDomainGetMemoryParameters(dom, params, &nparams, 0))
 *           goto error;
 *   }
3963
 *
3964
 * This function may require privileged access to the hypervisor. This function
3965
 * expects the caller to allocate the @params.
3966 3967 3968 3969 3970
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainGetMemoryParameters(virDomainPtr domain,
3971
                             virTypedParameterPtr params,
3972 3973 3974
                             int *nparams, unsigned int flags)
{
    virConnectPtr conn;
3975

3976
    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x",
3977
                     params, (nparams) ? *nparams : -1, flags);
3978 3979 3980 3981

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
3982
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
3983 3984 3985
        virDispatchError(NULL);
        return -1;
    }
3986 3987 3988 3989 3990
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
    if (*nparams != 0)
        virCheckNonNullArgGoto(params, error);

E
Eric Blake 已提交
3991 3992 3993
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;
3994 3995 3996 3997

    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
3998
        virReportInvalidArg(flags,
3999 4000
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
4001
                            __FUNCTION__);
4002 4003
        goto error;
    }
4004 4005 4006 4007
    conn = domain->conn;

    if (conn->driver->domainGetMemoryParameters) {
        int ret;
4008
        ret = conn->driver->domainGetMemoryParameters(domain, params, nparams, flags);
4009 4010 4011 4012
        if (ret < 0)
            goto error;
        return ret;
    }
4013
    virReportUnsupportedError();
4014 4015 4016 4017 4018 4019

error:
    virDispatchError(domain->conn);
    return -1;
}

4020

4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042
/**
 * virDomainSetNumaParameters:
 * @domain: pointer to domain object
 * @params: pointer to numa parameter objects
 * @nparams: number of numa parameters (this value can be the same or
 *          less than the number of parameters supported)
 * @flags: bitwise-OR of virDomainModificationImpact
 *
 * Change all or a subset of the numa tunables.
 * This function may require privileged access to the hypervisor.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainSetNumaParameters(virDomainPtr domain,
                           virTypedParameterPtr params,
                           int nparams, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x",
                     params, nparams, flags);
4043
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
4044 4045 4046 4047 4048 4049 4050 4051

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
4052
    virCheckReadOnlyGoto(domain->conn->flags, error);
4053 4054
    virCheckNonNullArgGoto(params, error);
    virCheckPositiveArgGoto(nparams, error);
4055
    if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0)
4056
        goto error;
4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068

    conn = domain->conn;

    if (conn->driver->domainSetNumaParameters) {
        int ret;
        ret = conn->driver->domainSetNumaParameters(domain, params, nparams,
                                                    flags);
        if (ret < 0)
            goto error;
        return ret;
    }

4069
    virReportUnsupportedError();
4070 4071 4072 4073 4074 4075

error:
    virDispatchError(domain->conn);
    return -1;
}

4076

4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
/**
 * virDomainGetNumaParameters:
 * @domain: pointer to domain object
 * @params: pointer to numa parameter object
 *          (return value, allocated by the caller)
 * @nparams: pointer to number of numa parameters
 * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
 *
 * Get all numa parameters.  On input, @nparams gives the size of the
 * @params array; on output, @nparams gives how many slots were filled
 * with parameter information, which might be less but will not exceed
 * the input value.
 *
 * As a special case, calling with @params as NULL and @nparams as 0 on
 * input will cause @nparams on output to contain the number of parameters
 * supported by the hypervisor. The caller should then allocate @params
 * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
 * again.
 *
 * See virDomainGetMemoryParameters() for an equivalent usage example.
 *
 * This function may require privileged access to the hypervisor. This function
 * expects the caller to allocate the @params.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainGetNumaParameters(virDomainPtr domain,
                           virTypedParameterPtr params,
                           int *nparams, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x",
                     params, (nparams) ? *nparams : -1, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
4120 4121 4122 4123 4124
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
    if (*nparams != 0)
        virCheckNonNullArgGoto(params, error);

4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;

    conn = domain->conn;

    if (conn->driver->domainGetNumaParameters) {
        int ret;
        ret = conn->driver->domainGetNumaParameters(domain, params, nparams,
                                                    flags);
        if (ret < 0)
            goto error;
        return ret;
    }
4139
    virReportUnsupportedError();
4140 4141 4142 4143 4144 4145

error:
    virDispatchError(domain->conn);
    return -1;
}

4146

4147 4148 4149 4150
/**
 * virDomainSetBlkioParameters:
 * @domain: pointer to domain object
 * @params: pointer to blkio parameter objects
4151
 * @nparams: number of blkio parameters (this value can be the same or
4152
 *          less than the number of parameters supported)
E
Eric Blake 已提交
4153
 * @flags: bitwise-OR of virDomainModificationImpact
4154
 *
4155
 * Change all or a subset of the blkio tunables.
4156
 * This function may require privileged access to the hypervisor.
4157 4158 4159 4160 4161
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainSetBlkioParameters(virDomainPtr domain,
4162 4163
                            virTypedParameterPtr params,
                            int nparams, unsigned int flags)
4164 4165 4166
{
    virConnectPtr conn;

4167
    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x",
4168
                     params, nparams, flags);
4169
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
4170 4171 4172 4173 4174 4175 4176 4177

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
4178
    virCheckReadOnlyGoto(domain->conn->flags, error);
4179 4180 4181
    virCheckNonNullArgGoto(params, error);
    virCheckNonNegativeArgGoto(nparams, error);

4182
    if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0)
4183
        goto error;
E
Eric Blake 已提交
4184

4185 4186 4187 4188
    conn = domain->conn;

    if (conn->driver->domainSetBlkioParameters) {
        int ret;
4189
        ret = conn->driver->domainSetBlkioParameters(domain, params, nparams, flags);
4190 4191 4192 4193 4194
        if (ret < 0)
            goto error;
        return ret;
    }

4195
    virReportUnsupportedError();
4196 4197 4198 4199 4200 4201

error:
    virDispatchError(domain->conn);
    return -1;
}

4202

4203 4204 4205 4206 4207
/**
 * virDomainGetBlkioParameters:
 * @domain: pointer to domain object
 * @params: pointer to blkio parameter object
 *          (return value, allocated by the caller)
4208
 * @nparams: pointer to number of blkio parameters; input and output
E
Eric Blake 已提交
4209
 * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
4210
 *
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222
 * Get all blkio parameters.  On input, @nparams gives the size of the
 * @params array; on output, @nparams gives how many slots were filled
 * with parameter information, which might be less but will not exceed
 * the input value.
 *
 * As a special case, calling with @params as NULL and @nparams as 0 on
 * input will cause @nparams on output to contain the number of parameters
 * supported by the hypervisor. The caller should then allocate @params
 * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
 * again.
 *
 * See virDomainGetMemoryParameters() for an equivalent usage example.
4223
 *
4224
 * This function may require privileged access to the hypervisor. This function
4225 4226 4227 4228 4229 4230
 * expects the caller to allocate the @params.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainGetBlkioParameters(virDomainPtr domain,
4231 4232
                            virTypedParameterPtr params,
                            int *nparams, unsigned int flags)
4233 4234 4235
{
    virConnectPtr conn;

4236
    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x",
4237 4238 4239 4240 4241 4242 4243 4244 4245
                     params, (nparams) ? *nparams : -1, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
4246 4247 4248 4249 4250
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
    if (*nparams != 0)
        virCheckNonNullArgGoto(params, error);

E
Eric Blake 已提交
4251 4252 4253
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;
4254 4255 4256 4257

    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
4258
        virReportInvalidArg(flags,
4259 4260
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
4261
                            __FUNCTION__);
4262 4263
        goto error;
    }
4264 4265 4266 4267
    conn = domain->conn;

    if (conn->driver->domainGetBlkioParameters) {
        int ret;
4268
        ret = conn->driver->domainGetBlkioParameters(domain, params, nparams, flags);
4269 4270 4271 4272
        if (ret < 0)
            goto error;
        return ret;
    }
4273
    virReportUnsupportedError();
4274 4275 4276 4277 4278 4279

error:
    virDispatchError(domain->conn);
    return -1;
}

4280

4281 4282
/**
 * virDomainGetInfo:
4283
 * @domain: a domain object
4284
 * @info: pointer to a virDomainInfo structure allocated by the user
4285
 *
4286
 * Extract information about a domain. Note that if the connection
4287
 * used to get the domain is limited only a partial set of the information
4288 4289 4290 4291 4292
 * can be extracted.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
4293 4294
virDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
{
4295
    virConnectPtr conn;
4296 4297

    VIR_DOMAIN_DEBUG(domain, "info=%p", info);
4298

4299 4300
    virResetLastError();

D
Daniel Veillard 已提交
4301
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
4302
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
4303
        virDispatchError(NULL);
4304
        return -1;
D
Daniel Veillard 已提交
4305
    }
4306
    virCheckNonNullArgGoto(info, error);
4307

4308
    memset(info, 0, sizeof(virDomainInfo));
4309

4310 4311
    conn = domain->conn;

4312 4313
    if (conn->driver->domainGetInfo) {
        int ret;
4314
        ret = conn->driver->domainGetInfo(domain, info);
4315 4316 4317 4318
        if (ret < 0)
            goto error;
        return ret;
    }
4319

4320
    virReportUnsupportedError();
4321 4322

error:
4323
    virDispatchError(domain->conn);
4324
    return -1;
4325
}
4326

4327

4328 4329 4330 4331 4332 4333
/**
 * virDomainGetState:
 * @domain: a domain object
 * @state: returned state of the domain (one of virDomainState)
 * @reason: returned reason which led to @state (one of virDomain*Reason
 * corresponding to the current state); it is allowed to be NULL
4334
 * @flags: extra flags; not used yet, so callers should always pass 0
4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348
 *
 * Extract domain state. Each state can be accompanied with a reason (if known)
 * which led to the state.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainGetState(virDomainPtr domain,
                  int *state,
                  int *reason,
                  unsigned int flags)
{
    virConnectPtr conn;

E
Eric Blake 已提交
4349 4350
    VIR_DOMAIN_DEBUG(domain, "state=%p, reason=%p, flags=%x",
                     state, reason, flags);
4351 4352 4353 4354 4355 4356 4357 4358

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
4359
    virCheckNonNullArgGoto(state, error);
4360 4361 4362 4363 4364 4365

    conn = domain->conn;
    if (conn->driver->domainGetState) {
        int ret;
        ret = conn->driver->domainGetState(domain, state, reason, flags);
        if (ret < 0)
4366 4367 4368 4369
            goto error;
        return ret;
    }

4370
    virReportUnsupportedError();
4371 4372 4373 4374 4375 4376

error:
    virDispatchError(domain->conn);
    return -1;
}

4377

4378 4379 4380 4381
/**
 * virDomainGetControlInfo:
 * @domain: a domain object
 * @info: pointer to a virDomainControlInfo structure allocated by the user
4382
 * @flags: extra flags; not used yet, so callers should always pass 0
4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394
 *
 * Extract details about current state of control interface to a domain.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainGetControlInfo(virDomainPtr domain,
                        virDomainControlInfoPtr info,
                        unsigned int flags)
{
    virConnectPtr conn;

E
Eric Blake 已提交
4395
    VIR_DOMAIN_DEBUG(domain, "info=%p, flags=%x", info, flags);
4396 4397 4398 4399 4400 4401 4402 4403 4404

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

4405
    virCheckNonNullArgGoto(info, error);
4406 4407 4408 4409 4410 4411

    conn = domain->conn;
    if (conn->driver->domainGetControlInfo) {
        int ret;
        ret = conn->driver->domainGetControlInfo(domain, info, flags);
        if (ret < 0)
4412 4413 4414 4415
            goto error;
        return ret;
    }

4416
    virReportUnsupportedError();
4417 4418 4419 4420 4421 4422

error:
    virDispatchError(domain->conn);
    return -1;
}

4423

4424 4425 4426
/**
 * virDomainGetXMLDesc:
 * @domain: a domain object
4427
 * @flags: bitwise-OR of virDomainXMLFlags
4428 4429
 *
 * Provide an XML description of the domain. The description may be reused
4430
 * later to relaunch the domain with virDomainCreateXML().
4431
 *
4432 4433 4434 4435 4436 4437 4438 4439 4440 4441
 * No security-sensitive data will be included unless @flags contains
 * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only
 * connections.  If @flags includes VIR_DOMAIN_XML_INACTIVE, then the
 * XML represents the configuration that will be used on the next boot
 * of a persistent domain; otherwise, the configuration represents the
 * currently running domain.  If @flags contains
 * VIR_DOMAIN_XML_UPDATE_CPU, then the portion of the domain XML
 * describing CPU capabilities is modified to match actual
 * capabilities of the host.
 *
4442 4443 4444 4445
 * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
4446
virDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
4447
{
4448
    virConnectPtr conn;
4449

4450
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
4451

4452 4453 4454
    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
4455
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
4456
        virDispatchError(NULL);
4457
        return NULL;
D
Daniel Veillard 已提交
4458
    }
4459

4460 4461
    conn = domain->conn;

4462
    if ((conn->flags & VIR_CONNECT_RO) && (flags & VIR_DOMAIN_XML_SECURE)) {
4463
        virLibConnError(VIR_ERR_OPERATION_DENIED, "%s",
4464 4465 4466 4467
                        _("virDomainGetXMLDesc with secure flag"));
        goto error;
    }

4468
    if (conn->driver->domainGetXMLDesc) {
4469
        char *ret;
4470
        ret = conn->driver->domainGetXMLDesc(domain, flags);
4471 4472 4473 4474
        if (!ret)
            goto error;
        return ret;
    }
4475

4476
    virReportUnsupportedError();
4477 4478

error:
4479
    virDispatchError(domain->conn);
4480
    return NULL;
4481
}
4482

4483

4484 4485 4486 4487 4488
/**
 * virConnectDomainXMLFromNative:
 * @conn: a connection object
 * @nativeFormat: configuration format importing from
 * @nativeConfig: the configuration data to import
4489
 * @flags: extra flags; not used yet, so callers should always pass 0
4490 4491 4492 4493 4494 4495 4496 4497
 *
 * Reads native configuration data  describing a domain, and
 * generates libvirt domain XML. The format of the native
 * data is hypervisor dependant.
 *
 * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error.
 *         the caller must free() the returned value.
 */
4498 4499 4500 4501 4502
char *
virConnectDomainXMLFromNative(virConnectPtr conn,
                              const char *nativeFormat,
                              const char *nativeConfig,
                              unsigned int flags)
4503
{
E
Eric Blake 已提交
4504
    VIR_DEBUG("conn=%p, format=%s, config=%s, flags=%x",
4505
              conn, nativeFormat, nativeConfig, flags);
4506 4507 4508

    virResetLastError();

4509
    virCheckConnectReturn(conn, NULL);
4510
    virCheckReadOnlyGoto(conn->flags, error);
4511

4512 4513
    virCheckNonNullArgGoto(nativeFormat, error);
    virCheckNonNullArgGoto(nativeConfig, error);
4514

4515
    if (conn->driver->connectDomainXMLFromNative) {
4516
        char *ret;
4517 4518 4519 4520
        ret = conn->driver->connectDomainXMLFromNative(conn,
                                                       nativeFormat,
                                                       nativeConfig,
                                                       flags);
4521 4522 4523 4524 4525
        if (!ret)
            goto error;
        return ret;
    }

4526
    virReportUnsupportedError();
4527 4528

error:
4529
    virDispatchError(conn);
4530 4531 4532
    return NULL;
}

4533

4534 4535 4536 4537 4538
/**
 * virConnectDomainXMLToNative:
 * @conn: a connection object
 * @nativeFormat: configuration format exporting to
 * @domainXml: the domain configuration to export
4539
 * @flags: extra flags; not used yet, so callers should always pass 0
4540 4541
 *
 * Reads a domain XML configuration document, and generates
E
Eric Blake 已提交
4542
 * a native configuration file describing the domain.
4543 4544 4545 4546 4547
 * The format of the native data is hypervisor dependant.
 *
 * Returns a 0 terminated UTF-8 encoded native config datafile, or NULL in case of error.
 *         the caller must free() the returned value.
 */
4548 4549 4550 4551 4552
char *
virConnectDomainXMLToNative(virConnectPtr conn,
                            const char *nativeFormat,
                            const char *domainXml,
                            unsigned int flags)
4553
{
E
Eric Blake 已提交
4554
    VIR_DEBUG("conn=%p, format=%s, xml=%s, flags=%x",
4555
              conn, nativeFormat, domainXml, flags);
4556 4557 4558

    virResetLastError();

4559
    virCheckConnectReturn(conn, NULL);
4560
    virCheckReadOnlyGoto(conn->flags, error);
4561

4562 4563
    virCheckNonNullArgGoto(nativeFormat, error);
    virCheckNonNullArgGoto(domainXml, error);
4564

4565
    if (conn->driver->connectDomainXMLToNative) {
4566
        char *ret;
4567 4568 4569 4570
        ret = conn->driver->connectDomainXMLToNative(conn,
                                                     nativeFormat,
                                                     domainXml,
                                                     flags);
4571 4572 4573 4574 4575
        if (!ret)
            goto error;
        return ret;
    }

4576
    virReportUnsupportedError();
4577 4578

error:
4579
    virDispatchError(conn);
4580 4581 4582 4583
    return NULL;
}


4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599
/*
 * Sequence v1:
 *
 *  Dst: Prepare
 *        - Get ready to accept incoming VM
 *        - Generate optional cookie to pass to src
 *
 *  Src: Perform
 *        - Start migration and wait for send completion
 *        - Kill off VM if successful, resume if failed
 *
 *  Dst: Finish
 *        - Wait for recv completion and check status
 *        - Kill off VM if unsuccessful
 *
 */
4600
static virDomainPtr
4601 4602 4603 4604 4605 4606
virDomainMigrateVersion1(virDomainPtr domain,
                         virConnectPtr dconn,
                         unsigned long flags,
                         const char *dname,
                         const char *uri,
                         unsigned long bandwidth)
4607 4608 4609 4610
{
    virDomainPtr ddomain = NULL;
    char *uri_out = NULL;
    char *cookie = NULL;
4611 4612
    int cookielen = 0, ret;
    virDomainInfo info;
4613
    unsigned int destflags;
4614

4615
    VIR_DOMAIN_DEBUG(domain,
E
Eric Blake 已提交
4616
                     "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu",
4617
                     dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);
4618

4619
    ret = virDomainGetInfo(domain, &info);
4620
    if (ret == 0 && info.state == VIR_DOMAIN_PAUSED)
4621
        flags |= VIR_MIGRATE_PAUSED;
4622 4623

    destflags = flags & ~VIR_MIGRATE_ABORT_ON_ERROR;
4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636

    /* Prepare the migration.
     *
     * The destination host may return a cookie, or leave cookie as
     * NULL.
     *
     * The destination host MUST set uri_out if uri_in is NULL.
     *
     * If uri_in is non-NULL, then the destination host may modify
     * the URI by setting uri_out.  If it does not wish to modify
     * the URI, it should leave uri_out as NULL.
     */
    if (dconn->driver->domainMigratePrepare
4637
        (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname,
4638 4639 4640 4641
         bandwidth) == -1)
        goto done;

    if (uri == NULL && uri_out == NULL) {
4642
        virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663
                         _("domainMigratePrepare did not set uri"));
        goto done;
    }
    if (uri_out)
        uri = uri_out; /* Did domainMigratePrepare change URI? */

    /* Perform the migration.  The driver isn't supposed to return
     * until the migration is complete.
     */
    if (domain->conn->driver->domainMigratePerform
        (domain, cookie, cookielen, uri, flags, dname, bandwidth) == -1)
        goto done;

    /* Get the destination domain and return it or error.
     * 'domain' no longer actually exists at this point
     * (or so we hope), but we still use the object in memory
     * in order to get the name.
     */
    dname = dname ? dname : domain->name;
    if (dconn->driver->domainMigrateFinish)
        ddomain = dconn->driver->domainMigrateFinish
4664
            (dconn, dname, cookie, cookielen, uri, destflags);
4665
    else
4666
        ddomain = virDomainLookupByName(dconn, dname);
4667

4668
done:
4669 4670
    VIR_FREE(uri_out);
    VIR_FREE(cookie);
4671 4672 4673
    return ddomain;
}

4674

4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693
/*
 * Sequence v2:
 *
 *  Src: DumpXML
 *        - Generate XML to pass to dst
 *
 *  Dst: Prepare
 *        - Get ready to accept incoming VM
 *        - Generate optional cookie to pass to src
 *
 *  Src: Perform
 *        - Start migration and wait for send completion
 *        - Kill off VM if successful, resume if failed
 *
 *  Dst: Finish
 *        - Wait for recv completion and check status
 *        - Kill off VM if unsuccessful
 *
 */
4694
static virDomainPtr
4695 4696 4697 4698 4699 4700
virDomainMigrateVersion2(virDomainPtr domain,
                         virConnectPtr dconn,
                         unsigned long flags,
                         const char *dname,
                         const char *uri,
                         unsigned long bandwidth)
4701 4702 4703 4704 4705 4706
{
    virDomainPtr ddomain = NULL;
    char *uri_out = NULL;
    char *cookie = NULL;
    char *dom_xml = NULL;
    int cookielen = 0, ret;
4707
    virDomainInfo info;
4708
    virErrorPtr orig_err = NULL;
4709
    unsigned int getxml_flags = 0;
4710
    int cancelled;
4711
    unsigned long destflags;
4712

4713
    VIR_DOMAIN_DEBUG(domain,
E
Eric Blake 已提交
4714
                     "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu",
4715
                     dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);
4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732

    /* Prepare the migration.
     *
     * The destination host may return a cookie, or leave cookie as
     * NULL.
     *
     * The destination host MUST set uri_out if uri_in is NULL.
     *
     * If uri_in is non-NULL, then the destination host may modify
     * the URI by setting uri_out.  If it does not wish to modify
     * the URI, it should leave uri_out as NULL.
     */

    /* In version 2 of the protocol, the prepare step is slightly
     * different.  We fetch the domain XML of the source domain
     * and pass it to Prepare2.
     */
4733
    if (!domain->conn->driver->domainGetXMLDesc) {
4734
        virLibConnError(VIR_ERR_INTERNAL_ERROR, __FUNCTION__);
4735
        virDispatchError(domain->conn);
4736 4737
        return NULL;
    }
4738 4739 4740 4741 4742 4743 4744 4745 4746

    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_XML_MIGRATABLE)) {
        getxml_flags |= VIR_DOMAIN_XML_MIGRATABLE;
    } else {
        getxml_flags |= VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_UPDATE_CPU;
    }

    dom_xml = domain->conn->driver->domainGetXMLDesc(domain, getxml_flags);
4747 4748 4749
    if (!dom_xml)
        return NULL;

4750
    ret = virDomainGetInfo(domain, &info);
4751
    if (ret == 0 && info.state == VIR_DOMAIN_PAUSED)
4752 4753
        flags |= VIR_MIGRATE_PAUSED;

4754 4755 4756
    destflags = flags & ~VIR_MIGRATE_ABORT_ON_ERROR;

    VIR_DEBUG("Prepare2 %p flags=%lx", dconn, destflags);
4757
    ret = dconn->driver->domainMigratePrepare2
4758
        (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname,
4759
         bandwidth, dom_xml);
4760
    VIR_FREE(dom_xml);
4761 4762 4763 4764
    if (ret == -1)
        goto done;

    if (uri == NULL && uri_out == NULL) {
4765
        virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
4766
                         _("domainMigratePrepare2 did not set uri"));
4767
        virDispatchError(domain->conn);
4768 4769
        cancelled = 1;
        goto finish;
4770 4771 4772 4773 4774 4775 4776
    }
    if (uri_out)
        uri = uri_out; /* Did domainMigratePrepare2 change URI? */

    /* Perform the migration.  The driver isn't supposed to return
     * until the migration is complete.
     */
4777
    VIR_DEBUG("Perform %p", domain->conn);
4778 4779 4780
    ret = domain->conn->driver->domainMigratePerform
        (domain, cookie, cookielen, uri, flags, dname, bandwidth);

4781 4782 4783 4784
    /* Perform failed. Make sure Finish doesn't overwrite the error */
    if (ret < 0)
        orig_err = virSaveLastError();

4785 4786 4787 4788 4789 4790
    /* If Perform returns < 0, then we need to cancel the VM
     * startup on the destination
     */
    cancelled = ret < 0 ? 1 : 0;

finish:
4791 4792 4793 4794 4795
    /* In version 2 of the migration protocol, we pass the
     * status code from the sender to the destination host,
     * so it can do any cleanup if the migration failed.
     */
    dname = dname ? dname : domain->name;
4796
    VIR_DEBUG("Finish2 %p ret=%d", dconn, ret);
4797
    ddomain = dconn->driver->domainMigrateFinish2
4798
        (dconn, dname, cookie, cookielen, uri, destflags, cancelled);
4799

4800
done:
4801 4802 4803 4804
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
4805 4806
    VIR_FREE(uri_out);
    VIR_FREE(cookie);
4807 4808 4809
    return ddomain;
}

4810

4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833
/*
 * Sequence v3:
 *
 *  Src: Begin
 *        - Generate XML to pass to dst
 *        - Generate optional cookie to pass to dst
 *
 *  Dst: Prepare
 *        - Get ready to accept incoming VM
 *        - Generate optional cookie to pass to src
 *
 *  Src: Perform
 *        - Start migration and wait for send completion
 *        - Generate optional cookie to pass to dst
 *
 *  Dst: Finish
 *        - Wait for recv completion and check status
 *        - Kill off VM if failed, resume if success
 *        - Generate optional cookie to pass to src
 *
 *  Src: Confirm
 *        - Kill off VM if success, resume if failed
 *
4834 4835 4836 4837
  * If useParams is true, params and nparams contain migration parameters and
  * we know it's safe to call the API which supports extensible parameters.
  * Otherwise, we have to use xmlin, dname, uri, and bandwidth and pass them
  * to the old-style APIs.
4838 4839
 */
static virDomainPtr
4840 4841 4842 4843 4844 4845 4846 4847 4848 4849
virDomainMigrateVersion3Full(virDomainPtr domain,
                             virConnectPtr dconn,
                             const char *xmlin,
                             const char *dname,
                             const char *uri,
                             unsigned long long bandwidth,
                             virTypedParameterPtr params,
                             int nparams,
                             bool useParams,
                             unsigned int flags)
4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860
{
    virDomainPtr ddomain = NULL;
    char *uri_out = NULL;
    char *cookiein = NULL;
    char *cookieout = NULL;
    char *dom_xml = NULL;
    int cookieinlen = 0;
    int cookieoutlen = 0;
    int ret;
    virDomainInfo info;
    virErrorPtr orig_err = NULL;
4861 4862
    int cancelled = 1;
    unsigned long protection = 0;
4863
    bool notify_source = true;
4864
    unsigned int destflags;
4865 4866
    int state;
    virTypedParameterPtr tmp;
4867

4868 4869 4870 4871 4872 4873
    VIR_DOMAIN_DEBUG(domain,
                     "dconn=%p, xmlin=%s, dname=%s, uri=%s, bandwidth=%llu, "
                     "params=%p, nparams=%d, useParams=%d, flags=%x",
                     dconn, NULLSTR(xmlin), NULLSTR(dname), NULLSTR(uri),
                     bandwidth, params, nparams, useParams, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
4874

4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886
    if ((!useParams &&
         (!domain->conn->driver->domainMigrateBegin3 ||
          !domain->conn->driver->domainMigratePerform3 ||
          !domain->conn->driver->domainMigrateConfirm3 ||
          !dconn->driver->domainMigratePrepare3 ||
          !dconn->driver->domainMigrateFinish3)) ||
        (useParams &&
         (!domain->conn->driver->domainMigrateBegin3Params ||
          !domain->conn->driver->domainMigratePerform3Params ||
          !domain->conn->driver->domainMigrateConfirm3Params ||
          !dconn->driver->domainMigratePrepare3Params ||
          !dconn->driver->domainMigrateFinish3Params))) {
4887 4888 4889 4890
        virLibConnError(VIR_ERR_INTERNAL_ERROR, __FUNCTION__);
        return NULL;
    }

4891 4892 4893 4894
    if (virTypedParamsCopy(&tmp, params, nparams) < 0)
        return NULL;
    params = tmp;

4895 4896 4897 4898
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION))
        protection = VIR_MIGRATE_CHANGE_PROTECTION;

4899
    VIR_DEBUG("Begin3 %p", domain->conn);
4900 4901 4902 4903 4904 4905 4906 4907 4908
    if (useParams) {
        dom_xml = domain->conn->driver->domainMigrateBegin3Params
            (domain, params, nparams, &cookieout, &cookieoutlen,
             flags | protection);
    } else {
        dom_xml = domain->conn->driver->domainMigrateBegin3
            (domain, xmlin, &cookieout, &cookieoutlen,
             flags | protection, dname, bandwidth);
    }
4909 4910 4911
    if (!dom_xml)
        goto done;

4912 4913 4914 4915 4916 4917 4918
    if (useParams) {
        /* If source is new enough to support extensible migration parameters,
         * it's certainly new enough to support virDomainGetState. */
        ret = virDomainGetState(domain, &state, NULL, 0);
    } else {
        ret = virDomainGetInfo(domain, &info);
        state = info.state;
4919
    }
4920 4921
    if (ret == 0 && state == VIR_DOMAIN_PAUSED)
        flags |= VIR_MIGRATE_PAUSED;
4922

4923 4924 4925
    destflags = flags & ~VIR_MIGRATE_ABORT_ON_ERROR;

    VIR_DEBUG("Prepare3 %p flags=%x", dconn, destflags);
4926 4927 4928 4929
    cookiein = cookieout;
    cookieinlen = cookieoutlen;
    cookieout = NULL;
    cookieoutlen = 0;
4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942
    if (useParams) {
        if (virTypedParamsReplaceString(&params, &nparams,
                                        VIR_MIGRATE_PARAM_DEST_XML,
                                        dom_xml) < 0)
            goto done;
        ret = dconn->driver->domainMigratePrepare3Params
            (dconn, params, nparams, cookiein, cookieinlen,
             &cookieout, &cookieoutlen, &uri_out, destflags);
    } else {
        ret = dconn->driver->domainMigratePrepare3
            (dconn, cookiein, cookieinlen, &cookieout, &cookieoutlen,
             uri, &uri_out, destflags, dname, bandwidth, dom_xml);
    }
4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953
    if (ret == -1) {
        if (protection) {
            /* Begin already started a migration job so we need to cancel it by
             * calling Confirm while making sure it doesn't overwrite the error
             */
            orig_err = virSaveLastError();
            goto confirm;
        } else {
            goto done;
        }
    }
4954

4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965
    /* Did domainMigratePrepare3 change URI? */
    if (uri_out) {
        uri = uri_out;
        if (useParams &&
            virTypedParamsReplaceString(&params, &nparams,
                                        VIR_MIGRATE_PARAM_URI,
                                        uri_out) < 0)
            goto finish;
    } else if (!uri &&
               virTypedParamsGetString(params, nparams,
                                       VIR_MIGRATE_PARAM_URI, &uri) <= 0) {
4966
        virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
4967 4968 4969
                        _("domainMigratePrepare3 did not set uri"));
    }

L
liguang 已提交
4970 4971 4972 4973 4974 4975 4976 4977
    if (flags & VIR_MIGRATE_OFFLINE) {
        VIR_DEBUG("Offline migration, skipping Perform phase");
        VIR_FREE(cookieout);
        cookieoutlen = 0;
        cancelled = 0;
        goto finish;
    }

4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988
    /* Perform the migration.  The driver isn't supposed to return
     * until the migration is complete. The src VM should remain
     * running, but in paused state until the destination can
     * confirm migration completion.
     */
    VIR_DEBUG("Perform3 %p uri=%s", domain->conn, uri);
    VIR_FREE(cookiein);
    cookiein = cookieout;
    cookieinlen = cookieoutlen;
    cookieout = NULL;
    cookieoutlen = 0;
4989
    /* dconnuri not relevant in non-P2P modes, so left NULL here */
4990 4991 4992 4993 4994 4995 4996 4997 4998 4999
    if (useParams) {
        ret = domain->conn->driver->domainMigratePerform3Params
            (domain, NULL, params, nparams, cookiein, cookieinlen,
             &cookieout, &cookieoutlen, flags | protection);
    } else {
        ret = domain->conn->driver->domainMigratePerform3
            (domain, NULL, cookiein, cookieinlen,
             &cookieout, &cookieoutlen, NULL,
             uri, flags | protection, dname, bandwidth);
    }
5000 5001

    /* Perform failed. Make sure Finish doesn't overwrite the error */
5002
    if (ret < 0) {
5003
        orig_err = virSaveLastError();
5004 5005 5006 5007 5008
        /* Perform failed so we don't need to call confirm to let source know
         * about the failure.
         */
        notify_source = false;
    }
5009 5010 5011 5012 5013 5014

    /* If Perform returns < 0, then we need to cancel the VM
     * startup on the destination
     */
    cancelled = ret < 0 ? 1 : 0;

5015
finish:
5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027
    /*
     * The status code from the source is passed to the destination.
     * The dest can cleanup if the source indicated it failed to
     * send all migration data. Returns NULL for ddomain if
     * the dest was unable to complete migration.
     */
    VIR_DEBUG("Finish3 %p ret=%d", dconn, ret);
    VIR_FREE(cookiein);
    cookiein = cookieout;
    cookieinlen = cookieoutlen;
    cookieout = NULL;
    cookieoutlen = 0;
5028 5029 5030 5031 5032 5033
    if (useParams) {
        if (virTypedParamsGetString(params, nparams,
                                    VIR_MIGRATE_PARAM_DEST_NAME, NULL) <= 0 &&
            virTypedParamsReplaceString(&params, &nparams,
                                        VIR_MIGRATE_PARAM_DEST_NAME,
                                        domain->name) < 0) {
5034
            ddomain = NULL;
5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045
        } else {
            ddomain = dconn->driver->domainMigrateFinish3Params
                (dconn, params, nparams, cookiein, cookieinlen,
                 &cookieout, &cookieoutlen, destflags, cancelled);
        }
    } else {
        dname = dname ? dname : domain->name;
        ddomain = dconn->driver->domainMigrateFinish3
            (dconn, dname, cookiein, cookieinlen, &cookieout, &cookieoutlen,
             NULL, uri, destflags, cancelled);
    }
5046 5047 5048 5049 5050 5051 5052 5053

    /* If ddomain is NULL, then we were unable to start
     * the guest on the target, and must restart on the
     * source. There is a small chance that the ddomain
     * is NULL due to an RPC failure, in which case
     * ddomain could in fact be running on the dest.
     * The lock manager plugins should take care of
     * safety in this scenario.
5054
     */
5055
    cancelled = ddomain == NULL ? 1 : 0;
5056

5057 5058 5059 5060 5061 5062
    /* If finish3 set an error, and we don't have an earlier
     * one we need to preserve it in case confirm3 overwrites
     */
    if (!orig_err)
        orig_err = virSaveLastError();

5063
confirm:
5064
    /*
5065 5066 5067
     * If cancelled, then src VM will be restarted, else it will be killed.
     * Don't do this if migration failed on source and thus it was already
     * cancelled there.
5068
     */
5069 5070 5071 5072 5073 5074 5075
    if (notify_source) {
        VIR_DEBUG("Confirm3 %p ret=%d domain=%p", domain->conn, ret, domain);
        VIR_FREE(cookiein);
        cookiein = cookieout;
        cookieinlen = cookieoutlen;
        cookieout = NULL;
        cookieoutlen = 0;
5076 5077 5078 5079 5080 5081 5082 5083 5084
        if (useParams) {
            ret = domain->conn->driver->domainMigrateConfirm3Params
                (domain, params, nparams, cookiein, cookieinlen,
                 flags | protection, cancelled);
        } else {
            ret = domain->conn->driver->domainMigrateConfirm3
                (domain, cookiein, cookieinlen,
                 flags | protection, cancelled);
        }
5085 5086 5087 5088 5089 5090 5091 5092 5093
        /* If Confirm3 returns -1, there's nothing more we can
         * do, but fortunately worst case is that there is a
         * domain left in 'paused' state on source.
         */
        if (ret < 0) {
            VIR_WARN("Guest %s probably left in 'paused' state on source",
                     domain->name);
        }
    }
5094

5095
done:
5096 5097 5098 5099
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
5100
    VIR_FREE(dom_xml);
5101 5102 5103
    VIR_FREE(uri_out);
    VIR_FREE(cookiein);
    VIR_FREE(cookieout);
5104
    virTypedParamsFree(params, nparams);
5105 5106 5107
    return ddomain;
}

5108

5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121
static virDomainPtr
virDomainMigrateVersion3(virDomainPtr domain,
                         virConnectPtr dconn,
                         const char *xmlin,
                         unsigned long flags,
                         const char *dname,
                         const char *uri,
                         unsigned long bandwidth)
{
    return virDomainMigrateVersion3Full(domain, dconn, xmlin, dname, uri,
                                        bandwidth, NULL, 0, false, flags);
}

5122

J
Jiri Denemark 已提交
5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133
static virDomainPtr
virDomainMigrateVersion3Params(virDomainPtr domain,
                               virConnectPtr dconn,
                               virTypedParameterPtr params,
                               int nparams,
                               unsigned int flags)
{
    return virDomainMigrateVersion3Full(domain, dconn, NULL, NULL, NULL, 0,
                                        params, nparams, true, flags);
}

5134

5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148
/*
 * In normal migration, the libvirt client co-ordinates communication
 * between the 2 libvirtd instances on source & dest hosts.
 *
 * In this peer-2-peer migration alternative, the libvirt client
 * only talks to the source libvirtd instance. The source libvirtd
 * then opens its own connection to the destination and co-ordinates
 * migration itself.
 *
 * If useParams is true, params and nparams contain migration parameters and
 * we know it's safe to call the API which supports extensible parameters.
 * Otherwise, we have to use xmlin, dname, uri, and bandwidth and pass them
 * to the old-style APIs.
 */
5149
static int
5150 5151 5152 5153 5154 5155 5156 5157 5158 5159
virDomainMigratePeer2PeerFull(virDomainPtr domain,
                              const char *dconnuri,
                              const char *xmlin,
                              const char *dname,
                              const char *uri,
                              unsigned long long bandwidth,
                              virTypedParameterPtr params,
                              int nparams,
                              bool useParams,
                              unsigned int flags)
5160
{
M
Martin Kletzander 已提交
5161
    virURIPtr tempuri = NULL;
5162

5163 5164 5165 5166 5167 5168
    VIR_DOMAIN_DEBUG(domain,
                     "dconnuri=%s, xmlin=%s, dname=%s, uri=%s, bandwidth=%llu "
                     "params=%p, nparams=%d, useParams=%d, flags=%x",
                     dconnuri, NULLSTR(xmlin), NULLSTR(dname), NULLSTR(uri),
                     bandwidth, params, nparams, useParams, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
5169

5170 5171 5172 5173 5174
    if ((useParams && !domain->conn->driver->domainMigratePerform3Params) ||
        (!useParams &&
         !domain->conn->driver->domainMigratePerform &&
         !domain->conn->driver->domainMigratePerform3)) {
        virLibConnError(VIR_ERR_INTERNAL_ERROR, __FUNCTION__);
5175 5176 5177
        return -1;
    }

5178
    if (!(tempuri = virURIParse(dconnuri)))
5179
        return -1;
5180
    if (!tempuri->server || STRPREFIX(tempuri->server, "localhost")) {
5181 5182 5183
        virReportInvalidArg(dconnuri,
                            _("unable to parse server from dconnuri in %s"),
                            __FUNCTION__);
5184
        virURIFree(tempuri);
5185 5186
        return -1;
    }
5187
    virURIFree(tempuri);
5188

5189 5190 5191 5192 5193 5194 5195
    if (useParams) {
        VIR_DEBUG("Using migration protocol 3 with extensible parameters");
        return domain->conn->driver->domainMigratePerform3Params
                (domain, dconnuri, params, nparams,
                 NULL, 0, NULL, NULL, flags);
    } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                        VIR_DRV_FEATURE_MIGRATION_V3)) {
5196
        VIR_DEBUG("Using migration protocol 3");
5197 5198 5199
        return domain->conn->driver->domainMigratePerform3
                (domain, xmlin, NULL, 0, NULL, NULL, dconnuri,
                 uri, flags, dname, bandwidth);
5200 5201
    } else {
        VIR_DEBUG("Using migration protocol 2");
5202
        if (xmlin) {
5203 5204 5205
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("Unable to change target guest XML "
                              "during migration"));
5206 5207
            return -1;
        }
5208 5209 5210 5211 5212
        if (uri) {
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("Unable to override peer2peer migration URI"));
            return -1;
        }
5213 5214
        return domain->conn->driver->domainMigratePerform
                (domain, NULL, 0, dconnuri, flags, dname, bandwidth);
5215
    }
5216 5217
}

5218

5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231
static int
virDomainMigratePeer2Peer(virDomainPtr domain,
                          const char *xmlin,
                          unsigned long flags,
                          const char *dname,
                          const char *dconnuri,
                          const char *uri,
                          unsigned long bandwidth)
{
    return virDomainMigratePeer2PeerFull(domain, dconnuri, xmlin, dname, uri,
                                         bandwidth, NULL, 0, false, flags);
}

5232

J
Jiri Denemark 已提交
5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243
static int
virDomainMigratePeer2PeerParams(virDomainPtr domain,
                                const char *dconnuri,
                                virTypedParameterPtr params,
                                int nparams,
                                unsigned int flags)
{
    return virDomainMigratePeer2PeerFull(domain, dconnuri, NULL, NULL, NULL, 0,
                                         params, nparams, true, flags);
}

5244

C
Chris Lalancette 已提交
5245
/*
5246
 * In normal migration, the libvirt client co-ordinates communication
5247
 * between the 2 libvirtd instances on source & dest hosts.
C
Chris Lalancette 已提交
5248
 *
5249 5250 5251
 * Some hypervisors support an alternative, direct migration where
 * there is no requirement for a libvirtd instance on the dest host.
 * In this case
5252
 *
5253 5254
 * eg, XenD can talk direct to XenD, so libvirtd on dest does not
 * need to be involved at all, or even running
C
Chris Lalancette 已提交
5255
 */
5256
static int
5257 5258 5259 5260 5261 5262
virDomainMigrateDirect(virDomainPtr domain,
                       const char *xmlin,
                       unsigned long flags,
                       const char *dname,
                       const char *uri,
                       unsigned long bandwidth)
5263
{
5264 5265 5266 5267
    VIR_DOMAIN_DEBUG(domain,
                     "xmlin=%s, flags=%lx, dname=%s, uri=%s, bandwidth=%lu",
                     NULLSTR(xmlin), flags, NULLSTR(dname), NULLSTR(uri),
                     bandwidth);
5268

5269
    if (!domain->conn->driver->domainMigratePerform) {
5270
        virReportUnsupportedError();
5271
        virDispatchError(domain->conn);
5272 5273 5274
        return -1;
    }

C
Chris Lalancette 已提交
5275 5276 5277
    /* Perform the migration.  The driver isn't supposed to return
     * until the migration is complete.
     */
5278 5279 5280
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_MIGRATION_V3)) {
        VIR_DEBUG("Using migration protocol 3");
5281 5282
        /* dconn URI not relevant in direct migration, since no
         * target libvirtd is involved */
5283
        return domain->conn->driver->domainMigratePerform3(domain,
5284
                                                           xmlin,
5285 5286 5287 5288
                                                           NULL, /* cookiein */
                                                           0,    /* cookieinlen */
                                                           NULL, /* cookieoutlen */
                                                           NULL, /* cookieoutlen */
5289
                                                           NULL, /* dconnuri */
5290 5291 5292 5293 5294 5295
                                                           uri,
                                                           flags,
                                                           dname,
                                                           bandwidth);
    } else {
        VIR_DEBUG("Using migration protocol 2");
5296 5297 5298 5299 5300
        if (xmlin) {
            virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("Unable to change target guest XML during migration"));
            return -1;
        }
5301 5302 5303 5304 5305 5306 5307 5308
        return domain->conn->driver->domainMigratePerform(domain,
                                                          NULL, /* cookie */
                                                          0,    /* cookielen */
                                                          uri,
                                                          flags,
                                                          dname,
                                                          bandwidth);
    }
C
Chris Lalancette 已提交
5309 5310
}

5311

5312 5313 5314 5315
/**
 * virDomainMigrate:
 * @domain: a domain object
 * @dconn: destination host (a connection object)
5316
 * @flags: bitwise-OR of virDomainMigrateFlags
5317 5318
 * @dname: (optional) rename domain to this at destination
 * @uri: (optional) dest hostname/URI as seen from the source host
5319
 * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
5320 5321 5322 5323 5324
 *
 * Migrate the domain object from its current host to the destination
 * host given by dconn (a connection to the destination host).
 *
 * Flags may be one of more of the following:
5325 5326 5327
 *   VIR_MIGRATE_LIVE      Do not pause the VM during migration
 *   VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts
 *   VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel
C
Chris Lalancette 已提交
5328 5329 5330 5331
 *   VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain
 *                            on the destination host.
 *   VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the
 *                               domain on the source host.
5332
 *   VIR_MIGRATE_PAUSED    Leave the domain suspended on the remote side.
5333 5334 5335 5336
 *   VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full
 *                               disk copy
 *   VIR_MIGRATE_NON_SHARED_INC  Migration with non-shared storage with
 *                               incremental disk copy
5337 5338 5339
 *   VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration
 *                                 changes during the migration process (set
 *                                 automatically when supported).
J
Jiri Denemark 已提交
5340
 *   VIR_MIGRATE_UNSAFE    Force migration even if it is considered unsafe.
5341
 *   VIR_MIGRATE_OFFLINE Migrate offline
5342 5343 5344 5345 5346
 *
 * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set.
 * Applications using the VIR_MIGRATE_PEER2PEER flag will probably
 * prefer to invoke virDomainMigrateToURI, avoiding the need to
 * open connection to the destination host themselves.
5347 5348 5349 5350 5351 5352
 *
 * If a hypervisor supports renaming domains during migration,
 * then you may set the dname parameter to the new name (otherwise
 * it keeps the same name).  If this is not supported by the
 * hypervisor, dname must be NULL or else you will get an error.
 *
5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363
 * If the VIR_MIGRATE_PEER2PEER flag is set, the uri parameter
 * must be a valid libvirt connection URI, by which the source
 * libvirt driver can connect to the destination libvirt. If
 * omitted, the dconn connection object will be queried for its
 * current URI.
 *
 * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the URI parameter
 * takes a hypervisor specific format. The hypervisor capabilities
 * XML includes details of the support URI schemes. If omitted
 * the dconn will be asked for a default URI.
 *
5364 5365 5366 5367
 * If you want to copy non-shared storage within migration you
 * can use either VIR_MIGRATE_NON_SHARED_DISK or
 * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive.
 *
5368
 * In either case it is typically only necessary to specify a
5369 5370
 * URI if the destination host has multiple interfaces and a
 * specific interface is required to transmit migration data.
5371
 *
5372
 * The maximum bandwidth (in MiB/s) that will be used to do migration
5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390
 * can be specified with the bandwidth parameter.  If set to 0,
 * libvirt will choose a suitable default.  Some hypervisors do
 * not support this feature and will return an error if bandwidth
 * is not 0.
 *
 * To see which features are supported by the current hypervisor,
 * see virConnectGetCapabilities, /capabilities/host/migration_features.
 *
 * There are many limitations on migration imposed by the underlying
 * technology - for example it may not be possible to migrate between
 * different processors even with the same architecture, or between
 * different types of hypervisor.
 *
 * Returns the new domain object if the migration was successful,
 *   or NULL in case of error.  Note that the new domain object
 *   exists in the scope of the destination connection (dconn).
 */
virDomainPtr
5391 5392 5393 5394 5395 5396
virDomainMigrate(virDomainPtr domain,
                 virConnectPtr dconn,
                 unsigned long flags,
                 const char *dname,
                 const char *uri,
                 unsigned long bandwidth)
5397 5398
{
    virDomainPtr ddomain = NULL;
5399

5400 5401
    VIR_DOMAIN_DEBUG(domain,
                     "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu",
5402
                     dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);
5403

5404 5405
    virResetLastError();

5406
    /* First checkout the source */
5407
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
5408
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
5409
        virDispatchError(NULL);
5410 5411
        return NULL;
    }
5412
    virCheckReadOnlyGoto(domain->conn->flags, error);
5413

5414
    /* Now checkout the destination */
5415
    virCheckConnectGoto(dconn, error);
5416
    virCheckReadOnlyGoto(dconn->flags, error);
5417

5418 5419 5420 5421 5422 5423 5424 5425 5426
    if (flags & VIR_MIGRATE_NON_SHARED_DISK &&
        flags & VIR_MIGRATE_NON_SHARED_INC) {
        virReportInvalidArg(flags,
                            _("flags 'shared disk' and 'shared incremental' "
                              "in %s are mutually exclusive"),
                            __FUNCTION__);
        goto error;
    }

L
liguang 已提交
5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443
    if (flags & VIR_MIGRATE_OFFLINE) {
        if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                      VIR_DRV_FEATURE_MIGRATION_OFFLINE)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("offline migration is not supported by "
                              "the source host"));
            goto error;
        }
        if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                      VIR_DRV_FEATURE_MIGRATION_OFFLINE)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("offline migration is not supported by "
                              "the destination host"));
            goto error;
        }
    }

5444
    if (flags & VIR_MIGRATE_PEER2PEER) {
5445 5446
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_P2P)) {
5447 5448 5449
            char *dstURI = NULL;
            if (uri == NULL) {
                dstURI = virConnectGetURI(dconn);
5450
                if (!dstURI)
5451 5452
                    return NULL;
            }
5453

5454
            VIR_DEBUG("Using peer2peer migration");
5455
            if (virDomainMigratePeer2Peer(domain, NULL, flags, dname,
5456
                                          uri ? uri : dstURI, NULL, bandwidth) < 0) {
5457 5458 5459 5460
                VIR_FREE(dstURI);
                goto error;
            }
            VIR_FREE(dstURI);
C
Chris Lalancette 已提交
5461

5462
            ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name);
5463 5464
        } else {
            /* This driver does not support peer to peer migration */
5465
            virReportUnsupportedError();
5466 5467
            goto error;
        }
5468
    } else {
5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481
        /* Change protection requires support only on source side, and
         * is only needed in v3 migration, which automatically re-adds
         * the flag for just the source side.  We mask it out for
         * non-peer2peer to allow migration from newer source to an
         * older destination that rejects the flag.  */
        if (flags & VIR_MIGRATE_CHANGE_PROTECTION &&
            !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                      VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("cannot enforce change protection"));
            goto error;
        }
        flags &= ~VIR_MIGRATE_CHANGE_PROTECTION;
5482
        if (flags & VIR_MIGRATE_TUNNELLED) {
5483
            virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
5484 5485 5486 5487
                            _("cannot perform tunnelled migration without using peer2peer flag"));
            goto error;
        }

C
Chris Lalancette 已提交
5488 5489
        /* Check that migration is supported by both drivers. */
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
5490
                                     VIR_DRV_FEATURE_MIGRATION_V3) &&
C
Chris Lalancette 已提交
5491
            VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
5492 5493
                                     VIR_DRV_FEATURE_MIGRATION_V3)) {
            VIR_DEBUG("Using migration protocol 3");
5494 5495
            ddomain = virDomainMigrateVersion3(domain, dconn, NULL,
                                               flags, dname, uri, bandwidth);
5496 5497 5498 5499 5500
        } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                            VIR_DRV_FEATURE_MIGRATION_V2) &&
                   VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                          VIR_DRV_FEATURE_MIGRATION_V2)) {
            VIR_DEBUG("Using migration protocol 2");
5501 5502
            ddomain = virDomainMigrateVersion2(domain, dconn, flags,
                                               dname, uri, bandwidth);
5503 5504 5505 5506 5507
        } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                            VIR_DRV_FEATURE_MIGRATION_V1) &&
                   VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                            VIR_DRV_FEATURE_MIGRATION_V1)) {
            VIR_DEBUG("Using migration protocol 1");
5508 5509 5510 5511
            ddomain = virDomainMigrateVersion1(domain, dconn, flags,
                                               dname, uri, bandwidth);
        } else {
            /* This driver does not support any migration method */
5512
            virReportUnsupportedError();
5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531
            goto error;
        }
    }

    if (ddomain == NULL)
        goto error;

    return ddomain;

error:
    virDispatchError(domain->conn);
    return NULL;
}


/**
 * virDomainMigrate2:
 * @domain: a domain object
 * @dconn: destination host (a connection object)
5532
 * @flags: bitwise-OR of virDomainMigrateFlags
5533 5534 5535
 * @dxml: (optional) XML config for launching guest on target
 * @dname: (optional) rename domain to this at destination
 * @uri: (optional) dest hostname/URI as seen from the source host
5536
 * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549
 *
 * Migrate the domain object from its current host to the destination
 * host given by dconn (a connection to the destination host).
 *
 * Flags may be one of more of the following:
 *   VIR_MIGRATE_LIVE      Do not pause the VM during migration
 *   VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts
 *   VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel
 *   VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain
 *                            on the destination host.
 *   VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the
 *                               domain on the source host.
 *   VIR_MIGRATE_PAUSED    Leave the domain suspended on the remote side.
5550 5551 5552 5553
 *   VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full
 *                               disk copy
 *   VIR_MIGRATE_NON_SHARED_INC  Migration with non-shared storage with
 *                               incremental disk copy
5554 5555 5556
 *   VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration
 *                                 changes during the migration process (set
 *                                 automatically when supported).
J
Jiri Denemark 已提交
5557
 *   VIR_MIGRATE_UNSAFE    Force migration even if it is considered unsafe.
5558
 *   VIR_MIGRATE_OFFLINE Migrate offline
5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580
 *
 * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set.
 * Applications using the VIR_MIGRATE_PEER2PEER flag will probably
 * prefer to invoke virDomainMigrateToURI, avoiding the need to
 * open connection to the destination host themselves.
 *
 * If a hypervisor supports renaming domains during migration,
 * then you may set the dname parameter to the new name (otherwise
 * it keeps the same name).  If this is not supported by the
 * hypervisor, dname must be NULL or else you will get an error.
 *
 * If the VIR_MIGRATE_PEER2PEER flag is set, the uri parameter
 * must be a valid libvirt connection URI, by which the source
 * libvirt driver can connect to the destination libvirt. If
 * omitted, the dconn connection object will be queried for its
 * current URI.
 *
 * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the URI parameter
 * takes a hypervisor specific format. The hypervisor capabilities
 * XML includes details of the support URI schemes. If omitted
 * the dconn will be asked for a default URI.
 *
5581 5582 5583 5584
 * If you want to copy non-shared storage within migration you
 * can use either VIR_MIGRATE_NON_SHARED_DISK or
 * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive.
 *
5585 5586 5587 5588
 * In either case it is typically only necessary to specify a
 * URI if the destination host has multiple interfaces and a
 * specific interface is required to transmit migration data.
 *
5589
 * The maximum bandwidth (in MiB/s) that will be used to do migration
5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602
 * can be specified with the bandwidth parameter.  If set to 0,
 * libvirt will choose a suitable default.  Some hypervisors do
 * not support this feature and will return an error if bandwidth
 * is not 0.
 *
 * To see which features are supported by the current hypervisor,
 * see virConnectGetCapabilities, /capabilities/host/migration_features.
 *
 * There are many limitations on migration imposed by the underlying
 * technology - for example it may not be possible to migrate between
 * different processors even with the same architecture, or between
 * different types of hypervisor.
 *
5603 5604 5605 5606 5607 5608 5609 5610
 * If the hypervisor supports it, @dxml can be used to alter
 * host-specific portions of the domain XML that will be used on
 * the destination.  For example, it is possible to alter the
 * backing filename that is associated with a disk device, in order
 * to account for naming differences between source and destination
 * in accessing the underlying storage.  The migration will fail
 * if @dxml would cause any guest-visible changes.  Pass NULL
 * if no changes are needed to the XML between source and destination.
5611
 * @dxml cannot be used to rename the domain during migration (use
5612 5613
 * @dname for that purpose).  Domain name in @dxml must match the
 * original domain name.
5614
 *
5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629
 * Returns the new domain object if the migration was successful,
 *   or NULL in case of error.  Note that the new domain object
 *   exists in the scope of the destination connection (dconn).
 */
virDomainPtr
virDomainMigrate2(virDomainPtr domain,
                  virConnectPtr dconn,
                  const char *dxml,
                  unsigned long flags,
                  const char *dname,
                  const char *uri,
                  unsigned long bandwidth)
{
    virDomainPtr ddomain = NULL;

5630 5631
    VIR_DOMAIN_DEBUG(domain,
                     "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu",
5632 5633 5634 5635 5636
                     dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);

    virResetLastError();

    /* First checkout the source */
5637
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
5638 5639 5640 5641
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
5642
    virCheckReadOnlyGoto(domain->conn->flags, error);
5643 5644

    /* Now checkout the destination */
5645
    virCheckConnectGoto(dconn, error);
5646
    virCheckReadOnlyGoto(dconn->flags, error);
5647

5648 5649 5650 5651 5652 5653 5654 5655 5656
    if (flags & VIR_MIGRATE_NON_SHARED_DISK &&
        flags & VIR_MIGRATE_NON_SHARED_INC) {
        virReportInvalidArg(flags,
                            _("flags 'shared disk' and 'shared incremental' "
                              "in %s are mutually exclusive"),
                            __FUNCTION__);
        goto error;
    }

L
liguang 已提交
5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673
    if (flags & VIR_MIGRATE_OFFLINE) {
        if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                      VIR_DRV_FEATURE_MIGRATION_OFFLINE)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("offline migration is not supported by "
                              "the source host"));
            goto error;
        }
        if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                      VIR_DRV_FEATURE_MIGRATION_OFFLINE)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("offline migration is not supported by "
                              "the destination host"));
            goto error;
        }
    }

5674
    if (flags & VIR_MIGRATE_PEER2PEER) {
5675 5676
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_P2P)) {
5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688
            char *dstURI = virConnectGetURI(dconn);
            if (!dstURI)
                return NULL;

            VIR_DEBUG("Using peer2peer migration");
            if (virDomainMigratePeer2Peer(domain, dxml, flags, dname,
                                          dstURI, uri, bandwidth) < 0) {
                VIR_FREE(dstURI);
                goto error;
            }
            VIR_FREE(dstURI);

5689
            ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name);
5690 5691
        } else {
            /* This driver does not support peer to peer migration */
5692
            virReportUnsupportedError();
5693 5694 5695
            goto error;
        }
    } else {
5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708
        /* Change protection requires support only on source side, and
         * is only needed in v3 migration, which automatically re-adds
         * the flag for just the source side.  We mask it out for
         * non-peer2peer to allow migration from newer source to an
         * older destination that rejects the flag.  */
        if (flags & VIR_MIGRATE_CHANGE_PROTECTION &&
            !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                      VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("cannot enforce change protection"));
            goto error;
        }
        flags &= ~VIR_MIGRATE_CHANGE_PROTECTION;
5709
        if (flags & VIR_MIGRATE_TUNNELLED) {
5710
            virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746
                            _("cannot perform tunnelled migration without using peer2peer flag"));
            goto error;
        }

        /* Check that migration is supported by both drivers. */
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_V3) &&
            VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                     VIR_DRV_FEATURE_MIGRATION_V3)) {
            VIR_DEBUG("Using migration protocol 3");
            ddomain = virDomainMigrateVersion3(domain, dconn, dxml,
                                               flags, dname, uri, bandwidth);
        } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                            VIR_DRV_FEATURE_MIGRATION_V2) &&
                   VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                          VIR_DRV_FEATURE_MIGRATION_V2)) {
            VIR_DEBUG("Using migration protocol 2");
            if (dxml) {
                virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("Unable to change target guest XML during migration"));
                goto error;
            }
            ddomain = virDomainMigrateVersion2(domain, dconn, flags,
                                               dname, uri, bandwidth);
        } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                            VIR_DRV_FEATURE_MIGRATION_V1) &&
                   VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                            VIR_DRV_FEATURE_MIGRATION_V1)) {
            VIR_DEBUG("Using migration protocol 1");
            if (dxml) {
                virLibConnError(VIR_ERR_INTERNAL_ERROR, "%s",
                                _("Unable to change target guest XML during migration"));
                goto error;
            }
            ddomain = virDomainMigrateVersion1(domain, dconn, flags,
                                               dname, uri, bandwidth);
5747
        } else {
5748
            /* This driver does not support any migration method */
5749
            virReportUnsupportedError();
C
Chris Lalancette 已提交
5750 5751
            goto error;
        }
5752 5753
    }

5754 5755
    if (ddomain == NULL)
        goto error;
D
Daniel Veillard 已提交
5756

5757
    return ddomain;
5758 5759

error:
5760
    virDispatchError(domain->conn);
5761
    return NULL;
5762 5763
}

5764

J
Jiri Denemark 已提交
5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822
/**
 * virDomainMigrate3:
 * @domain: a domain object
 * @dconn: destination host (a connection object)
 * @params: (optional) migration parameters
 * @nparams: (optional) number of migration parameters in @params
 * @flags: bitwise-OR of virDomainMigrateFlags
 *
 * Migrate the domain object from its current host to the destination host
 * given by dconn (a connection to the destination host).
 *
 * See virDomainMigrateFlags documentation for description of individual flags.
 *
 * VIR_MIGRATE_TUNNELLED and VIR_MIGRATE_PEER2PEER are not supported by this
 * API, use virDomainMigrateToURI3 instead.
 *
 * If you want to copy non-shared storage within migration you
 * can use either VIR_MIGRATE_NON_SHARED_DISK or
 * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive.
 *
 * There are many limitations on migration imposed by the underlying
 * technology - for example it may not be possible to migrate between
 * different processors even with the same architecture, or between
 * different types of hypervisor.
 *
 * Returns the new domain object if the migration was successful,
 *   or NULL in case of error.  Note that the new domain object
 *   exists in the scope of the destination connection (dconn).
 */
virDomainPtr
virDomainMigrate3(virDomainPtr domain,
                  virConnectPtr dconn,
                  virTypedParameterPtr params,
                  unsigned int nparams,
                  unsigned int flags)
{
    virDomainPtr ddomain = NULL;
    const char *compatParams[] = { VIR_MIGRATE_PARAM_URI,
                                   VIR_MIGRATE_PARAM_DEST_NAME,
                                   VIR_MIGRATE_PARAM_DEST_XML,
                                   VIR_MIGRATE_PARAM_BANDWIDTH };
    const char *uri = NULL;
    const char *dname = NULL;
    const char *dxml = NULL;
    unsigned long long bandwidth = 0;

    VIR_DOMAIN_DEBUG(domain, "dconn=%p, params=%p, nparms=%u flags=%x",
                     dconn, params, nparams, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

    /* First checkout the source */
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
5823
    virCheckReadOnlyGoto(domain->conn->flags, error);
J
Jiri Denemark 已提交
5824 5825

    /* Now checkout the destination */
5826
    virCheckConnectGoto(dconn, error);
5827
    virCheckReadOnlyGoto(dconn->flags, error);
J
Jiri Denemark 已提交
5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940

    if (flags & VIR_MIGRATE_NON_SHARED_DISK &&
        flags & VIR_MIGRATE_NON_SHARED_INC) {
        virReportInvalidArg(flags,
                            _("flags 'shared disk' and 'shared incremental' "
                              "in %s are mutually exclusive"),
                            __FUNCTION__);
        goto error;
    }
    if (flags & (VIR_MIGRATE_PEER2PEER | VIR_MIGRATE_TUNNELLED)) {
        virReportInvalidArg(flags, "%s",
                            _("use virDomainMigrateToURI3 for peer-to-peer "
                              "migration"));
        goto error;
    }

    if (flags & VIR_MIGRATE_OFFLINE) {
        if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                      VIR_DRV_FEATURE_MIGRATION_OFFLINE)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("offline migration is not supported by "
                              "the source host"));
            goto error;
        }
        if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                      VIR_DRV_FEATURE_MIGRATION_OFFLINE)) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("offline migration is not supported by "
                              "the destination host"));
            goto error;
        }
    }

    /* Change protection requires support only on source side, and
     * is only needed in v3 migration, which automatically re-adds
     * the flag for just the source side.  We mask it out to allow
     * migration from newer source to an older destination that
     * rejects the flag.  */
    if (flags & VIR_MIGRATE_CHANGE_PROTECTION &&
        !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                  VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) {
        virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                        _("cannot enforce change protection"));
        goto error;
    }
    flags &= ~VIR_MIGRATE_CHANGE_PROTECTION;

    /* Prefer extensible API but fall back to older migration APIs if params
     * only contains parameters which were supported by the older API. */
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_MIGRATION_PARAMS) &&
        VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                 VIR_DRV_FEATURE_MIGRATION_PARAMS)) {
        VIR_DEBUG("Using migration protocol 3 with extensible parameters");
        ddomain = virDomainMigrateVersion3Params(domain, dconn, params,
                                                 nparams, flags);
        goto done;
    }

    if (!virTypedParamsCheck(params, nparams, compatParams,
                             ARRAY_CARDINALITY(compatParams))) {
        virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                        _("Migration APIs with extensible parameters are not "
                          "supported but extended parameters were passed"));
        goto error;
    }

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_URI, &uri) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML, &dxml) < 0 ||
        virTypedParamsGetULLong(params, nparams,
                                VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) {
        goto error;
    }

    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_MIGRATION_V3) &&
        VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                 VIR_DRV_FEATURE_MIGRATION_V3)) {
        VIR_DEBUG("Using migration protocol 3");
        ddomain = virDomainMigrateVersion3(domain, dconn, dxml, flags,
                                           dname, uri, bandwidth);
    } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                        VIR_DRV_FEATURE_MIGRATION_V2) &&
               VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                      VIR_DRV_FEATURE_MIGRATION_V2)) {
        VIR_DEBUG("Using migration protocol 2");
        if (dxml) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("Unable to change target guest XML during "
                              "migration"));
            goto error;
        }
        ddomain = virDomainMigrateVersion2(domain, dconn, flags,
                                           dname, uri, bandwidth);
    } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                        VIR_DRV_FEATURE_MIGRATION_V1) &&
               VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                        VIR_DRV_FEATURE_MIGRATION_V1)) {
        VIR_DEBUG("Using migration protocol 1");
        if (dxml) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("Unable to change target guest XML during "
                              "migration"));
            goto error;
        }
        ddomain = virDomainMigrateVersion1(domain, dconn, flags,
                                           dname, uri, bandwidth);
    } else {
        /* This driver does not support any migration method */
5941
        virReportUnsupportedError();
J
Jiri Denemark 已提交
5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956
        goto error;
    }

done:
    if (ddomain == NULL)
        goto error;

    return ddomain;

error:
    virDispatchError(domain->conn);
    return NULL;
}


5957 5958 5959 5960
/**
 * virDomainMigrateToURI:
 * @domain: a domain object
 * @duri: mandatory URI for the destination host
5961
 * @flags: bitwise-OR of virDomainMigrateFlags
5962
 * @dname: (optional) rename domain to this at destination
5963
 * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
5964 5965
 *
 * Migrate the domain object from its current host to the destination
D
Dan Kenigsberg 已提交
5966
 * host given by duri.
5967 5968 5969 5970 5971
 *
 * Flags may be one of more of the following:
 *   VIR_MIGRATE_LIVE      Do not pause the VM during migration
 *   VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts
 *   VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel
5972 5973 5974 5975
 *   VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain
 *                            on the destination host.
 *   VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the
 *                               domain on the source host.
5976 5977 5978 5979 5980
 *   VIR_MIGRATE_PAUSED    Leave the domain suspended on the remote side.
 *   VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full
 *                               disk copy
 *   VIR_MIGRATE_NON_SHARED_INC  Migration with non-shared storage with
 *                               incremental disk copy
5981 5982 5983
 *   VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration
 *                                 changes during the migration process (set
 *                                 automatically when supported).
J
Jiri Denemark 已提交
5984
 *   VIR_MIGRATE_UNSAFE    Force migration even if it is considered unsafe.
5985
 *   VIR_MIGRATE_OFFLINE Migrate offline
5986
 *
5987 5988 5989 5990 5991 5992 5993 5994 5995 5996
 * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
 * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the duri parameter
 * takes a hypervisor specific format. The uri_transports element of the
 * hypervisor capabilities XML includes details of the supported URI
 * schemes. Not all hypervisors will support this mode of migration, so
 * if the VIR_MIGRATE_PEER2PEER flag is not set, then it may be necessary
 * to use the alternative virDomainMigrate API providing and explicit
 * virConnectPtr for the destination host.
 *
 * If the VIR_MIGRATE_PEER2PEER flag IS set, the duri parameter
5997
 * must be a valid libvirt connection URI, by which the source
D
Dan Kenigsberg 已提交
5998
 * libvirt driver can connect to the destination libvirt.
5999
 *
6000 6001
 * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set.
 *
6002 6003 6004 6005
 * If you want to copy non-shared storage within migration you
 * can use either VIR_MIGRATE_NON_SHARED_DISK or
 * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive.
 *
6006 6007 6008 6009 6010
 * If a hypervisor supports renaming domains during migration,
 * the dname parameter specifies the new name for the domain.
 * Setting dname to NULL keeps the domain name the same.  If domain
 * renaming is not supported by the hypervisor, dname must be NULL or
 * else an error will be returned.
6011
 *
6012
 * The maximum bandwidth (in MiB/s) that will be used to do migration
6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028
 * can be specified with the bandwidth parameter.  If set to 0,
 * libvirt will choose a suitable default.  Some hypervisors do
 * not support this feature and will return an error if bandwidth
 * is not 0.
 *
 * To see which features are supported by the current hypervisor,
 * see virConnectGetCapabilities, /capabilities/host/migration_features.
 *
 * There are many limitations on migration imposed by the underlying
 * technology - for example it may not be possible to migrate between
 * different processors even with the same architecture, or between
 * different types of hypervisor.
 *
 * Returns 0 if the migration succeeded, -1 upon error.
 */
int
6029 6030 6031 6032 6033
virDomainMigrateToURI(virDomainPtr domain,
                      const char *duri,
                      unsigned long flags,
                      const char *dname,
                      unsigned long bandwidth)
6034
{
6035
    VIR_DOMAIN_DEBUG(domain, "duri=%p, flags=%lx, dname=%s, bandwidth=%lu",
6036
                     NULLSTR(duri), flags, NULLSTR(dname), bandwidth);
6037 6038 6039 6040

    virResetLastError();

    /* First checkout the source */
6041
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
6042
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
6043
        virDispatchError(NULL);
6044 6045
        return -1;
    }
6046
    virCheckReadOnlyGoto(domain->conn->flags, error);
6047

6048
    virCheckNonNullArgGoto(duri, error);
6049

6050 6051 6052 6053 6054 6055 6056 6057 6058
    if (flags & VIR_MIGRATE_NON_SHARED_DISK &&
        flags & VIR_MIGRATE_NON_SHARED_INC) {
        virReportInvalidArg(flags,
                            _("flags 'shared disk' and 'shared incremental' "
                              "in %s are mutually exclusive"),
                            __FUNCTION__);
        goto error;
    }

L
liguang 已提交
6059 6060 6061 6062 6063 6064 6065 6066 6067
    if (flags & VIR_MIGRATE_OFFLINE &&
        !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                  VIR_DRV_FEATURE_MIGRATION_OFFLINE)) {
        virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                        _("offline migration is not supported by "
                          "the source host"));
        goto error;
    }

6068
    if (flags & VIR_MIGRATE_PEER2PEER) {
6069 6070
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_P2P)) {
6071
            VIR_DEBUG("Using peer2peer migration");
6072
            if (virDomainMigratePeer2Peer(domain, NULL, flags,
6073
                                          dname, duri, NULL, bandwidth) < 0)
6074 6075 6076
                goto error;
        } else {
            /* No peer to peer migration supported */
6077
            virReportUnsupportedError();
6078 6079 6080
            goto error;
        }
    } else {
6081 6082
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_DIRECT)) {
6083
            VIR_DEBUG("Using direct migration");
6084 6085
            if (virDomainMigrateDirect(domain, NULL, flags,
                                       dname, duri, bandwidth) < 0)
6086 6087 6088
                goto error;
        } else {
            /* Cannot do a migration with only the perform step */
J
Jiri Denemark 已提交
6089 6090 6091
            virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("direct migration is not supported by the"
                              " connection driver"));
6092 6093 6094 6095 6096 6097 6098
            goto error;
        }
    }

    return 0;

error:
6099
    virDispatchError(domain->conn);
6100 6101 6102 6103
    return -1;
}


6104 6105 6106 6107 6108 6109
/**
 * virDomainMigrateToURI2:
 * @domain: a domain object
 * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER
 * @miguri: (optional) URI for invoking the migration, not if @flags includs VIR_MIGRATE_TUNNELLED
 * @dxml: (optional) XML config for launching guest on target
6110
 * @flags: bitwise-OR of virDomainMigrateFlags
6111
 * @dname: (optional) rename domain to this at destination
6112
 * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124
 *
 * Migrate the domain object from its current host to the destination
 * host given by duri.
 *
 * Flags may be one of more of the following:
 *   VIR_MIGRATE_LIVE      Do not pause the VM during migration
 *   VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts
 *   VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel
 *   VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain
 *                            on the destination host.
 *   VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the
 *                               domain on the source host.
6125 6126 6127 6128 6129
 *   VIR_MIGRATE_PAUSED    Leave the domain suspended on the remote side.
 *   VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full
 *                               disk copy
 *   VIR_MIGRATE_NON_SHARED_INC  Migration with non-shared storage with
 *                               incremental disk copy
6130 6131 6132
 *   VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration
 *                                 changes during the migration process (set
 *                                 automatically when supported).
J
Jiri Denemark 已提交
6133
 *   VIR_MIGRATE_UNSAFE    Force migration even if it is considered unsafe.
6134
 *   VIR_MIGRATE_OFFLINE Migrate offline
6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151
 *
 * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
 *
 * If the VIR_MIGRATE_PEER2PEER flag is set, the @dconnuri parameter
 * must be a valid libvirt connection URI, by which the source
 * libvirt driver can connect to the destination libvirt. If the
 * VIR_MIGRATE_PEER2PEER flag is NOT set, then @dconnuri must be
 * NULL.
 *
 * If the VIR_MIGRATE_TUNNELLED flag is NOT set, then the @miguri
 * parameter allows specification of a URI to use to initiate the
 * VM migration. It takes a hypervisor specific format. The uri_transports
 * element of the hypervisor capabilities XML includes details of the
 * supported URI schemes.
 *
 * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set.
 *
6152 6153 6154 6155
 * If you want to copy non-shared storage within migration you
 * can use either VIR_MIGRATE_NON_SHARED_DISK or
 * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive.
 *
6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170
 * If a hypervisor supports changing the configuration of the guest
 * during migration, the @dxml parameter specifies the new config
 * for the guest. The configuration must include an identical set
 * of virtual devices, to ensure a stable guest ABI across migration.
 * Only parameters related to host side configuration can be
 * changed in the XML. Hypervisors will validate this and refuse to
 * allow migration if the provided XML would cause a change in the
 * guest ABI,
 *
 * If a hypervisor supports renaming domains during migration,
 * the dname parameter specifies the new name for the domain.
 * Setting dname to NULL keeps the domain name the same.  If domain
 * renaming is not supported by the hypervisor, dname must be NULL or
 * else an error will be returned.
 *
6171
 * The maximum bandwidth (in MiB/s) that will be used to do migration
6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196
 * can be specified with the bandwidth parameter.  If set to 0,
 * libvirt will choose a suitable default.  Some hypervisors do
 * not support this feature and will return an error if bandwidth
 * is not 0.
 *
 * To see which features are supported by the current hypervisor,
 * see virConnectGetCapabilities, /capabilities/host/migration_features.
 *
 * There are many limitations on migration imposed by the underlying
 * technology - for example it may not be possible to migrate between
 * different processors even with the same architecture, or between
 * different types of hypervisor.
 *
 * Returns 0 if the migration succeeded, -1 upon error.
 */
int
virDomainMigrateToURI2(virDomainPtr domain,
                       const char *dconnuri,
                       const char *miguri,
                       const char *dxml,
                       unsigned long flags,
                       const char *dname,
                       unsigned long bandwidth)
{
    VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, miguri=%s, dxml=%s, "
6197
                     "flags=%lx, dname=%s, bandwidth=%lu",
6198 6199 6200 6201 6202 6203
                     NULLSTR(dconnuri), NULLSTR(miguri), NULLSTR(dxml),
                     flags, NULLSTR(dname), bandwidth);

    virResetLastError();

    /* First checkout the source */
6204
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
6205 6206 6207 6208
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
6209
    virCheckReadOnlyGoto(domain->conn->flags, error);
6210

6211 6212 6213 6214 6215 6216 6217 6218 6219
    if (flags & VIR_MIGRATE_NON_SHARED_DISK &&
        flags & VIR_MIGRATE_NON_SHARED_INC) {
        virReportInvalidArg(flags,
                            _("flags 'shared disk' and 'shared incremental' "
                              "in %s are mutually exclusive"),
                            __FUNCTION__);
        goto error;
    }

6220
    if (flags & VIR_MIGRATE_PEER2PEER) {
6221 6222
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_P2P)) {
6223 6224 6225 6226 6227 6228
            VIR_DEBUG("Using peer2peer migration");
            if (virDomainMigratePeer2Peer(domain, dxml, flags,
                                          dname, dconnuri, miguri, bandwidth) < 0)
                goto error;
        } else {
            /* No peer to peer migration supported */
6229
            virReportUnsupportedError();
6230 6231 6232
            goto error;
        }
    } else {
6233 6234
        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_DIRECT)) {
6235 6236 6237 6238 6239 6240
            VIR_DEBUG("Using direct migration");
            if (virDomainMigrateDirect(domain, dxml, flags,
                                       dname, miguri, bandwidth) < 0)
                goto error;
        } else {
            /* Cannot do a migration with only the perform step */
J
Jiri Denemark 已提交
6241 6242 6243
            virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("direct migration is not supported by the"
                              " connection driver"));
6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255
            goto error;
        }
    }

    return 0;

error:
    virDispatchError(domain->conn);
    return -1;
}


J
Jiri Denemark 已提交
6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321
/**
 * virDomainMigrateToURI3:
 * @domain: a domain object
 * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER
 * @params: (optional) migration parameters
 * @nparams: (optional) number of migration parameters in @params
 * @flags: bitwise-OR of virDomainMigrateFlags
 *
 * Migrate the domain object from its current host to the destination host
 * given by URI.
 *
 * See virDomainMigrateFlags documentation for description of individual flags.
 *
 * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
 *
 * If the VIR_MIGRATE_PEER2PEER flag is set, the @dconnuri parameter must be a
 * valid libvirt connection URI, by which the source libvirt daemon can connect
 * to the destination libvirt.
 *
 * If the VIR_MIGRATE_PEER2PEER flag is NOT set, then @dconnuri must be NULL
 * and VIR_MIGRATE_PARAM_URI migration parameter must be filled in with
 * hypervisor specific URI used to initiate the migration. This is called
 * "direct" migration.
 *
 * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set.
 *
 * If you want to copy non-shared storage within migration you
 * can use either VIR_MIGRATE_NON_SHARED_DISK or
 * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive.
 *
 * There are many limitations on migration imposed by the underlying
 * technology - for example it may not be possible to migrate between
 * different processors even with the same architecture, or between
 * different types of hypervisor.
 *
 * Returns 0 if the migration succeeded, -1 upon error.
 */
int
virDomainMigrateToURI3(virDomainPtr domain,
                       const char *dconnuri,
                       virTypedParameterPtr params,
                       unsigned int nparams,
                       unsigned int flags)
{
    bool compat;
    const char *compatParams[] = { VIR_MIGRATE_PARAM_URI,
                                   VIR_MIGRATE_PARAM_DEST_NAME,
                                   VIR_MIGRATE_PARAM_DEST_XML,
                                   VIR_MIGRATE_PARAM_BANDWIDTH };
    const char *uri = NULL;
    const char *dname = NULL;
    const char *dxml = NULL;
    unsigned long long bandwidth = 0;

    VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparms=%u flags=%x",
                     NULLSTR(dconnuri), params, nparams, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

    /* First checkout the source */
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
6322
    virCheckReadOnlyGoto(domain->conn->flags, error);
J
Jiri Denemark 已提交
6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404

    if (flags & VIR_MIGRATE_NON_SHARED_DISK &&
        flags & VIR_MIGRATE_NON_SHARED_INC) {
        virReportInvalidArg(flags,
                            _("flags 'shared disk' and 'shared incremental' "
                              "in %s are mutually exclusive"),
                            __FUNCTION__);
        goto error;
    }

    compat = virTypedParamsCheck(params, nparams, compatParams,
                                 ARRAY_CARDINALITY(compatParams));

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_URI, &uri) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML, &dxml) < 0 ||
        virTypedParamsGetULLong(params, nparams,
                                VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) {
        goto error;
    }

    if (flags & VIR_MIGRATE_PEER2PEER) {
        if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                      VIR_DRV_FEATURE_MIGRATION_P2P)) {
            virLibConnError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                            _("Peer-to-peer migration is not supported by "
                              "the connection driver"));
            goto error;
        }

        if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                     VIR_DRV_FEATURE_MIGRATION_PARAMS)) {
            VIR_DEBUG("Using peer2peer migration with extensible parameters");
            if (virDomainMigratePeer2PeerParams(domain, dconnuri, params,
                                                nparams, flags) < 0)
                goto error;
        } else if (compat) {
            VIR_DEBUG("Using peer2peer migration");
            if (virDomainMigratePeer2Peer(domain, dxml, flags, dname,
                                          dconnuri, uri, bandwidth) < 0)
                goto error;
        } else {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("Peer-to-peer migration with extensible "
                              "parameters is not supported but extended "
                              "parameters were passed"));
            goto error;
        }
    } else {
        if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                      VIR_DRV_FEATURE_MIGRATION_DIRECT)) {
            /* Cannot do a migration with only the perform step */
            virLibConnError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                            _("Direct migration is not supported by the"
                              " connection driver"));
            goto error;
        }

        if (!compat) {
            virLibConnError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                            _("Direct migration does not support extensible "
                              "parameters"));
            goto error;
        }

        VIR_DEBUG("Using direct migration");
        if (virDomainMigrateDirect(domain, dxml, flags,
                                   dname, uri, bandwidth) < 0)
            goto error;
    }

    return 0;

error:
    virDispatchError(domain->conn);
    return -1;
}


D
Daniel Veillard 已提交
6405 6406
/*
 * Not for public use.  This function is part of the internal
6407 6408 6409
 * implementation of migration in the remote case.
 */
int
6410 6411 6412 6413 6414 6415 6416 6417
virDomainMigratePrepare(virConnectPtr dconn,
                        char **cookie,
                        int *cookielen,
                        const char *uri_in,
                        char **uri_out,
                        unsigned long flags,
                        const char *dname,
                        unsigned long bandwidth)
6418
{
J
John Levon 已提交
6419
    VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p, "
6420
              "flags=%lx, dname=%s, bandwidth=%lu", dconn, cookie, cookielen,
J
John Levon 已提交
6421
              NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth);
6422

6423 6424
    virResetLastError();

6425
    virCheckConnectReturn(dconn, -1);
6426
    virCheckReadOnlyGoto(dconn->flags, error);
6427

6428 6429
    if (dconn->driver->domainMigratePrepare) {
        int ret;
6430 6431 6432
        ret = dconn->driver->domainMigratePrepare(dconn, cookie, cookielen,
                                                  uri_in, uri_out,
                                                  flags, dname, bandwidth);
6433 6434 6435 6436
        if (ret < 0)
            goto error;
        return ret;
    }
6437

6438
    virReportUnsupportedError();
6439 6440

error:
6441
    virDispatchError(dconn);
6442 6443 6444
    return -1;
}

6445

D
Daniel Veillard 已提交
6446 6447
/*
 * Not for public use.  This function is part of the internal
6448 6449 6450
 * implementation of migration in the remote case.
 */
int
6451 6452 6453 6454 6455 6456 6457
virDomainMigratePerform(virDomainPtr domain,
                        const char *cookie,
                        int cookielen,
                        const char *uri,
                        unsigned long flags,
                        const char *dname,
                        unsigned long bandwidth)
6458 6459
{
    virConnectPtr conn;
6460

6461
    VIR_DOMAIN_DEBUG(domain, "cookie=%p, cookielen=%d, uri=%s, flags=%lx, "
6462 6463
                     "dname=%s, bandwidth=%lu", cookie, cookielen, uri, flags,
                     NULLSTR(dname), bandwidth);
6464

6465 6466
    virResetLastError();

6467
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
6468
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
6469
        virDispatchError(NULL);
6470 6471 6472 6473
        return -1;
    }
    conn = domain->conn;

6474
    virCheckReadOnlyGoto(domain->conn->flags, error);
6475

6476 6477
    if (conn->driver->domainMigratePerform) {
        int ret;
6478 6479 6480
        ret = conn->driver->domainMigratePerform(domain, cookie, cookielen,
                                                 uri,
                                                 flags, dname, bandwidth);
6481 6482 6483 6484
        if (ret < 0)
            goto error;
        return ret;
    }
6485

6486
    virReportUnsupportedError();
6487 6488

error:
6489
    virDispatchError(domain->conn);
6490 6491 6492
    return -1;
}

6493

D
Daniel Veillard 已提交
6494 6495
/*
 * Not for public use.  This function is part of the internal
6496 6497 6498
 * implementation of migration in the remote case.
 */
virDomainPtr
6499 6500 6501 6502 6503 6504
virDomainMigrateFinish(virConnectPtr dconn,
                       const char *dname,
                       const char *cookie,
                       int cookielen,
                       const char *uri,
                       unsigned long flags)
6505
{
J
John Levon 已提交
6506
    VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, "
6507
              "flags=%lx", dconn, NULLSTR(dname), cookie, cookielen,
J
John Levon 已提交
6508
              uri, flags);
6509

6510 6511
    virResetLastError();

6512
    virCheckConnectReturn(dconn, NULL);
6513
    virCheckReadOnlyGoto(dconn->flags, error);
6514

6515 6516
    if (dconn->driver->domainMigrateFinish) {
        virDomainPtr ret;
6517 6518 6519
        ret = dconn->driver->domainMigrateFinish(dconn, dname,
                                                 cookie, cookielen,
                                                 uri, flags);
6520 6521 6522 6523
        if (!ret)
            goto error;
        return ret;
    }
6524

6525
    virReportUnsupportedError();
6526 6527

error:
6528
    virDispatchError(dconn);
6529
    return NULL;
D
Daniel Veillard 已提交
6530 6531 6532
}


D
Daniel Veillard 已提交
6533 6534
/*
 * Not for public use.  This function is part of the internal
D
Daniel Veillard 已提交
6535 6536 6537
 * implementation of migration in the remote case.
 */
int
6538 6539 6540 6541 6542 6543 6544 6545 6546
virDomainMigratePrepare2(virConnectPtr dconn,
                         char **cookie,
                         int *cookielen,
                         const char *uri_in,
                         char **uri_out,
                         unsigned long flags,
                         const char *dname,
                         unsigned long bandwidth,
                         const char *dom_xml)
D
Daniel Veillard 已提交
6547
{
J
John Levon 已提交
6548
    VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p,"
6549
              "flags=%lx, dname=%s, bandwidth=%lu, dom_xml=%s", dconn,
J
John Levon 已提交
6550 6551
              cookie, cookielen, uri_in, uri_out, flags, NULLSTR(dname),
              bandwidth, dom_xml);
D
Daniel Veillard 已提交
6552

6553 6554
    virResetLastError();

6555
    virCheckConnectReturn(dconn, -1);
6556
    virCheckReadOnlyGoto(dconn->flags, error);
6557

6558 6559
    if (dconn->driver->domainMigratePrepare2) {
        int ret;
6560 6561 6562 6563
        ret = dconn->driver->domainMigratePrepare2(dconn, cookie, cookielen,
                                                   uri_in, uri_out,
                                                   flags, dname, bandwidth,
                                                   dom_xml);
6564 6565 6566 6567
        if (ret < 0)
            goto error;
        return ret;
    }
D
Daniel Veillard 已提交
6568

6569
    virReportUnsupportedError();
6570 6571

error:
6572
    virDispatchError(dconn);
D
Daniel Veillard 已提交
6573 6574 6575
    return -1;
}

6576

D
Daniel Veillard 已提交
6577 6578
/*
 * Not for public use.  This function is part of the internal
D
Daniel Veillard 已提交
6579 6580 6581
 * implementation of migration in the remote case.
 */
virDomainPtr
6582 6583 6584 6585 6586 6587 6588
virDomainMigrateFinish2(virConnectPtr dconn,
                        const char *dname,
                        const char *cookie,
                        int cookielen,
                        const char *uri,
                        unsigned long flags,
                        int retcode)
D
Daniel Veillard 已提交
6589
{
J
John Levon 已提交
6590
    VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, "
6591
              "flags=%lx, retcode=%d", dconn, NULLSTR(dname), cookie,
J
John Levon 已提交
6592
              cookielen, uri, flags, retcode);
D
Daniel Veillard 已提交
6593

6594 6595
    virResetLastError();

6596
    virCheckConnectReturn(dconn, NULL);
6597
    virCheckReadOnlyGoto(dconn->flags, error);
6598

6599 6600
    if (dconn->driver->domainMigrateFinish2) {
        virDomainPtr ret;
6601 6602 6603 6604
        ret = dconn->driver->domainMigrateFinish2(dconn, dname,
                                                  cookie, cookielen,
                                                  uri, flags,
                                                  retcode);
6605 6606 6607 6608
        if (!ret)
            goto error;
        return ret;
    }
D
Daniel Veillard 已提交
6609

6610
    virReportUnsupportedError();
6611 6612

error:
6613
    virDispatchError(dconn);
D
Daniel Veillard 已提交
6614
    return NULL;
6615 6616 6617
}


C
Chris Lalancette 已提交
6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629
/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigratePrepareTunnel(virConnectPtr conn,
                              virStreamPtr st,
                              unsigned long flags,
                              const char *dname,
                              unsigned long bandwidth,
                              const char *dom_xml)
{
6630
    VIR_DEBUG("conn=%p, stream=%p, flags=%lx, dname=%s, "
6631
              "bandwidth=%lu, dom_xml=%s", conn, st, flags,
C
Chris Lalancette 已提交
6632 6633 6634 6635
              NULLSTR(dname), bandwidth, dom_xml);

    virResetLastError();

6636
    virCheckConnectReturn(conn, -1);
6637
    virCheckReadOnlyGoto(conn->flags, error);
C
Chris Lalancette 已提交
6638 6639

    if (conn != st->conn) {
6640 6641 6642
        virReportInvalidArg(conn,
                            _("conn in %s must match stream connection"),
                            __FUNCTION__);
C
Chris Lalancette 已提交
6643 6644 6645 6646
        goto error;
    }

    if (conn->driver->domainMigratePrepareTunnel) {
6647
        int rv = conn->driver->domainMigratePrepareTunnel(conn, st,
C
Chris Lalancette 已提交
6648 6649 6650 6651 6652 6653 6654
                                                          flags, dname,
                                                          bandwidth, dom_xml);
        if (rv < 0)
            goto error;
        return rv;
    }

6655
    virReportUnsupportedError();
C
Chris Lalancette 已提交
6656 6657

error:
6658
    virDispatchError(conn);
C
Chris Lalancette 已提交
6659 6660 6661
    return -1;
}

6662

6663 6664 6665 6666 6667 6668
/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
char *
virDomainMigrateBegin3(virDomainPtr domain,
6669
                       const char *xmlin,
6670 6671 6672 6673 6674 6675 6676 6677
                       char **cookieout,
                       int *cookieoutlen,
                       unsigned long flags,
                       const char *dname,
                       unsigned long bandwidth)
{
    virConnectPtr conn;

6678
    VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookieout=%p, cookieoutlen=%p, "
6679
                     "flags=%lx, dname=%s, bandwidth=%lu",
6680
                     NULLSTR(xmlin), cookieout, cookieoutlen, flags,
6681 6682 6683 6684
                     NULLSTR(dname), bandwidth);

    virResetLastError();

6685
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
6686 6687 6688 6689 6690 6691
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
    conn = domain->conn;

6692
    virCheckReadOnlyGoto(domain->conn->flags, error);
6693 6694 6695

    if (conn->driver->domainMigrateBegin3) {
        char *xml;
6696
        xml = conn->driver->domainMigrateBegin3(domain, xmlin,
6697 6698 6699 6700 6701 6702 6703 6704
                                                cookieout, cookieoutlen,
                                                flags, dname, bandwidth);
        VIR_DEBUG("xml %s", NULLSTR(xml));
        if (!xml)
            goto error;
        return xml;
    }

6705
    virReportUnsupportedError();
6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729

error:
    virDispatchError(domain->conn);
    return NULL;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigratePrepare3(virConnectPtr dconn,
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
                         const char *uri_in,
                         char **uri_out,
                         unsigned long flags,
                         const char *dname,
                         unsigned long bandwidth,
                         const char *dom_xml)
{
6730 6731 6732 6733 6734
    VIR_DEBUG("dconn=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, "
              "cookieoutlen=%p, uri_in=%s, uri_out=%p, flags=%lx, dname=%s, "
              "bandwidth=%lu, dom_xml=%s",
              dconn, cookiein, cookieinlen, cookieout, cookieoutlen, uri_in,
              uri_out, flags, NULLSTR(dname), bandwidth, dom_xml);
6735 6736 6737

    virResetLastError();

6738
    virCheckConnectReturn(dconn, -1);
6739
    virCheckReadOnlyGoto(dconn->flags, error);
6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753

    if (dconn->driver->domainMigratePrepare3) {
        int ret;
        ret = dconn->driver->domainMigratePrepare3(dconn,
                                                   cookiein, cookieinlen,
                                                   cookieout, cookieoutlen,
                                                   uri_in, uri_out,
                                                   flags, dname, bandwidth,
                                                   dom_xml);
        if (ret < 0)
            goto error;
        return ret;
    }

6754
    virReportUnsupportedError();
6755 6756 6757 6758 6759 6760

error:
    virDispatchError(dconn);
    return -1;
}

6761

6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777
/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigratePrepareTunnel3(virConnectPtr conn,
                               virStreamPtr st,
                               const char *cookiein,
                               int cookieinlen,
                               char **cookieout,
                               int *cookieoutlen,
                               unsigned long flags,
                               const char *dname,
                               unsigned long bandwidth,
                               const char *dom_xml)
{
6778 6779 6780
    VIR_DEBUG("conn=%p, stream=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, "
              "cookieoutlen=%p, flags=%lx, dname=%s, bandwidth=%lu, "
              "dom_xml=%s",
6781 6782 6783 6784 6785
              conn, st, cookiein, cookieinlen, cookieout, cookieoutlen, flags,
              NULLSTR(dname), bandwidth, dom_xml);

    virResetLastError();

6786
    virCheckConnectReturn(conn, -1);
6787
    virCheckReadOnlyGoto(conn->flags, error);
6788 6789

    if (conn != st->conn) {
6790 6791 6792
        virReportInvalidArg(conn,
                            _("conn in %s must match stream connection"),
                            __FUNCTION__);
6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806
        goto error;
    }

    if (conn->driver->domainMigratePrepareTunnel3) {
        int rv = conn->driver->domainMigratePrepareTunnel3(conn, st,
                                                           cookiein, cookieinlen,
                                                           cookieout, cookieoutlen,
                                                           flags, dname,
                                                           bandwidth, dom_xml);
        if (rv < 0)
            goto error;
        return rv;
    }

6807
    virReportUnsupportedError();
6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820

error:
    virDispatchError(conn);
    return -1;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigratePerform3(virDomainPtr domain,
6821
                         const char *xmlin,
6822 6823 6824 6825
                         const char *cookiein,
                         int cookieinlen,
                         char **cookieout,
                         int *cookieoutlen,
6826
                         const char *dconnuri,
6827 6828 6829 6830 6831 6832 6833
                         const char *uri,
                         unsigned long flags,
                         const char *dname,
                         unsigned long bandwidth)
{
    virConnectPtr conn;

6834
    VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookiein=%p, cookieinlen=%d, "
6835
                     "cookieout=%p, cookieoutlen=%p, dconnuri=%s, "
6836
                     "uri=%s, flags=%lx, dname=%s, bandwidth=%lu",
6837
                     NULLSTR(xmlin), cookiein, cookieinlen,
6838 6839
                     cookieout, cookieoutlen, NULLSTR(dconnuri),
                     NULLSTR(uri), flags, NULLSTR(dname), bandwidth);
6840 6841 6842

    virResetLastError();

6843
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
6844 6845 6846 6847 6848 6849
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = domain->conn;

6850
    virCheckReadOnlyGoto(domain->conn->flags, error);
6851 6852 6853

    if (conn->driver->domainMigratePerform3) {
        int ret;
6854
        ret = conn->driver->domainMigratePerform3(domain, xmlin,
6855 6856
                                                  cookiein, cookieinlen,
                                                  cookieout, cookieoutlen,
6857
                                                  dconnuri, uri,
6858 6859 6860 6861 6862 6863
                                                  flags, dname, bandwidth);
        if (ret < 0)
            goto error;
        return ret;
    }

6864
    virReportUnsupportedError();
6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875

error:
    virDispatchError(domain->conn);
    return -1;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
6876
virDomainPtr
6877 6878 6879 6880 6881 6882
virDomainMigrateFinish3(virConnectPtr dconn,
                        const char *dname,
                        const char *cookiein,
                        int cookieinlen,
                        char **cookieout,
                        int *cookieoutlen,
6883
                        const char *dconnuri,
6884 6885
                        const char *uri,
                        unsigned long flags,
6886
                        int cancelled)
6887 6888
{
    VIR_DEBUG("dconn=%p, dname=%s, cookiein=%p, cookieinlen=%d, cookieout=%p,"
6889
              "cookieoutlen=%p, dconnuri=%s, uri=%s, flags=%lx, retcode=%d",
6890
              dconn, NULLSTR(dname), cookiein, cookieinlen, cookieout,
6891
              cookieoutlen, NULLSTR(dconnuri), NULLSTR(uri), flags, cancelled);
6892 6893 6894

    virResetLastError();

6895
    virCheckConnectReturn(dconn, NULL);
6896
    virCheckReadOnlyGoto(dconn->flags, error);
6897 6898

    if (dconn->driver->domainMigrateFinish3) {
6899
        virDomainPtr ret;
6900 6901 6902
        ret = dconn->driver->domainMigrateFinish3(dconn, dname,
                                                  cookiein, cookieinlen,
                                                  cookieout, cookieoutlen,
6903
                                                  dconnuri, uri, flags,
6904 6905
                                                  cancelled);
        if (!ret)
6906 6907 6908 6909
            goto error;
        return ret;
    }

6910
    virReportUnsupportedError();
6911 6912 6913

error:
    virDispatchError(dconn);
6914
    return NULL;
6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigrateConfirm3(virDomainPtr domain,
                         const char *cookiein,
                         int cookieinlen,
                         unsigned long flags,
                         int cancelled)
{
    virConnectPtr conn;

6931 6932
    VIR_DOMAIN_DEBUG(domain,
                     "cookiein=%p, cookieinlen=%d, flags=%lx, cancelled=%d",
6933 6934 6935 6936
                     cookiein, cookieinlen, flags, cancelled);

    virResetLastError();

6937
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
6938 6939 6940 6941 6942 6943
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = domain->conn;

6944
    virCheckReadOnlyGoto(domain->conn->flags, error);
6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955

    if (conn->driver->domainMigrateConfirm3) {
        int ret;
        ret = conn->driver->domainMigrateConfirm3(domain,
                                                  cookiein, cookieinlen,
                                                  flags, cancelled);
        if (ret < 0)
            goto error;
        return ret;
    }

6956
    virReportUnsupportedError();
6957 6958 6959 6960 6961 6962

error:
    virDispatchError(domain->conn);
    return -1;
}

C
Chris Lalancette 已提交
6963

6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991
/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
char *
virDomainMigrateBegin3Params(virDomainPtr domain,
                             virTypedParameterPtr params,
                             int nparams,
                             char **cookieout,
                             int *cookieoutlen,
                             unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, "
                     "cookieout=%p, cookieoutlen=%p, flags=%x",
                     params, nparams, cookieout, cookieoutlen, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
    conn = domain->conn;

6992
    virCheckReadOnlyGoto(domain->conn->flags, error);
6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004

    if (conn->driver->domainMigrateBegin3Params) {
        char *xml;
        xml = conn->driver->domainMigrateBegin3Params(domain, params, nparams,
                                                      cookieout, cookieoutlen,
                                                      flags);
        VIR_DEBUG("xml %s", NULLSTR(xml));
        if (!xml)
            goto error;
        return xml;
    }

7005
    virReportUnsupportedError();
7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035

error:
    virDispatchError(domain->conn);
    return NULL;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigratePrepare3Params(virConnectPtr dconn,
                               virTypedParameterPtr params,
                               int nparams,
                               const char *cookiein,
                               int cookieinlen,
                               char **cookieout,
                               int *cookieoutlen,
                               char **uri_out,
                               unsigned int flags)
{
    VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, "
              "cookieout=%p, cookieoutlen=%p, uri_out=%p, flags=%x",
              dconn, params, nparams, cookiein, cookieinlen,
              cookieout, cookieoutlen, uri_out, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

7036
    virCheckConnectReturn(dconn, -1);
7037
    virCheckReadOnlyGoto(dconn->flags, error);
7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049

    if (dconn->driver->domainMigratePrepare3Params) {
        int ret;
        ret = dconn->driver->domainMigratePrepare3Params(dconn, params, nparams,
                                                         cookiein, cookieinlen,
                                                         cookieout, cookieoutlen,
                                                         uri_out, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

7050
    virReportUnsupportedError();
7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080

error:
    virDispatchError(dconn);
    return -1;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigratePrepareTunnel3Params(virConnectPtr conn,
                                     virStreamPtr st,
                                     virTypedParameterPtr params,
                                     int nparams,
                                     const char *cookiein,
                                     int cookieinlen,
                                     char **cookieout,
                                     int *cookieoutlen,
                                     unsigned int flags)
{
    VIR_DEBUG("conn=%p, stream=%p, params=%p, nparams=%d, cookiein=%p, "
              "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=%x",
              conn, st, params, nparams, cookiein, cookieinlen,
              cookieout, cookieoutlen, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

7081
    virCheckConnectReturn(conn, -1);
7082
    virCheckReadOnlyGoto(conn->flags, error);
7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100

    if (conn != st->conn) {
        virReportInvalidArg(conn,
                            _("conn in %s must match stream connection"),
                            __FUNCTION__);
        goto error;
    }

    if (conn->driver->domainMigratePrepareTunnel3Params) {
        int rv;
        rv = conn->driver->domainMigratePrepareTunnel3Params(
                conn, st, params, nparams, cookiein, cookieinlen,
                cookieout, cookieoutlen, flags);
        if (rv < 0)
            goto error;
        return rv;
    }

7101
    virReportUnsupportedError();
7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140

error:
    virDispatchError(conn);
    return -1;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigratePerform3Params(virDomainPtr domain,
                               const char *dconnuri,
                               virTypedParameterPtr params,
                               int nparams,
                               const char *cookiein,
                               int cookieinlen,
                               char **cookieout,
                               int *cookieoutlen,
                               unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparams=%d, cookiein=%p, "
                     "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=%x",
                     NULLSTR(dconnuri), params, nparams, cookiein,
                     cookieinlen, cookieout, cookieoutlen, flags);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = domain->conn;

7141
    virCheckReadOnlyGoto(domain->conn->flags, error);
7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152

    if (conn->driver->domainMigratePerform3Params) {
        int ret;
        ret = conn->driver->domainMigratePerform3Params(
                domain, dconnuri, params, nparams, cookiein, cookieinlen,
                cookieout, cookieoutlen, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

7153
    virReportUnsupportedError();
7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183

error:
    virDispatchError(domain->conn);
    return -1;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
virDomainPtr
virDomainMigrateFinish3Params(virConnectPtr dconn,
                              virTypedParameterPtr params,
                              int nparams,
                              const char *cookiein,
                              int cookieinlen,
                              char **cookieout,
                              int *cookieoutlen,
                              unsigned int flags,
                              int cancelled)
{
    VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, "
              "cookieout=%p, cookieoutlen=%p, flags=%x, cancelled=%d",
              dconn, params, nparams, cookiein, cookieinlen, cookieout,
              cookieoutlen, flags, cancelled);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

7184
    virCheckConnectReturn(dconn, NULL);
7185
    virCheckReadOnlyGoto(dconn->flags, error);
7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196

    if (dconn->driver->domainMigrateFinish3Params) {
        virDomainPtr ret;
        ret = dconn->driver->domainMigrateFinish3Params(
                dconn, params, nparams, cookiein, cookieinlen,
                cookieout, cookieoutlen, flags, cancelled);
        if (!ret)
            goto error;
        return ret;
    }

7197
    virReportUnsupportedError();
7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233

error:
    virDispatchError(dconn);
    return NULL;
}


/*
 * Not for public use.  This function is part of the internal
 * implementation of migration in the remote case.
 */
int
virDomainMigrateConfirm3Params(virDomainPtr domain,
                               virTypedParameterPtr params,
                               int nparams,
                               const char *cookiein,
                               int cookieinlen,
                               unsigned int flags,
                               int cancelled)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, cookiein=%p, "
                     "cookieinlen=%d, flags=%x, cancelled=%d",
                     params, nparams, cookiein, cookieinlen, flags, cancelled);
    VIR_TYPED_PARAMS_DEBUG(params, nparams);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = domain->conn;

7234
    virCheckReadOnlyGoto(domain->conn->flags, error);
7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245

    if (conn->driver->domainMigrateConfirm3Params) {
        int ret;
        ret = conn->driver->domainMigrateConfirm3Params(
                domain, params, nparams,
                cookiein, cookieinlen, flags, cancelled);
        if (ret < 0)
            goto error;
        return ret;
    }

7246
    virReportUnsupportedError();
7247 7248 7249 7250 7251 7252 7253

error:
    virDispatchError(domain->conn);
    return -1;
}


7254 7255 7256 7257
/**
 * virNodeGetInfo:
 * @conn: pointer to the hypervisor connection
 * @info: pointer to a virNodeInfo structure allocated by the user
7258
 *
7259 7260 7261 7262 7263
 * Extract hardware information about the node.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
7264 7265
virNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
7266
    VIR_DEBUG("conn=%p, info=%p", conn, info);
7267

7268 7269
    virResetLastError();

7270
    virCheckConnectReturn(conn, -1);
7271
    virCheckNonNullArgGoto(info, error);
7272

7273 7274
    if (conn->driver->nodeGetInfo) {
        int ret;
7275
        ret = conn->driver->nodeGetInfo(conn, info);
7276 7277 7278 7279
        if (ret < 0)
            goto error;
        return ret;
    }
7280

7281
    virReportUnsupportedError();
7282 7283

error:
7284
    virDispatchError(conn);
7285
    return -1;
7286
}
7287

7288

7289 7290 7291 7292 7293 7294
/**
 * virConnectGetCapabilities:
 * @conn: pointer to the hypervisor connection
 *
 * Provides capabilities of the hypervisor / driver.
 *
7295 7296
 * Returns NULL in case of error, or an XML string
 * defining the capabilities.
7297 7298 7299
 * The client must free the returned string after use.
 */
char *
7300
virConnectGetCapabilities(virConnectPtr conn)
7301
{
7302
    VIR_DEBUG("conn=%p", conn);
7303

7304 7305
    virResetLastError();

7306
    virCheckConnectReturn(conn, NULL);
7307

7308
    if (conn->driver->connectGetCapabilities) {
7309
        char *ret;
7310
        ret = conn->driver->connectGetCapabilities(conn);
7311 7312
        if (!ret)
            goto error;
7313
        VIR_DEBUG("conn=%p ret=%s", conn, ret);
7314 7315
        return ret;
    }
7316

7317
    virReportUnsupportedError();
7318 7319

error:
7320
    virDispatchError(conn);
7321 7322 7323
    return NULL;
}

7324

7325 7326 7327
/**
 * virNodeGetCPUStats:
 * @conn: pointer to the hypervisor connection.
7328
 * @cpuNum: number of node cpu. (VIR_NODE_CPU_STATS_ALL_CPUS means total cpu
7329 7330 7331 7332
 *          statistics)
 * @params: pointer to node cpu time parameter objects
 * @nparams: number of node cpu time parameter (this value should be same or
 *          less than the number of parameters supported)
7333
 * @flags: extra flags; not used yet, so callers should always pass 0
7334 7335 7336
 *
 * This function provides individual cpu statistics of the node.
 * If you want to get total cpu statistics of the node, you must specify
7337
 * VIR_NODE_CPU_STATS_ALL_CPUS to @cpuNum.
7338 7339 7340 7341 7342 7343
 * The @params array will be filled with the values equal to the number of
 * parameters suggested by @nparams
 *
 * As the value of @nparams is dynamic, call the API setting @nparams to 0 and
 * @params as NULL, the API returns the number of parameters supported by the
 * HV by updating @nparams on SUCCESS. The caller should then allocate @params
7344
 * array, i.e. (sizeof(@virNodeCPUStats) * @nparams) bytes and call
7345 7346 7347 7348
 * the API again.
 *
 * Here is a sample code snippet:
 *
E
Eric Blake 已提交
7349 7350 7351 7352 7353 7354 7355 7356
 *   if (virNodeGetCPUStats(conn, cpuNum, NULL, &nparams, 0) == 0 &&
 *       nparams != 0) {
 *       if ((params = malloc(sizeof(virNodeCPUStats) * nparams)) == NULL)
 *           goto error;
 *       memset(params, 0, sizeof(virNodeCPUStats) * nparams);
 *       if (virNodeGetCPUStats(conn, cpuNum, params, &nparams, 0))
 *           goto error;
 *   }
7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378
 *
 * This function doesn't require privileged access to the hypervisor.
 * This function expects the caller to allocate the @params.
 *
 * CPU time Statistics:
 *
 * VIR_NODE_CPU_STATS_KERNEL:
 *     The cumulative CPU time which spends by kernel,
 *     when the node booting up.(nanoseconds)
 * VIR_NODE_CPU_STATS_USER:
 *     The cumulative CPU time which spends by user processes,
 *     when the node booting up.(nanoseconds)
 * VIR_NODE_CPU_STATS_IDLE:
 *     The cumulative idle CPU time, when the node booting up.(nanoseconds)
 * VIR_NODE_CPU_STATS_IOWAIT:
 *     The cumulative I/O wait CPU time, when the node booting up.(nanoseconds)
 * VIR_NODE_CPU_STATS_UTILIZATION:
 *     The CPU utilization. The usage value is in percent and 100%
 *     represents all CPUs on the server.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
7379 7380 7381 7382 7383
int
virNodeGetCPUStats(virConnectPtr conn,
                   int cpuNum,
                   virNodeCPUStatsPtr params,
                   int *nparams, unsigned int flags)
7384
{
7385
    VIR_DEBUG("conn=%p, cpuNum=%d, params=%p, nparams=%d, flags=%x",
7386 7387 7388 7389
              conn, cpuNum, params, nparams ? *nparams : -1, flags);

    virResetLastError();

7390
    virCheckConnectReturn(conn, -1);
7391 7392
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
7393
    if (cpuNum < 0 && cpuNum != VIR_NODE_CPU_STATS_ALL_CPUS) {
7394
        virReportInvalidArg(cpuNum,
7395 7396
                            _("cpuNum in %s only accepts %d as a negative "
                              "value"),
7397
                            __FUNCTION__, VIR_NODE_CPU_STATS_ALL_CPUS);
7398 7399 7400 7401 7402
        goto error;
    }

    if (conn->driver->nodeGetCPUStats) {
        int ret;
7403
        ret = conn->driver->nodeGetCPUStats(conn, cpuNum, params, nparams, flags);
7404 7405 7406 7407
        if (ret < 0)
            goto error;
        return ret;
    }
7408
    virReportUnsupportedError();
7409 7410 7411 7412 7413 7414

error:
    virDispatchError(conn);
    return -1;
}

7415

7416 7417 7418
/**
 * virNodeGetMemoryStats:
 * @conn: pointer to the hypervisor connection.
7419 7420
 * @cellNum: number of node cell. (VIR_NODE_MEMORY_STATS_ALL_CELLS means total
 *           cell statistics)
7421 7422 7423
 * @params: pointer to node memory stats objects
 * @nparams: number of node memory stats (this value should be same or
 *          less than the number of stats supported)
7424
 * @flags: extra flags; not used yet, so callers should always pass 0
7425 7426
 *
 * This function provides memory stats of the node.
7427
 * If you want to get total memory statistics of the node, you must specify
7428
 * VIR_NODE_MEMORY_STATS_ALL_CELLS to @cellNum.
7429 7430 7431 7432 7433 7434
 * The @params array will be filled with the values equal to the number of
 * stats suggested by @nparams
 *
 * As the value of @nparams is dynamic, call the API setting @nparams to 0 and
 * @params as NULL, the API returns the number of parameters supported by the
 * HV by updating @nparams on SUCCESS. The caller should then allocate @params
7435
 * array, i.e. (sizeof(@virNodeMemoryStats) * @nparams) bytes and call
7436 7437 7438 7439
 * the API again.
 *
 * Here is the sample code snippet:
 *
E
Eric Blake 已提交
7440 7441 7442 7443 7444 7445 7446 7447
 *   if (virNodeGetMemoryStats(conn, cellNum, NULL, &nparams, 0) == 0 &&
 *       nparams != 0) {
 *       if ((params = malloc(sizeof(virNodeMemoryStats) * nparams)) == NULL)
 *           goto error;
 *       memset(params, cellNum, 0, sizeof(virNodeMemoryStats) * nparams);
 *       if (virNodeGetMemoryStats(conn, params, &nparams, 0))
 *           goto error;
 *   }
7448 7449 7450 7451 7452 7453
 *
 * This function doesn't require privileged access to the hypervisor.
 * This function expects the caller to allocate the @params.
 *
 * Memory Stats:
 *
7454
 * VIR_NODE_MEMORY_STATS_TOTAL:
7455
 *     The total memory usage.(KB)
7456
 * VIR_NODE_MEMORY_STATS_FREE:
7457 7458
 *     The free memory usage.(KB)
 *     On linux, this usage includes buffers and cached.
7459
 * VIR_NODE_MEMORY_STATS_BUFFERS:
7460
 *     The buffers memory usage.(KB)
7461
 * VIR_NODE_MEMORY_STATS_CACHED:
7462 7463 7464 7465
 *     The cached memory usage.(KB)
 *
 * Returns -1 in case of error, 0 in case of success.
 */
7466 7467 7468 7469 7470
int
virNodeGetMemoryStats(virConnectPtr conn,
                      int cellNum,
                      virNodeMemoryStatsPtr params,
                      int *nparams, unsigned int flags)
7471
{
7472
    VIR_DEBUG("conn=%p, cellNum=%d, params=%p, nparams=%d, flags=%x",
7473 7474 7475 7476
              conn, cellNum, params, nparams ? *nparams : -1, flags);

    virResetLastError();

7477
    virCheckConnectReturn(conn, -1);
7478 7479
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
7480
    if (cellNum < 0 && cellNum != VIR_NODE_MEMORY_STATS_ALL_CELLS) {
7481
        virReportInvalidArg(cpuNum,
7482 7483
                            _("cellNum in %s only accepts %d as a negative "
                              "value"),
7484
                            __FUNCTION__, VIR_NODE_MEMORY_STATS_ALL_CELLS);
7485 7486 7487 7488 7489
        goto error;
    }

    if (conn->driver->nodeGetMemoryStats) {
        int ret;
7490
        ret = conn->driver->nodeGetMemoryStats(conn, cellNum, params, nparams, flags);
7491 7492 7493 7494
        if (ret < 0)
            goto error;
        return ret;
    }
7495
    virReportUnsupportedError();
7496 7497 7498 7499 7500 7501

error:
    virDispatchError(conn);
    return -1;
}

7502

7503 7504 7505
/**
 * virNodeGetFreeMemory:
 * @conn: pointer to the hypervisor connection
7506
 *
D
Daniel Veillard 已提交
7507
 * provides the free memory available on the Node
7508
 * Note: most libvirt APIs provide memory sizes in kibibytes, but in this
D
Daniel Veillard 已提交
7509
 * function the returned value is in bytes. Divide by 1024 as necessary.
7510
 *
D
Daniel Veillard 已提交
7511
 * Returns the available free memory in bytes or 0 in case of error
7512 7513 7514 7515
 */
unsigned long long
virNodeGetFreeMemory(virConnectPtr conn)
{
7516
    VIR_DEBUG("conn=%p", conn);
7517

7518 7519
    virResetLastError();

7520
    virCheckConnectReturn(conn, 0);
7521

7522
    if (conn->driver->nodeGetFreeMemory) {
7523
        unsigned long long ret;
7524
        ret = conn->driver->nodeGetFreeMemory(conn);
7525 7526 7527 7528
        if (ret == 0)
            goto error;
        return ret;
    }
7529

7530
    virReportUnsupportedError();
7531 7532

error:
7533
    virDispatchError(conn);
7534 7535 7536
    return 0;
}

7537

7538 7539 7540 7541 7542 7543 7544 7545 7546 7547
/**
 * virNodeSuspendForDuration:
 * @conn: pointer to the hypervisor connection
 * @target: the state to which the host must be suspended to,
 *         such as: VIR_NODE_SUSPEND_TARGET_MEM (Suspend-to-RAM)
 *                  VIR_NODE_SUSPEND_TARGET_DISK (Suspend-to-Disk)
 *                  VIR_NODE_SUSPEND_TARGET_HYBRID (Hybrid-Suspend,
 *                  which is a combination of the former modes).
 * @duration: the time duration in seconds for which the host
 *            has to be suspended
7548
 * @flags: extra flags; not used yet, so callers should always pass 0
7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564
 *
 * Attempt to suspend the node (host machine) for the given duration of
 * time in the specified state (Suspend-to-RAM, Suspend-to-Disk or
 * Hybrid-Suspend). Schedule the node's Real-Time-Clock interrupt to
 * resume the node after the duration is complete.
 *
 * Returns 0 on success (i.e., the node will be suspended after a short
 * delay), -1 on failure (the operation is not supported, or an attempted
 * suspend is already underway).
 */
int
virNodeSuspendForDuration(virConnectPtr conn,
                          unsigned int target,
                          unsigned long long duration,
                          unsigned int flags)
{
7565 7566
    VIR_DEBUG("conn=%p, target=%d, duration=%lld, flags=%x",
              conn, target, duration, flags);
7567 7568 7569

    virResetLastError();

7570
    virCheckConnectReturn(conn, -1);
7571
    virCheckReadOnlyGoto(conn->flags, error);
7572 7573 7574 7575 7576 7577 7578 7579 7580 7581

    if (conn->driver->nodeSuspendForDuration) {
        int ret;
        ret = conn->driver->nodeSuspendForDuration(conn, target,
                                                   duration, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

7582
    virReportUnsupportedError();
7583 7584 7585 7586 7587 7588

error:
    virDispatchError(conn);
    return -1;
}

7589

7590 7591 7592 7593 7594 7595 7596 7597
/*
 * virNodeGetMemoryParameters:
 * @conn: pointer to the hypervisor connection
 * @params: pointer to memory parameter object
 *          (return value, allocated by the caller)
 * @nparams: pointer to number of memory parameters; input and output
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
7598 7599 7600 7601
 * Get all node memory parameters (parameters unsupported by OS will be
 * omitted).  On input, @nparams gives the size of the @params array;
 * on output, @nparams gives how many slots were filled with parameter
 * information, which might be less but will not exceed the input value.
7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622
 *
 * As a special case, calling with @params as NULL and @nparams as 0 on
 * input will cause @nparams on output to contain the number of parameters
 * supported by the hypervisor. The caller should then allocate @params
 * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
 * again.  See virDomainGetMemoryParameters() for an equivalent usage
 * example.
 *
 * Returns 0 in case of success, and -1 in case of failure.
 */
int
virNodeGetMemoryParameters(virConnectPtr conn,
                           virTypedParameterPtr params,
                           int *nparams,
                           unsigned int flags)
{
    VIR_DEBUG("conn=%p, params=%p, nparams=%p, flags=%x",
              conn, params, nparams, flags);

    virResetLastError();

7623
    virCheckConnectReturn(conn, -1);
7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
    if (*nparams != 0)
        virCheckNonNullArgGoto(params, error);

    if (VIR_DRV_SUPPORTS_FEATURE(conn->driver, conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;

    if (conn->driver->nodeGetMemoryParameters) {
        int ret;
        ret = conn->driver->nodeGetMemoryParameters(conn, params,
                                                    nparams, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

7642
    virReportUnsupportedError();
7643 7644 7645 7646 7647 7648

error:
    virDispatchError(conn);
    return -1;
}

7649

7650 7651 7652 7653 7654 7655 7656 7657 7658
/*
 * virNodeSetMemoryParameters:
 * @conn: pointer to the hypervisor connection
 * @params: pointer to scheduler parameter objects
 * @nparams: number of scheduler parameter objects
 *          (this value can be the same or less than the returned
 *           value nparams of virDomainGetSchedulerType)
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
7659 7660
 * Change all or a subset of the node memory tunables. The function
 * fails if not all of the tunables are supported.
O
Osier Yang 已提交
7661 7662 7663 7664 7665 7666
 *
 * Note that it's not recommended to use this function while the
 * outside tuning program is running (such as ksmtuned under Linux),
 * as they could change the tunables in parallel, which could cause
 * conflicts.
 *
7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678
 * This function may require privileged access to the hypervisor.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virNodeSetMemoryParameters(virConnectPtr conn,
                           virTypedParameterPtr params,
                           int nparams,
                           unsigned int flags)
{
    VIR_DEBUG("conn=%p, params=%p, nparams=%d, flags=%x",
              conn, params, nparams, flags);
7679
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
7680 7681 7682

    virResetLastError();

7683
    virCheckConnectReturn(conn, -1);
7684
    virCheckReadOnlyGoto(conn->flags, error);
7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699
    virCheckNonNullArgGoto(params, error);
    virCheckNonNegativeArgGoto(nparams, error);

    if (virTypedParameterValidateSet(conn, params, nparams) < 0)
        goto error;

    if (conn->driver->nodeSetMemoryParameters) {
        int ret;
        ret = conn->driver->nodeSetMemoryParameters(conn, params,
                                                          nparams, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

7700
    virReportUnsupportedError();
7701 7702 7703 7704 7705

error:
    virDispatchError(conn);
    return -1;
}
7706

7707

7708 7709 7710
/**
 * virDomainGetSchedulerType:
 * @domain: pointer to domain object
7711 7712
 * @nparams: pointer to number of scheduler parameters, can be NULL
 *           (return value)
7713
 *
7714
 * Get the scheduler type and the number of scheduler parameters.
7715 7716 7717 7718 7719 7720 7721 7722
 *
 * Returns NULL in case of error. The caller must free the returned string.
 */
char *
virDomainGetSchedulerType(virDomainPtr domain, int *nparams)
{
    virConnectPtr conn;
    char *schedtype;
7723 7724

    VIR_DOMAIN_DEBUG(domain, "nparams=%p", nparams);
7725

7726 7727
    virResetLastError();

7728
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
7729
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
7730
        virDispatchError(NULL);
7731 7732 7733 7734 7735
        return NULL;
    }
    conn = domain->conn;

    if (conn->driver->domainGetSchedulerType){
7736
        schedtype = conn->driver->domainGetSchedulerType(domain, nparams);
7737 7738
        if (!schedtype)
            goto error;
7739 7740 7741
        return schedtype;
    }

7742
    virReportUnsupportedError();
7743 7744

error:
7745
    virDispatchError(domain->conn);
7746 7747 7748 7749 7750 7751 7752
    return NULL;
}


/**
 * virDomainGetSchedulerParameters:
 * @domain: pointer to domain object
7753
 * @params: pointer to scheduler parameter objects
7754
 *          (return value)
7755
 * @nparams: pointer to number of scheduler parameter objects
7756 7757 7758 7759 7760 7761 7762
 *          (this value should generally be as large as the returned value
 *           nparams of virDomainGetSchedulerType()); input and output
 *
 * Get all scheduler parameters.  On input, @nparams gives the size of the
 * @params array; on output, @nparams gives how many slots were filled
 * with parameter information, which might be less but will not exceed
 * the input value.  @nparams cannot be 0.
7763
 *
7764
 * It is hypervisor specific whether this returns the live or
7765
 * persistent state; for more control, use
7766
 * virDomainGetSchedulerParametersFlags().
7767 7768 7769 7770 7771
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainGetSchedulerParameters(virDomainPtr domain,
7772
                                virTypedParameterPtr params, int *nparams)
7773 7774
{
    virConnectPtr conn;
7775 7776

    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p", params, nparams);
7777

7778 7779
    virResetLastError();

7780
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
7781
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
7782
        virDispatchError(NULL);
7783 7784
        return -1;
    }
7785

7786 7787 7788
    virCheckNonNullArgGoto(params, error);
    virCheckNonNullArgGoto(nparams, error);
    virCheckPositiveArgGoto(*nparams, error);
7789

7790 7791
    conn = domain->conn;

7792 7793
    if (conn->driver->domainGetSchedulerParameters) {
        int ret;
7794
        ret = conn->driver->domainGetSchedulerParameters(domain, params, nparams);
7795 7796 7797 7798
        if (ret < 0)
            goto error;
        return ret;
    }
7799

7800
    virReportUnsupportedError();
7801 7802

error:
7803
    virDispatchError(domain->conn);
7804 7805 7806
    return -1;
}

7807

7808 7809 7810 7811 7812 7813 7814
/**
 * virDomainGetSchedulerParametersFlags:
 * @domain: pointer to domain object
 * @params: pointer to scheduler parameter object
 *          (return value)
 * @nparams: pointer to number of scheduler parameter
 *          (this value should be same than the returned value
7815
 *           nparams of virDomainGetSchedulerType()); input and output
E
Eric Blake 已提交
7816
 * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
7817
 *
7818 7819 7820 7821
 * Get all scheduler parameters.  On input, @nparams gives the size of the
 * @params array; on output, @nparams gives how many slots were filled
 * with parameter information, which might be less but will not exceed
 * the input value.  @nparams cannot be 0.
7822
 *
7823 7824
 * The value of @flags can be exactly VIR_DOMAIN_AFFECT_CURRENT,
 * VIR_DOMAIN_AFFECT_LIVE, or VIR_DOMAIN_AFFECT_CONFIG.
7825
 *
7826 7827
 * Here is a sample code snippet:
 *
E
Eric Blake 已提交
7828 7829 7830 7831 7832 7833 7834 7835
 *   char *ret = virDomainGetSchedulerType(dom, &nparams);
 *   if (ret && nparams != 0) {
 *       if ((params = malloc(sizeof(*params) * nparams)) == NULL)
 *           goto error;
 *       memset(params, 0, sizeof(*params) * nparams);
 *       if (virDomainGetSchedulerParametersFlags(dom, params, &nparams, 0))
 *           goto error;
 *   }
7836
 *
7837 7838 7839 7840 7841 7842 7843 7844 7845
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainGetSchedulerParametersFlags(virDomainPtr domain,
                                     virTypedParameterPtr params, int *nparams,
                                     unsigned int flags)
{
    virConnectPtr conn;

7846
    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p, flags=%x",
7847 7848 7849 7850 7851 7852 7853 7854 7855 7856
                     params, nparams, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

7857 7858 7859
    virCheckNonNullArgGoto(params, error);
    virCheckNonNullArgGoto(nparams, error);
    virCheckPositiveArgGoto(*nparams, error);
7860

E
Eric Blake 已提交
7861 7862 7863
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;
7864 7865 7866 7867

    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
7868
        virReportInvalidArg(flags,
7869 7870
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
7871
                            __FUNCTION__);
7872 7873
        goto error;
    }
7874 7875 7876 7877
    conn = domain->conn;

    if (conn->driver->domainGetSchedulerParametersFlags) {
        int ret;
7878 7879
        ret = conn->driver->domainGetSchedulerParametersFlags(domain, params,
                                                              nparams, flags);
7880 7881 7882 7883 7884
        if (ret < 0)
            goto error;
        return ret;
    }

7885
    virReportUnsupportedError();
7886 7887 7888 7889 7890 7891

error:
    virDispatchError(domain->conn);
    return -1;
}

7892

7893 7894 7895 7896
/**
 * virDomainSetSchedulerParameters:
 * @domain: pointer to domain object
 * @params: pointer to scheduler parameter objects
7897 7898
 * @nparams: number of scheduler parameter objects
 *          (this value can be the same or less than the returned value
7899 7900
 *           nparams of virDomainGetSchedulerType)
 *
7901 7902 7903 7904
 * Change all or a subset or the scheduler parameters.  It is
 * hypervisor-specific whether this sets live, persistent, or both
 * settings; for more control, use
 * virDomainSetSchedulerParametersFlags.
7905 7906 7907 7908
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
7909
virDomainSetSchedulerParameters(virDomainPtr domain,
7910
                                virTypedParameterPtr params, int nparams)
7911 7912
{
    virConnectPtr conn;
7913 7914

    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d", params, nparams);
7915
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
7916

7917 7918
    virResetLastError();

7919
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
7920
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
7921
        virDispatchError(NULL);
7922 7923
        return -1;
    }
7924

7925
    virCheckReadOnlyGoto(domain->conn->flags, error);
7926 7927 7928
    virCheckNonNullArgGoto(params, error);
    virCheckNonNegativeArgGoto(nparams, error);

7929
    if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0)
7930
        goto error;
7931

7932 7933
    conn = domain->conn;

7934 7935
    if (conn->driver->domainSetSchedulerParameters) {
        int ret;
7936
        ret = conn->driver->domainSetSchedulerParameters(domain, params, nparams);
7937 7938 7939 7940
        if (ret < 0)
            goto error;
        return ret;
    }
7941

7942
    virReportUnsupportedError();
7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953

error:
    virDispatchError(domain->conn);
    return -1;
}


/**
 * virDomainSetSchedulerParametersFlags:
 * @domain: pointer to domain object
 * @params: pointer to scheduler parameter objects
7954 7955
 * @nparams: number of scheduler parameter objects
 *          (this value can be the same or less than the returned value
7956
 *           nparams of virDomainGetSchedulerType)
7957
 * @flags: bitwise-OR of virDomainModificationImpact
7958
 *
7959
 * Change a subset or all scheduler parameters.  The value of @flags
7960 7961 7962
 * should be either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of
 * values from VIR_DOMAIN_AFFECT_LIVE and
 * VIR_DOMAIN_AFFECT_CURRENT, although hypervisors vary in which
7963
 * flags are supported.
7964 7965 7966 7967 7968
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainSetSchedulerParametersFlags(virDomainPtr domain,
7969
                                     virTypedParameterPtr params,
7970 7971 7972 7973 7974
                                     int nparams,
                                     unsigned int flags)
{
    virConnectPtr conn;

7975
    VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x",
7976
                     params, nparams, flags);
7977
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
7978 7979 7980 7981 7982 7983 7984 7985

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
7986

7987
    virCheckReadOnlyGoto(domain->conn->flags, error);
7988 7989 7990
    virCheckNonNullArgGoto(params, error);
    virCheckNonNegativeArgGoto(nparams, error);

7991
    if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0)
7992
        goto error;
7993

7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006
    conn = domain->conn;

    if (conn->driver->domainSetSchedulerParametersFlags) {
        int ret;
        ret = conn->driver->domainSetSchedulerParametersFlags(domain,
                                                              params,
                                                              nparams,
                                                              flags);
        if (ret < 0)
            goto error;
        return ret;
    }

8007
    virReportUnsupportedError();
8008 8009

error:
8010
    virDispatchError(domain->conn);
8011 8012 8013 8014
    return -1;
}


8015
/**
8016
 * virDomainBlockStats:
8017
 * @dom: pointer to the domain object
8018
 * @disk: path to the block device, or device shorthand
8019 8020 8021 8022 8023 8024
 * @stats: block device stats (returned)
 * @size: size of stats structure
 *
 * This function returns block device (disk) stats for block
 * devices attached to the domain.
 *
8025
 * The @disk parameter is either the device target shorthand (the
8026 8027 8028 8029 8030
 * <target dev='...'/> sub-element, such as "xvda"), or (since 0.9.8)
 * an unambiguous source name of the block device (the <source
 * file='...'/> sub-element, such as "/path/to/image").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041
 *
 * Domains may have more than one block device.  To get stats for
 * each you should make multiple calls to this function.
 *
 * Individual fields within the stats structure may be returned
 * as -1, which indicates that the hypervisor does not support
 * that particular statistic.
 *
 * Returns: 0 in case of success or -1 in case of failure.
 */
int
8042 8043
virDomainBlockStats(virDomainPtr dom, const char *disk,
                    virDomainBlockStatsPtr stats, size_t size)
8044 8045 8046
{
    virConnectPtr conn;
    struct _virDomainBlockStats stats2 = { -1, -1, -1, -1, -1 };
8047

8048
    VIR_DOMAIN_DEBUG(dom, "disk=%s, stats=%p, size=%zi", disk, stats, size);
8049

8050 8051
    virResetLastError();

8052
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
8053
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
8054
        virDispatchError(NULL);
8055 8056
        return -1;
    }
8057 8058 8059 8060 8061 8062
    virCheckNonNullArgGoto(disk, error);
    virCheckNonNullArgGoto(stats, error);
    if (size > sizeof(stats2)) {
        virReportInvalidArg(size,
                            _("size in %s must not exceed %zu"),
                            __FUNCTION__, sizeof(stats2));
8063 8064
        goto error;
    }
8065 8066 8067
    conn = dom->conn;

    if (conn->driver->domainBlockStats) {
8068
        if (conn->driver->domainBlockStats(dom, disk, &stats2) == -1)
8069
            goto error;
8070

8071
        memcpy(stats, &stats2, size);
8072 8073 8074
        return 0;
    }

8075
    virReportUnsupportedError();
8076 8077

error:
8078
    virDispatchError(dom->conn);
8079 8080 8081
    return -1;
}

8082

O
Osier Yang 已提交
8083 8084 8085
/**
 * virDomainBlockStatsFlags:
 * @dom: pointer to domain object
8086
 * @disk: path to the block device, or device shorthand
O
Osier Yang 已提交
8087 8088
 * @params: pointer to block stats parameter object
 *          (return value)
8089
 * @nparams: pointer to number of block stats; input and output
E
Eric Blake 已提交
8090
 * @flags: bitwise-OR of virTypedParameterFlags
O
Osier Yang 已提交
8091 8092 8093 8094
 *
 * This function is to get block stats parameters for block
 * devices attached to the domain.
 *
8095
 * The @disk parameter is either the device target shorthand (the
8096 8097 8098 8099 8100
 * <target dev='...'/> sub-element, such as "xvda"), or (since 0.9.8)
 * an unambiguous source name of the block device (the <source
 * file='...'/> sub-element, such as "/path/to/image").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
O
Osier Yang 已提交
8101 8102 8103 8104
 *
 * Domains may have more than one block device.  To get stats for
 * each you should make multiple calls to this function.
 *
8105 8106 8107 8108
 * On input, @nparams gives the size of the @params array; on output,
 * @nparams gives how many slots were filled with parameter
 * information, which might be less but will not exceed the input
 * value.
O
Osier Yang 已提交
8109
 *
8110 8111 8112 8113 8114
 * As a special case, calling with @params as NULL and @nparams as 0 on
 * input will cause @nparams on output to contain the number of parameters
 * supported by the hypervisor. (Note that block devices of different types
 * might support different parameters, so it might be necessary to compute
 * @nparams for each block device). The caller should then allocate @params
O
Osier Yang 已提交
8115
 * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
8116
 * again. See virDomainGetMemoryParameters() for more details.
O
Osier Yang 已提交
8117 8118 8119
 *
 * Returns -1 in case of error, 0 in case of success.
 */
8120 8121 8122 8123 8124 8125
int
virDomainBlockStatsFlags(virDomainPtr dom,
                         const char *disk,
                         virTypedParameterPtr params,
                         int *nparams,
                         unsigned int flags)
O
Osier Yang 已提交
8126 8127 8128
{
    virConnectPtr conn;

8129 8130
    VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x",
                     disk, params, nparams ? *nparams : -1, flags);
O
Osier Yang 已提交
8131 8132 8133

    virResetLastError();

8134
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
O
Osier Yang 已提交
8135 8136 8137 8138
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
8139 8140 8141 8142 8143 8144
    virCheckNonNullArgGoto(disk, error);
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
    if (*nparams != 0)
        virCheckNonNullArgGoto(params, error);

E
Eric Blake 已提交
8145 8146 8147
    if (VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;
O
Osier Yang 已提交
8148 8149 8150 8151
    conn = dom->conn;

    if (conn->driver->domainBlockStatsFlags) {
        int ret;
8152
        ret = conn->driver->domainBlockStatsFlags(dom, disk, params, nparams, flags);
O
Osier Yang 已提交
8153 8154 8155 8156
        if (ret < 0)
            goto error;
        return ret;
    }
8157
    virReportUnsupportedError();
O
Osier Yang 已提交
8158 8159 8160 8161 8162 8163 8164

error:
    virDispatchError(dom->conn);
    return -1;
}


8165
/**
8166
 * virDomainInterfaceStats:
8167 8168 8169 8170 8171 8172 8173 8174 8175 8176
 * @dom: pointer to the domain object
 * @path: path to the interface
 * @stats: network interface stats (returned)
 * @size: size of stats structure
 *
 * This function returns network interface stats for interfaces
 * attached to the domain.
 *
 * The path parameter is the name of the network interface.
 *
D
Dan Kenigsberg 已提交
8177
 * Domains may have more than one network interface.  To get stats for
8178 8179 8180 8181 8182 8183 8184 8185 8186
 * each you should make multiple calls to this function.
 *
 * Individual fields within the stats structure may be returned
 * as -1, which indicates that the hypervisor does not support
 * that particular statistic.
 *
 * Returns: 0 in case of success or -1 in case of failure.
 */
int
8187 8188
virDomainInterfaceStats(virDomainPtr dom, const char *path,
                        virDomainInterfaceStatsPtr stats, size_t size)
8189 8190 8191 8192
{
    virConnectPtr conn;
    struct _virDomainInterfaceStats stats2 = { -1, -1, -1, -1,
                                               -1, -1, -1, -1 };
8193 8194 8195

    VIR_DOMAIN_DEBUG(dom, "path=%s, stats=%p, size=%zi",
                     path, stats, size);
8196

8197 8198
    virResetLastError();

8199
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
8200
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
8201
        virDispatchError(NULL);
8202 8203
        return -1;
    }
8204 8205 8206 8207 8208 8209
    virCheckNonNullArgGoto(path, error);
    virCheckNonNullArgGoto(stats, error);
    if (size > sizeof(stats2)) {
        virReportInvalidArg(size,
                            _("size in %s must not exceed %zu"),
                            __FUNCTION__, sizeof(stats2));
8210 8211
        goto error;
    }
8212

8213 8214 8215
    conn = dom->conn;

    if (conn->driver->domainInterfaceStats) {
8216
        if (conn->driver->domainInterfaceStats(dom, path, &stats2) == -1)
8217
            goto error;
8218

8219
        memcpy(stats, &stats2, size);
8220 8221 8222
        return 0;
    }

8223
    virReportUnsupportedError();
8224 8225

error:
8226
    virDispatchError(dom->conn);
8227 8228 8229
    return -1;
}

8230 8231

/**
8232 8233 8234 8235 8236 8237 8238 8239
 * virDomainSetInterfaceParameters:
 * @domain: pointer to domain object
 * @device: the interface name or mac address
 * @params: pointer to interface parameter objects
 * @nparams: number of interface parameter (this value can be the same or
 *          less than the number of parameters supported)
 * @flags: bitwise-OR of virDomainModificationImpact
 *
8240 8241
 * Change a subset or all parameters of interface; currently this
 * includes bandwidth parameters.  The value of @flags should be
8242 8243
 * either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of values
 * VIR_DOMAIN_AFFECT_LIVE and VIR_DOMAIN_AFFECT_CONFIG, although
8244 8245
 * hypervisors vary in which flags are supported.
 *
8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259
 * This function may require privileged access to the hypervisor.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainSetInterfaceParameters(virDomainPtr domain,
                                const char *device,
                                virTypedParameterPtr params,
                                int nparams, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=%x",
                     device, params, nparams, flags);
8260
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
8261 8262 8263 8264 8265 8266 8267 8268

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
8269
    virCheckReadOnlyGoto(domain->conn->flags, error);
8270 8271 8272
    virCheckNonNullArgGoto(params, error);
    virCheckPositiveArgGoto(nparams, error);

8273
    if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0)
8274
        goto error;
8275 8276 8277 8278 8279

    conn = domain->conn;

    if (conn->driver->domainSetInterfaceParameters) {
        int ret;
8280 8281 8282
        ret = conn->driver->domainSetInterfaceParameters(domain, device,
                                                         params, nparams,
                                                         flags);
8283 8284 8285 8286 8287
        if (ret < 0)
            goto error;
        return ret;
    }

8288
    virReportUnsupportedError();
8289 8290 8291 8292 8293 8294

error:
    virDispatchError(domain->conn);
    return -1;
}

8295 8296

/**
8297 8298 8299 8300 8301
 * virDomainGetInterfaceParameters:
 * @domain: pointer to domain object
 * @device: the interface name or mac address
 * @params: pointer to interface parameter objects
 *          (return value, allocated by the caller)
8302 8303
 * @nparams: pointer to number of interface parameter; input and output
 * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339
 *
 * Get all interface parameters. On input, @nparams gives the size of
 * the @params array; on output, @nparams gives how many slots were
 * filled with parameter information, which might be less but will not
 * exceed the input value.
 *
 * As a special case, calling with @params as NULL and @nparams as 0 on
 * input will cause @nparams on output to contain the number of parameters
 * supported by the hypervisor. The caller should then allocate @params
 * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the
 * API again. See virDomainGetMemoryParameters() for an equivalent usage
 * example.
 *
 * This function may require privileged access to the hypervisor. This function
 * expects the caller to allocate the @params.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
int
virDomainGetInterfaceParameters(virDomainPtr domain,
                                const char *device,
                                virTypedParameterPtr params,
                                int *nparams, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=%x",
                     device, params, (nparams) ? *nparams : -1, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
8340 8341 8342 8343 8344
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
    if (*nparams != 0)
        virCheckNonNullArgGoto(params, error);

8345 8346 8347 8348 8349 8350 8351 8352
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;

    conn = domain->conn;

    if (conn->driver->domainGetInterfaceParameters) {
        int ret;
8353 8354 8355
        ret = conn->driver->domainGetInterfaceParameters(domain, device,
                                                         params, nparams,
                                                         flags);
8356 8357 8358 8359
        if (ret < 0)
            goto error;
        return ret;
    }
8360
    virReportUnsupportedError();
8361 8362 8363 8364 8365 8366

error:
    virDispatchError(domain->conn);
    return -1;
}

8367

8368 8369 8370 8371 8372
/**
 * virDomainMemoryStats:
 * @dom: pointer to the domain object
 * @stats: nr_stats-sized array of stat structures (returned)
 * @nr_stats: number of memory statistics requested
8373
 * @flags: extra flags; not used yet, so callers should always pass 0
8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394
 *
 * This function provides memory statistics for the domain.
 *
 * Up to 'nr_stats' elements of 'stats' will be populated with memory statistics
 * from the domain.  Only statistics supported by the domain, the driver, and
 * this version of libvirt will be returned.
 *
 * Memory Statistics:
 *
 * VIR_DOMAIN_MEMORY_STAT_SWAP_IN:
 *     The total amount of data read from swap space (in kb).
 * VIR_DOMAIN_MEMORY_STAT_SWAP_OUT:
 *     The total amount of memory written out to swap space (in kb).
 * VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT:
 *     The number of page faults that required disk IO to service.
 * VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT:
 *     The number of page faults serviced without disk IO.
 * VIR_DOMAIN_MEMORY_STAT_UNUSED:
 *     The amount of memory which is not being used for any purpose (in kb).
 * VIR_DOMAIN_MEMORY_STAT_AVAILABLE:
 *     The total amount of memory available to the domain's OS (in kb).
8395 8396
 * VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON:
 *     Current balloon value (in kb).
8397 8398 8399
 *
 * Returns: The number of stats provided or -1 in case of failure.
 */
8400 8401 8402
int
virDomainMemoryStats(virDomainPtr dom, virDomainMemoryStatPtr stats,
                     unsigned int nr_stats, unsigned int flags)
8403 8404 8405
{
    virConnectPtr conn;
    unsigned long nr_stats_ret = 0;
8406

E
Eric Blake 已提交
8407 8408
    VIR_DOMAIN_DEBUG(dom, "stats=%p, nr_stats=%u, flags=%x",
                     stats, nr_stats, flags);
8409 8410 8411

    virResetLastError();

8412
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
8413
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
8414
        virDispatchError(NULL);
8415 8416
        return -1;
    }
8417

8418 8419 8420 8421 8422 8423 8424 8425
    if (!stats || nr_stats == 0)
        return 0;

    if (nr_stats > VIR_DOMAIN_MEMORY_STAT_NR)
        nr_stats = VIR_DOMAIN_MEMORY_STAT_NR;

    conn = dom->conn;
    if (conn->driver->domainMemoryStats) {
8426 8427
        nr_stats_ret = conn->driver->domainMemoryStats(dom, stats, nr_stats,
                                                       flags);
8428 8429 8430 8431 8432
        if (nr_stats_ret == -1)
            goto error;
        return nr_stats_ret;
    }

8433
    virReportUnsupportedError();
8434 8435

error:
8436
    virDispatchError(dom->conn);
8437 8438 8439
    return -1;
}

8440

R
Richard W.M. Jones 已提交
8441 8442 8443
/**
 * virDomainBlockPeek:
 * @dom: pointer to the domain object
8444
 * @disk: path to the block device, or device shorthand
R
Richard W.M. Jones 已提交
8445 8446 8447
 * @offset: offset within block device
 * @size: size to read
 * @buffer: return buffer (must be at least size bytes)
8448
 * @flags: extra flags; not used yet, so callers should always pass 0
R
Richard W.M. Jones 已提交
8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462
 *
 * This function allows you to read the contents of a domain's
 * disk device.
 *
 * Typical uses for this are to determine if the domain has
 * written a Master Boot Record (indicating that the domain
 * has completed installation), or to try to work out the state
 * of the domain's filesystems.
 *
 * (Note that in the local case you might try to open the
 * block device or file directly, but that won't work in the
 * remote case, nor if you don't have sufficient permission.
 * Hence the need for this call).
 *
8463
 * The @disk parameter is either an unambiguous source name of the
8464 8465 8466 8467 8468
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or (since 0.9.5) the device target shorthand
 * (the <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
R
Richard W.M. Jones 已提交
8469 8470 8471 8472 8473 8474 8475
 *
 * 'offset' and 'size' represent an area which must lie entirely
 * within the device or file.  'size' may be 0 to test if the
 * call would succeed.
 *
 * 'buffer' is the return buffer and must be at least 'size' bytes.
 *
R
Richard W.M. Jones 已提交
8476 8477 8478
 * NB. The remote driver imposes a 64K byte limit on 'size'.
 * For your program to be able to work reliably over a remote
 * connection you should split large requests to <= 65536 bytes.
M
Michal Privoznik 已提交
8479
 * However, with 0.9.13 this RPC limit has been raised to 1M byte.
8480 8481
 * Starting with version 1.0.6 the RPC limit has been raised again.
 * Now large requests up to 16M byte are supported.
R
Richard W.M. Jones 已提交
8482
 *
R
Richard W.M. Jones 已提交
8483 8484 8485
 * Returns: 0 in case of success or -1 in case of failure.
 */
int
8486 8487 8488 8489 8490 8491
virDomainBlockPeek(virDomainPtr dom,
                   const char *disk,
                   unsigned long long offset /* really 64 bits */,
                   size_t size,
                   void *buffer,
                   unsigned int flags)
R
Richard W.M. Jones 已提交
8492 8493
{
    virConnectPtr conn;
8494

8495 8496
    VIR_DOMAIN_DEBUG(dom, "disk=%s, offset=%lld, size=%zi, buffer=%p, flags=%x",
                     disk, offset, size, buffer, flags);
R
Richard W.M. Jones 已提交
8497

8498 8499
    virResetLastError();

8500
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
8501
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
8502
        virDispatchError(NULL);
R
Richard W.M. Jones 已提交
8503 8504 8505
        return -1;
    }
    conn = dom->conn;
8506

8507
    virCheckReadOnlyGoto(dom->conn->flags, error);
8508

8509
    virCheckNonNullArgGoto(disk, error);
R
Richard W.M. Jones 已提交
8510 8511

    /* Allow size == 0 as an access test. */
8512 8513
    if (size > 0)
        virCheckNonNullArgGoto(buffer, error);
R
Richard W.M. Jones 已提交
8514

8515 8516
    if (conn->driver->domainBlockPeek) {
        int ret;
8517
        ret = conn->driver->domainBlockPeek(dom, disk, offset, size,
8518 8519 8520 8521 8522
                                            buffer, flags);
        if (ret < 0)
            goto error;
        return ret;
    }
R
Richard W.M. Jones 已提交
8523

8524
    virReportUnsupportedError();
8525 8526

error:
8527
    virDispatchError(dom->conn);
R
Richard W.M. Jones 已提交
8528 8529
    return -1;
}
8530

8531

O
Osier Yang 已提交
8532 8533 8534 8535
/**
 * virDomainBlockResize:
 * @dom: pointer to the domain object
 * @disk: path to the block image, or shorthand
E
Eric Blake 已提交
8536 8537
 * @size: new size of the block image, see below for unit
 * @flags: bitwise-OR of virDomainBlockResizeFlags
O
Osier Yang 已提交
8538
 *
E
Eric Blake 已提交
8539
 * Resize a block device of domain while the domain is running.  If
8540 8541 8542 8543 8544
 * @flags is 0, then @size is in kibibytes (blocks of 1024 bytes);
 * since 0.9.11, if @flags includes VIR_DOMAIN_BLOCK_RESIZE_BYTES,
 * @size is in bytes instead.  @size is taken directly as the new
 * size.  Depending on the file format, the hypervisor may round up
 * to the next alignment boundary.
O
Osier Yang 已提交
8545 8546 8547 8548 8549 8550 8551 8552
 *
 * The @disk parameter is either an unambiguous source name of the
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or (since 0.9.5) the device target shorthand
 * (the <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
E
Eric Blake 已提交
8553 8554 8555
 * Note that this call may fail if the underlying virtualization hypervisor
 * does not support it; this call requires privileged access to the
 * hypervisor.
O
Osier Yang 已提交
8556 8557 8558 8559
 *
 * Returns: 0 in case of success or -1 in case of failure.
 */
int
8560 8561 8562 8563
virDomainBlockResize(virDomainPtr dom,
                     const char *disk,
                     unsigned long long size,
                     unsigned int flags)
O
Osier Yang 已提交
8564 8565 8566 8567 8568 8569 8570
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(dom, "disk=%s, size=%llu, flags=%x", disk, size, flags);

    virResetLastError();

8571
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
O
Osier Yang 已提交
8572 8573 8574 8575 8576 8577
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = dom->conn;

8578
    virCheckReadOnlyGoto(dom->conn->flags, error);
O
Osier Yang 已提交
8579

8580
    virCheckNonNullArgGoto(disk, error);
O
Osier Yang 已提交
8581 8582 8583 8584 8585 8586 8587 8588 8589

    if (conn->driver->domainBlockResize) {
        int ret;
        ret =conn->driver->domainBlockResize(dom, disk, size, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

8590
    virReportUnsupportedError();
O
Osier Yang 已提交
8591 8592 8593 8594 8595 8596

error:
    virDispatchError(dom->conn);
    return -1;
}

8597

R
Richard W.M. Jones 已提交
8598 8599 8600 8601 8602 8603
/**
 * virDomainMemoryPeek:
 * @dom: pointer to the domain object
 * @start: start of memory to peek
 * @size: size of memory to peek
 * @buffer: return buffer (must be at least size bytes)
8604
 * @flags: bitwise-OR of virDomainMemoryFlags
R
Richard W.M. Jones 已提交
8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625
 *
 * This function allows you to read the contents of a domain's
 * memory.
 *
 * The memory which is read is controlled by the 'start', 'size'
 * and 'flags' parameters.
 *
 * If 'flags' is VIR_MEMORY_VIRTUAL then the 'start' and 'size'
 * parameters are interpreted as virtual memory addresses for
 * whichever task happens to be running on the domain at the
 * moment.  Although this sounds haphazard it is in fact what
 * you want in order to read Linux kernel state, because it
 * ensures that pointers in the kernel image can be interpreted
 * coherently.
 *
 * 'buffer' is the return buffer and must be at least 'size' bytes.
 * 'size' may be 0 to test if the call would succeed.
 *
 * NB. The remote driver imposes a 64K byte limit on 'size'.
 * For your program to be able to work reliably over a remote
 * connection you should split large requests to <= 65536 bytes.
M
Michal Privoznik 已提交
8626
 * However, with 0.9.13 this RPC limit has been raised to 1M byte.
8627 8628
 * Starting with version 1.0.6 the RPC limit has been raised again.
 * Now large requests up to 16M byte are supported.
R
Richard W.M. Jones 已提交
8629 8630 8631 8632
 *
 * Returns: 0 in case of success or -1 in case of failure.
 */
int
8633 8634 8635 8636 8637
virDomainMemoryPeek(virDomainPtr dom,
                    unsigned long long start /* really 64 bits */,
                    size_t size,
                    void *buffer,
                    unsigned int flags)
R
Richard W.M. Jones 已提交
8638 8639
{
    virConnectPtr conn;
8640

8641
    VIR_DOMAIN_DEBUG(dom, "start=%lld, size=%zi, buffer=%p, flags=%x",
8642
                     start, size, buffer, flags);
R
Richard W.M. Jones 已提交
8643

8644 8645
    virResetLastError();

8646
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
8647
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
8648
        virDispatchError(NULL);
R
Richard W.M. Jones 已提交
8649 8650 8651 8652
        return -1;
    }
    conn = dom->conn;

8653
    virCheckReadOnlyGoto(dom->conn->flags, error);
8654

8655
    /* Note on access to physical memory: A VIR_MEMORY_PHYSICAL flag is
R
Richard W.M. Jones 已提交
8656 8657 8658 8659 8660 8661
     * a possibility.  However it isn't really useful unless the caller
     * can also access registers, particularly CR3 on x86 in order to
     * get the Page Table Directory.  Since registers are different on
     * every architecture, that would imply another call to get the
     * machine registers.
     *
8662
     * The QEMU driver handles VIR_MEMORY_VIRTUAL, mapping it
R
Richard W.M. Jones 已提交
8663 8664 8665
     * to the qemu 'memsave' command which does the virtual to physical
     * mapping inside qemu.
     *
8666 8667 8668
     * The QEMU driver also handles VIR_MEMORY_PHYSICAL, mapping it
     * to the qemu 'pmemsave' command.
     *
R
Richard W.M. Jones 已提交
8669 8670 8671 8672 8673 8674 8675 8676
     * At time of writing there is no Xen driver.  However the Xen
     * hypervisor only lets you map physical pages from other domains,
     * and so the Xen driver would have to do the virtual to physical
     * mapping by chasing 2, 3 or 4-level page tables from the PTD.
     * There is example code in libxc (xc_translate_foreign_address)
     * which does this, although we cannot copy this code directly
     * because of incompatible licensing.
     */
8677

8678 8679
    /* Exactly one of these two flags must be set.  */
    if (!(flags & VIR_MEMORY_VIRTUAL) == !(flags & VIR_MEMORY_PHYSICAL)) {
8680
        virReportInvalidArg(flags,
8681 8682
                            _("flags in %s must include VIR_MEMORY_VIRTUAL or "
                              "VIR_MEMORY_PHYSICAL"),
8683
                            __FUNCTION__);
8684
        goto error;
R
Richard W.M. Jones 已提交
8685 8686 8687
    }

    /* Allow size == 0 as an access test. */
8688 8689
    if (size > 0)
        virCheckNonNullArgGoto(buffer, error);
R
Richard W.M. Jones 已提交
8690

8691 8692
    if (conn->driver->domainMemoryPeek) {
        int ret;
8693 8694
        ret = conn->driver->domainMemoryPeek(dom, start, size,
                                             buffer, flags);
8695 8696 8697 8698
        if (ret < 0)
            goto error;
        return ret;
    }
R
Richard W.M. Jones 已提交
8699

8700
    virReportUnsupportedError();
8701 8702

error:
8703
    virDispatchError(dom->conn);
R
Richard W.M. Jones 已提交
8704 8705 8706
    return -1;
}

8707

8708 8709 8710
/**
 * virDomainGetBlockInfo:
 * @domain: a domain object
8711
 * @disk: path to the block device, or device shorthand
8712
 * @info: pointer to a virDomainBlockInfo structure allocated by the user
8713
 * @flags: extra flags; not used yet, so callers should always pass 0
8714 8715 8716
 *
 * Extract information about a domain's block device.
 *
8717
 * The @disk parameter is either an unambiguous source name of the
8718 8719 8720 8721 8722 8723
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or (since 0.9.5) the device target shorthand
 * (the <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
8724 8725 8726
 * Returns 0 in case of success and -1 in case of failure.
 */
int
8727
virDomainGetBlockInfo(virDomainPtr domain, const char *disk,
8728
                      virDomainBlockInfoPtr info, unsigned int flags)
8729 8730
{
    virConnectPtr conn;
8731

E
Eric Blake 已提交
8732
    VIR_DOMAIN_DEBUG(domain, "info=%p, flags=%x", info, flags);
8733 8734 8735 8736

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
8737
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
8738
        virDispatchError(NULL);
8739
        return -1;
8740
    }
8741 8742
    virCheckNonNullArgGoto(disk, error);
    virCheckNonNullArgGoto(info, error);
8743 8744 8745 8746 8747 8748 8749

    memset(info, 0, sizeof(virDomainBlockInfo));

    conn = domain->conn;

    if (conn->driver->domainGetBlockInfo) {
        int ret;
8750
        ret = conn->driver->domainGetBlockInfo(domain, disk, info, flags);
8751 8752 8753 8754 8755
        if (ret < 0)
            goto error;
        return ret;
    }

8756
    virReportUnsupportedError();
8757 8758 8759 8760 8761 8762 8763

error:
    virDispatchError(domain->conn);
    return -1;
}


8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774
/************************************************************************
 *									*
 *		Handling of defined but not running domains		*
 *									*
 ************************************************************************/

/**
 * virDomainDefineXML:
 * @conn: pointer to the hypervisor connection
 * @xml: the XML description for the domain, preferably in UTF-8
 *
8775 8776
 * Define a domain, but does not start it.
 * This definition is persistent, until explicitly undefined with
8777
 * virDomainUndefine(). A previous definition for this domain would be
8778
 * overridden if it already exists.
8779
 *
E
Eric Blake 已提交
8780 8781 8782 8783 8784
 * Some hypervisors may prevent this operation if there is a current
 * block copy operation on a transient domain with the same id as the
 * domain being defined; in that case, use virDomainBlockJobAbort() to
 * stop the block copy first.
 *
8785 8786 8787
 * Returns NULL in case of error, a pointer to the domain otherwise
 */
virDomainPtr
8788 8789
virDomainDefineXML(virConnectPtr conn, const char *xml)
{
8790
    VIR_DEBUG("conn=%p, xml=%s", conn, xml);
8791

8792 8793
    virResetLastError();

8794
    virCheckConnectReturn(conn, NULL);
8795
    virCheckReadOnlyGoto(conn->flags, error);
8796
    virCheckNonNullArgGoto(xml, error);
8797

8798 8799
    if (conn->driver->domainDefineXML) {
        virDomainPtr ret;
8800
        ret = conn->driver->domainDefineXML(conn, xml);
8801 8802 8803 8804
        if (!ret)
            goto error;
        return ret;
    }
8805

8806
    virReportUnsupportedError();
8807 8808

error:
8809
    virDispatchError(conn);
8810
    return NULL;
8811 8812
}

8813

8814 8815 8816 8817
/**
 * virDomainUndefine:
 * @domain: pointer to a defined domain
 *
O
Osier Yang 已提交
8818 8819 8820 8821 8822
 * Undefine a domain. If the domain is running, it's converted to
 * transient domain, without stopping it. If the domain is inactive,
 * the domain configuration is removed.
 *
 * If the domain has a managed save image (see
8823 8824 8825
 * virDomainHasManagedSaveImage()), or if it is inactive and has any
 * snapshot metadata (see virDomainSnapshotNum()), then the undefine will
 * fail. See virDomainUndefineFlags() for more control.
8826 8827 8828 8829
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
8830 8831
virDomainUndefine(virDomainPtr domain)
{
8832
    virConnectPtr conn;
8833

8834
    VIR_DOMAIN_DEBUG(domain);
8835

8836 8837
    virResetLastError();

8838
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
8839
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
8840
        virDispatchError(NULL);
8841
        return -1;
8842
    }
8843
    conn = domain->conn;
8844
    virCheckReadOnlyGoto(conn->flags, error);
8845

8846 8847
    if (conn->driver->domainUndefine) {
        int ret;
8848
        ret = conn->driver->domainUndefine(domain);
8849 8850 8851 8852
        if (ret < 0)
            goto error;
        return ret;
    }
8853

8854
    virReportUnsupportedError();
8855 8856

error:
8857
    virDispatchError(domain->conn);
8858
    return -1;
8859 8860
}

8861

O
Osier Yang 已提交
8862 8863 8864
/**
 * virDomainUndefineFlags:
 * @domain: pointer to a defined domain
8865
 * @flags: bitwise-OR of supported virDomainUndefineFlagsValues
O
Osier Yang 已提交
8866 8867 8868 8869 8870 8871 8872 8873 8874
 *
 * Undefine a domain. If the domain is running, it's converted to
 * transient domain, without stopping it. If the domain is inactive,
 * the domain configuration is removed.
 *
 * If the domain has a managed save image (see virDomainHasManagedSaveImage()),
 * then including VIR_DOMAIN_UNDEFINE_MANAGED_SAVE in @flags will also remove
 * that file, and omitting the flag will cause the undefine process to fail.
 *
8875 8876 8877 8878 8879 8880 8881 8882 8883
 * If the domain is inactive and has any snapshot metadata (see
 * virDomainSnapshotNum()), then including
 * VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA in @flags will also remove
 * that metadata.  Omitting the flag will cause the undefine of an
 * inactive domain to fail.  Active snapshots will retain snapshot
 * metadata until the (now-transient) domain halts, regardless of
 * whether this flag is present.  On hypervisors where snapshots do
 * not use libvirt metadata, this flag has no effect.
 *
O
Osier Yang 已提交
8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901
 * Returns 0 in case of success, -1 in case of error
 */
int
virDomainUndefineFlags(virDomainPtr domain,
                       unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = domain->conn;
8902
    virCheckReadOnlyGoto(conn->flags, error);
O
Osier Yang 已提交
8903 8904 8905

    if (conn->driver->domainUndefineFlags) {
        int ret;
8906
        ret = conn->driver->domainUndefineFlags(domain, flags);
O
Osier Yang 已提交
8907 8908 8909 8910 8911
        if (ret < 0)
            goto error;
        return ret;
    }

8912
    virReportUnsupportedError();
O
Osier Yang 已提交
8913 8914 8915 8916 8917 8918 8919

error:
    virDispatchError(domain->conn);
    return -1;
}


8920 8921 8922 8923
/**
 * virConnectNumOfDefinedDomains:
 * @conn: pointer to the hypervisor connection
 *
8924
 * Provides the number of defined but inactive domains.
8925 8926 8927 8928 8929 8930
 *
 * Returns the number of domain found or -1 in case of error
 */
int
virConnectNumOfDefinedDomains(virConnectPtr conn)
{
8931
    VIR_DEBUG("conn=%p", conn);
8932

8933 8934
    virResetLastError();

8935
    virCheckConnectReturn(conn, -1);
8936

8937
    if (conn->driver->connectNumOfDefinedDomains) {
8938
        int ret;
8939
        ret = conn->driver->connectNumOfDefinedDomains(conn);
8940 8941 8942 8943
        if (ret < 0)
            goto error;
        return ret;
    }
8944

8945
    virReportUnsupportedError();
8946 8947

error:
8948
    virDispatchError(conn);
8949
    return -1;
8950 8951
}

8952

8953 8954 8955 8956 8957 8958
/**
 * virConnectListDefinedDomains:
 * @conn: pointer to the hypervisor connection
 * @names: pointer to an array to store the names
 * @maxnames: size of the array
 *
8959 8960
 * list the defined but inactive domains, stores the pointers to the names
 * in @names
8961
 *
8962 8963 8964 8965 8966 8967 8968 8969
 * For active domains, see virConnectListDomains().  For more control over
 * the results, see virConnectListAllDomains().
 *
 * Returns the number of names provided in the array or -1 in case of error.
 * Note that this command is inherently racy; a domain can be defined between
 * a call to virConnectNumOfDefinedDomains() and this call; you are only
 * guaranteed that all currently defined domains were listed if the return
 * is less than @maxids.  The client must call free() on each returned name.
8970 8971
 */
int
8972
virConnectListDefinedDomains(virConnectPtr conn, char **const names,
8973 8974
                             int maxnames)
{
8975
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
8976

8977 8978
    virResetLastError();

8979
    virCheckConnectReturn(conn, -1);
8980 8981
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
8982

8983
    if (conn->driver->connectListDefinedDomains) {
8984
        int ret;
8985
        ret = conn->driver->connectListDefinedDomains(conn, names, maxnames);
8986 8987 8988 8989
        if (ret < 0)
            goto error;
        return ret;
    }
8990

8991
    virReportUnsupportedError();
8992 8993

error:
8994
    virDispatchError(conn);
8995
    return -1;
8996 8997
}

8998

8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046
/**
 * virConnectListAllDomains:
 * @conn: Pointer to the hypervisor connection.
 * @domains: Pointer to a variable to store the array containing domain objects
 *           or NULL if the list is not required (just returns number of guests).
 * @flags: bitwise-OR of virConnectListAllDomainsFlags
 *
 * Collect a possibly-filtered list of all domains, and return an allocated
 * array of information for each.  This API solves the race inherent in
 * virConnectListDomains() and virConnectListDefinedDomains().
 *
 * Normally, all domains are returned; however, @flags can be used to
 * filter the results for a smaller list of targeted domains.  The valid
 * flags are divided into groups, where each group contains bits that
 * describe mutually exclusive attributes of a domain, and where all bits
 * within a group describe all possible domains.  Some hypervisors might
 * reject explicit bits from a group where the hypervisor cannot make a
 * distinction (for example, not all hypervisors can tell whether domains
 * have snapshots).  For a group supported by a given hypervisor, the
 * behavior when no bits of a group are set is identical to the behavior
 * when all bits in that group are set.  When setting bits from more than
 * one group, it is possible to select an impossible combination (such
 * as an inactive transient domain), in that case a hypervisor may return
 * either 0 or an error.
 *
 * The first group of @flags is VIR_CONNECT_LIST_DOMAINS_ACTIVE (online
 * domains) and VIR_CONNECT_LIST_DOMAINS_INACTIVE (offline domains).
 *
 * The next group of @flags is VIR_CONNECT_LIST_DOMAINS_PERSISTENT (defined
 * domains) and VIR_CONNECT_LIST_DOMAINS_TRANSIENT (running but not defined).
 *
 * The next group of @flags covers various domain states:
 * VIR_CONNECT_LIST_DOMAINS_RUNNING, VIR_CONNECT_LIST_DOMAINS_PAUSED,
 * VIR_CONNECT_LIST_DOMAINS_SHUTOFF, and a catch-all for all other states
 * (such as crashed, this catch-all covers the possibility of adding new
 * states).
 *
 * The remaining groups cover boolean attributes commonly asked about
 * domains; they include VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE and
 * VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE, for filtering based on whether
 * a managed save image exists; VIR_CONNECT_LIST_DOMAINS_AUTOSTART and
 * VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART, for filtering based on autostart;
 * VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT and
 * VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT, for filtering based on whether
 * a domain has snapshots.
 *
 * Example of usage:
 *
E
Eric Blake 已提交
9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060
 *   virDomainPtr *domains;
 *   size_t i;
 *   int ret;
 *   unsigned int flags = VIR_CONNECT_LIST_DOMAINS_RUNNING |
 *                        VIR_CONNECT_LIST_DOMAINS_PERSISTENT;
 *   ret = virConnectListAllDomains(conn, &domains, flags);
 *   if (ret < 0)
 *       error();
 *   for (i = 0; i < ret; i++) {
 *        do_something_with_domain(domains[i]);
 *        //here or in a separate loop if needed
 *        virDomainFree(domains[i]);
 *   }
 *   free(domains);
E
Eric Blake 已提交
9061 9062 9063 9064 9065 9066
 *
 * Returns the number of domains found or -1 and sets domains to NULL in case of
 * error.  On success, the array stored into @domains is guaranteed to have an
 * extra allocated element set to NULL but not included in the return count, to
 * make iteration easier. The caller is responsible for calling virDomainFree()
 * on each array element, then calling free() on @domains.
9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079
 */
int
virConnectListAllDomains(virConnectPtr conn,
                         virDomainPtr **domains,
                         unsigned int flags)
{
    VIR_DEBUG("conn=%p, domains=%p, flags=%x", conn, domains, flags);

    virResetLastError();

    if (domains)
        *domains = NULL;

9080
    virCheckConnectReturn(conn, -1);
9081

9082
    if (conn->driver->connectListAllDomains) {
9083
        int ret;
9084
        ret = conn->driver->connectListAllDomains(conn, domains, flags);
9085 9086 9087 9088 9089
        if (ret < 0)
            goto error;
        return ret;
    }

9090
    virReportUnsupportedError();
9091 9092 9093 9094 9095 9096

error:
    virDispatchError(conn);
    return -1;
}

9097

9098 9099 9100 9101
/**
 * virDomainCreate:
 * @domain: pointer to a defined domain
 *
9102
 * Launch a defined domain. If the call succeeds the domain moves from the
9103 9104 9105
 * defined to the running domains pools.  The domain will be paused only
 * if restoring from managed state created from a paused domain.  For more
 * control, see virDomainCreateWithFlags().
9106 9107 9108 9109
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
9110 9111
virDomainCreate(virDomainPtr domain)
{
9112
    virConnectPtr conn;
9113

9114
    VIR_DOMAIN_DEBUG(domain);
9115

9116 9117
    virResetLastError();

9118
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9119
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
9120
        virDispatchError(NULL);
9121
        return -1;
9122
    }
9123
    conn = domain->conn;
9124
    virCheckReadOnlyGoto(conn->flags, error);
9125

9126 9127
    if (conn->driver->domainCreate) {
        int ret;
9128
        ret = conn->driver->domainCreate(domain);
9129 9130 9131 9132
        if (ret < 0)
            goto error;
        return ret;
    }
9133

9134
    virReportUnsupportedError();
9135 9136

error:
9137
    virDispatchError(domain->conn);
9138
    return -1;
9139 9140
}

9141

9142 9143 9144
/**
 * virDomainCreateWithFlags:
 * @domain: pointer to a defined domain
9145
 * @flags: bitwise-OR of supported virDomainCreateFlags
9146 9147 9148 9149
 *
 * Launch a defined domain. If the call succeeds the domain moves from the
 * defined to the running domains pools.
 *
9150 9151 9152 9153 9154 9155
 * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain
 * has a managed save image that requested paused state (see
 * virDomainManagedSave()) the guest domain will be started, but its
 * CPUs will remain paused. The CPUs can later be manually started
 * using virDomainResume().  In all other cases, the guest domain will
 * be running.
9156 9157 9158 9159
 *
 * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
 * domain will be automatically destroyed when the virConnectPtr
 * object is finally released. This will also happen if the
E
Eric Blake 已提交
9160
 * client application crashes / loses its connection to the
9161
 * libvirtd daemon. Any domains marked for auto destroy will
9162
 * block attempts at migration, save-to-file, or snapshots.
9163
 *
9164 9165 9166 9167 9168 9169
 * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a
 * managed save file for this domain (created by virDomainManagedSave()),
 * then libvirt will attempt to bypass the file system cache while restoring
 * the file, or fail if it cannot do so for the given system; this can allow
 * less pressure on file system cache, but also risks slowing loads from NFS.
 *
9170 9171 9172
 * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save
 * file for this domain is discarded, and the domain boots from scratch.
 *
9173 9174 9175
 * Returns 0 in case of success, -1 in case of error
 */
int
9176 9177
virDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
{
9178
    virConnectPtr conn;
9179

9180
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
9181 9182 9183 9184

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9185
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
9186
        virDispatchError(NULL);
9187
        return -1;
9188 9189
    }
    conn = domain->conn;
9190
    virCheckReadOnlyGoto(conn->flags, error);
9191 9192 9193

    if (conn->driver->domainCreateWithFlags) {
        int ret;
9194
        ret = conn->driver->domainCreateWithFlags(domain, flags);
9195 9196 9197 9198 9199
        if (ret < 0)
            goto error;
        return ret;
    }

9200
    virReportUnsupportedError();
9201 9202 9203 9204 9205 9206

error:
    virDispatchError(domain->conn);
    return -1;
}

9207

9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266
/**
 * virDomainCreateWithFiles:
 * @domain: pointer to a defined domain
 * @nfiles: number of file descriptors passed
 * @files: list of file descriptors passed
 * @flags: bitwise-OR of supported virDomainCreateFlags
 *
 * Launch a defined domain. If the call succeeds the domain moves from the
 * defined to the running domains pools.
 *
 * @files provides an array of file descriptors which will be
 * made available to the 'init' process of the guest. The file
 * handles exposed to the guest will be renumbered to start
 * from 3 (ie immediately following stderr). This is only
 * supported for guests which use container based virtualization
 * technology.
 *
 * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain
 * has a managed save image that requested paused state (see
 * virDomainManagedSave()) the guest domain will be started, but its
 * CPUs will remain paused. The CPUs can later be manually started
 * using virDomainResume().  In all other cases, the guest domain will
 * be running.
 *
 * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
 * domain will be automatically destroyed when the virConnectPtr
 * object is finally released. This will also happen if the
 * client application crashes / loses its connection to the
 * libvirtd daemon. Any domains marked for auto destroy will
 * block attempts at migration, save-to-file, or snapshots.
 *
 * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a
 * managed save file for this domain (created by virDomainManagedSave()),
 * then libvirt will attempt to bypass the file system cache while restoring
 * the file, or fail if it cannot do so for the given system; this can allow
 * less pressure on file system cache, but also risks slowing loads from NFS.
 *
 * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save
 * file for this domain is discarded, and the domain boots from scratch.
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
virDomainCreateWithFiles(virDomainPtr domain, unsigned int nfiles,
                         int *files, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "nfiles=%u, files=%p, flags=%x",
                     nfiles, files, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = domain->conn;
9267
    virCheckReadOnlyGoto(conn->flags, error);
9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278

    if (conn->driver->domainCreateWithFiles) {
        int ret;
        ret = conn->driver->domainCreateWithFiles(domain,
                                                  nfiles, files,
                                                  flags);
        if (ret < 0)
            goto error;
        return ret;
    }

9279
    virReportUnsupportedError();
9280 9281 9282 9283 9284 9285

error:
    virDispatchError(domain->conn);
    return -1;
}

9286

9287 9288 9289
/**
 * virDomainGetAutostart:
 * @domain: a domain object
9290
 * @autostart: the value returned
9291
 *
9292
 * Provides a boolean value indicating whether the domain
9293 9294 9295 9296 9297 9298 9299
 * configured to be automatically started when the host
 * machine boots.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virDomainGetAutostart(virDomainPtr domain,
9300 9301 9302
                      int *autostart)
{
    virConnectPtr conn;
9303 9304

    VIR_DOMAIN_DEBUG(domain, "autostart=%p", autostart);
9305

9306 9307 9308
    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9309
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
9310
        virDispatchError(NULL);
9311
        return -1;
9312
    }
9313
    virCheckNonNullArgGoto(autostart, error);
9314

9315 9316
    conn = domain->conn;

9317 9318
    if (conn->driver->domainGetAutostart) {
        int ret;
9319
        ret = conn->driver->domainGetAutostart(domain, autostart);
9320 9321 9322 9323
        if (ret < 0)
            goto error;
        return ret;
    }
9324

9325
    virReportUnsupportedError();
9326 9327

error:
9328
    virDispatchError(domain->conn);
9329
    return -1;
9330 9331
}

9332

9333 9334 9335
/**
 * virDomainSetAutostart:
 * @domain: a domain object
9336
 * @autostart: whether the domain should be automatically started 0 or 1
9337 9338 9339 9340 9341 9342 9343 9344
 *
 * Configure the domain to be automatically started
 * when the host machine boots.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virDomainSetAutostart(virDomainPtr domain,
9345 9346 9347
                      int autostart)
{
    virConnectPtr conn;
9348 9349

    VIR_DOMAIN_DEBUG(domain, "autostart=%d", autostart);
9350

9351 9352 9353
    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9354
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
9355
        virDispatchError(NULL);
9356
        return -1;
9357 9358
    }

9359 9360
    conn = domain->conn;

9361
    virCheckReadOnlyGoto(domain->conn->flags, error);
9362

9363 9364
    if (conn->driver->domainSetAutostart) {
        int ret;
9365
        ret = conn->driver->domainSetAutostart(domain, autostart);
9366 9367 9368 9369
        if (ret < 0)
            goto error;
        return ret;
    }
9370

9371
    virReportUnsupportedError();
9372 9373

error:
9374
    virDispatchError(domain->conn);
9375
    return -1;
9376 9377
}

9378

9379 9380 9381
/**
 * virDomainInjectNMI:
 * @domain: pointer to domain object, or NULL for Domain0
9382
 * @flags: extra flags; not used yet, so callers should always pass 0
9383 9384 9385 9386 9387
 *
 * Send NMI to the guest
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
9388 9389
int
virDomainInjectNMI(virDomainPtr domain, unsigned int flags)
9390 9391
{
    virConnectPtr conn;
9392
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
9393 9394 9395 9396 9397 9398 9399 9400

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
9401
    virCheckReadOnlyGoto(domain->conn->flags, error);
9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412

    conn = domain->conn;

    if (conn->driver->domainInjectNMI) {
        int ret;
        ret = conn->driver->domainInjectNMI(domain, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

9413
    virReportUnsupportedError();
9414 9415 9416 9417 9418 9419

error:
    virDispatchError(domain->conn);
    return -1;
}

9420

9421 9422 9423 9424 9425 9426 9427
/**
 * virDomainSendKey:
 * @domain:    pointer to domain object, or NULL for Domain0
 * @codeset:   the code set of keycodes, from virKeycodeSet
 * @holdtime:  the duration (in milliseconds) that the keys will be held
 * @keycodes:  array of keycodes
 * @nkeycodes: number of keycodes, up to VIR_DOMAIN_SEND_KEY_MAX_KEYS
9428
 * @flags: extra flags; not used yet, so callers should always pass 0
9429 9430 9431 9432 9433
 *
 * Send key(s) to the guest.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
9434 9435 9436 9437 9438 9439 9440
int
virDomainSendKey(virDomainPtr domain,
                 unsigned int codeset,
                 unsigned int holdtime,
                 unsigned int *keycodes,
                 int nkeycodes,
                 unsigned int flags)
9441 9442
{
    virConnectPtr conn;
9443
    VIR_DOMAIN_DEBUG(domain, "codeset=%u, holdtime=%u, nkeycodes=%u, flags=%x",
9444 9445 9446 9447 9448 9449 9450 9451 9452
                     codeset, holdtime, nkeycodes, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
9453

9454 9455 9456
    conn = domain->conn;

    virCheckReadOnlyGoto(conn->flags, error);
9457 9458 9459 9460 9461 9462 9463 9464 9465 9466
    virCheckNonNullArgGoto(keycodes, error);
    virCheckPositiveArgGoto(nkeycodes, error);

    if (nkeycodes > VIR_DOMAIN_SEND_KEY_MAX_KEYS) {
        virReportInvalidArg(nkeycodes,
                            _("nkeycodes in %s must be <= %d"),
                            __FUNCTION__, VIR_DOMAIN_SEND_KEY_MAX_KEYS);
        goto error;
    }

9467 9468 9469 9470 9471 9472 9473 9474 9475
    if (conn->driver->domainSendKey) {
        int ret;
        ret = conn->driver->domainSendKey(domain, codeset, holdtime,
                                          keycodes, nkeycodes, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

9476
    virReportUnsupportedError();
9477 9478 9479 9480 9481 9482

error:
    virDispatchError(domain->conn);
    return -1;
}

9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516

/**
 * virDomainSendProcessSignal:
 * @domain: pointer to domain object
 * @pid_value: a positive integer process ID, or negative integer process group ID
 * @signum: a signal from the virDomainProcessSignal enum
 * @flags: one of the virDomainProcessSignalFlag values
 *
 * Send a signal to the designated process in the guest
 *
 * The signal numbers must be taken from the virDomainProcessSignal
 * enum. These will be translated to the corresponding signal
 * number for the guest OS, by the guest agent delivering the
 * signal. If there is no mapping from virDomainProcessSignal to
 * the native OS signals, this API will report an error.
 *
 * If @pid_value is an integer greater than zero, it is
 * treated as a process ID. If @pid_value is an integer
 * less than zero, it is treated as a process group ID.
 * All the @pid_value numbers are from the container/guest
 * namespace. The value zero is not valid.
 *
 * Not all hypervisors will support sending signals to
 * arbitrary processes or process groups. If this API is
 * implemented the minimum requirement is to be able to
 * use @pid_value==1 (i.e. kill init). No other value is
 * required to be supported.
 *
 * If the @signum is VIR_DOMAIN_PROCESS_SIGNAL_NOP then this
 * API will simply report whether the process is running in
 * the container/guest.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
9517 9518 9519 9520 9521
int
virDomainSendProcessSignal(virDomainPtr domain,
                           long long pid_value,
                           unsigned int signum,
                           unsigned int flags)
9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536
{
    virConnectPtr conn;
    VIR_DOMAIN_DEBUG(domain, "pid=%lld, signum=%u flags=%x",
                     pid_value, signum, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    virCheckNonZeroArgGoto(pid_value, error);

9537
    virCheckReadOnlyGoto(domain->conn->flags, error);
9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551

    conn = domain->conn;

    if (conn->driver->domainSendProcessSignal) {
        int ret;
        ret = conn->driver->domainSendProcessSignal(domain,
                                                    pid_value,
                                                    signum,
                                                    flags);
        if (ret < 0)
            goto error;
        return ret;
    }

9552
    virReportUnsupportedError();
9553 9554 9555 9556 9557 9558 9559

error:
    virDispatchError(domain->conn);
    return -1;
}


9560 9561 9562 9563 9564 9565 9566 9567
/**
 * virDomainSetVcpus:
 * @domain: pointer to domain object, or NULL for Domain0
 * @nvcpus: the new number of virtual CPUs for this domain
 *
 * Dynamically change the number of virtual CPUs used by the domain.
 * Note that this call may fail if the underlying virtualization hypervisor
 * does not support it or if growing the number is arbitrary limited.
9568
 * This function may require privileged access to the hypervisor.
9569
 *
9570
 * This command only changes the runtime configuration of the domain,
E
Eric Blake 已提交
9571 9572 9573
 * so can only be called on an active domain.  It is hypervisor-dependent
 * whether it also affects persistent configuration; for more control,
 * use virDomainSetVcpusFlags().
9574
 *
9575 9576 9577 9578 9579
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
{
9580
    virConnectPtr conn;
9581 9582

    VIR_DOMAIN_DEBUG(domain, "nvcpus=%u", nvcpus);
9583

9584 9585
    virResetLastError();

9586
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9587
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
9588
        virDispatchError(NULL);
9589
        return -1;
9590
    }
9591
    virCheckReadOnlyGoto(domain->conn->flags, error);
9592

9593 9594
    virCheckNonZeroArgGoto(nvcpus, error);

9595
    conn = domain->conn;
9596

9597 9598
    if (conn->driver->domainSetVcpus) {
        int ret;
9599
        ret = conn->driver->domainSetVcpus(domain, nvcpus);
9600 9601 9602 9603
        if (ret < 0)
            goto error;
        return ret;
    }
9604

9605
    virReportUnsupportedError();
9606 9607

error:
9608
    virDispatchError(domain->conn);
9609
    return -1;
9610 9611
}

9612

E
Eric Blake 已提交
9613 9614 9615 9616
/**
 * virDomainSetVcpusFlags:
 * @domain: pointer to domain object, or NULL for Domain0
 * @nvcpus: the new number of virtual CPUs for this domain, must be at least 1
9617
 * @flags: bitwise-OR of virDomainVcpuFlags
E
Eric Blake 已提交
9618 9619 9620 9621
 *
 * Dynamically change the number of virtual CPUs used by the domain.
 * Note that this call may fail if the underlying virtualization hypervisor
 * does not support it or if growing the number is arbitrary limited.
9622
 * This function may require privileged access to the hypervisor.
E
Eric Blake 已提交
9623
 *
9624
 * @flags may include VIR_DOMAIN_AFFECT_LIVE to affect a running
E
Eric Blake 已提交
9625
 * domain (which may fail if domain is not active), or
9626
 * VIR_DOMAIN_AFFECT_CONFIG to affect the next boot via the XML
E
Eric Blake 已提交
9627
 * description of the domain.  Both flags may be set.
9628 9629 9630 9631
 * If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT),
 * then an inactive domain modifies persistent setup, while an active domain
 * is hypervisor-dependent on whether just live or both live and persistent
 * state is changed.
E
Eric Blake 已提交
9632 9633
 *
 * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then
9634
 * VIR_DOMAIN_AFFECT_LIVE must be clear, and only the maximum virtual
E
Eric Blake 已提交
9635 9636 9637 9638
 * CPU limit is altered; generally, this value must be less than or
 * equal to virConnectGetMaxVcpus().  Otherwise, this call affects the
 * current virtual CPU limit, which must be less than or equal to the
 * maximum limit.
9639
 *
9640 9641 9642 9643
 * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of processors is
 * modified inside the guest instead of the hypervisor. This flag can only
 * be used with live guests and is incompatible with VIR_DOMAIN_VCPU_MAXIMUM.
 * The usage of this flag may require a guest agent configured.
9644
 *
9645
 * Not all hypervisors can support all flag combinations.
E
Eric Blake 已提交
9646 9647 9648 9649 9650 9651 9652 9653
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
                       unsigned int flags)
{
    virConnectPtr conn;
9654

9655
    VIR_DOMAIN_DEBUG(domain, "nvcpus=%u, flags=%x", nvcpus, flags);
E
Eric Blake 已提交
9656 9657 9658 9659

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9660
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
E
Eric Blake 已提交
9661
        virDispatchError(NULL);
9662
        return -1;
E
Eric Blake 已提交
9663
    }
9664
    virCheckReadOnlyGoto(domain->conn->flags, error);
E
Eric Blake 已提交
9665

9666
    if (flags & VIR_DOMAIN_VCPU_GUEST &&
9667 9668 9669
        flags & VIR_DOMAIN_VCPU_MAXIMUM) {
        virReportInvalidArg(flags,
                            _("flags 'VIR_DOMAIN_VCPU_MAXIMUM' and "
9670
                              "'VIR_DOMAIN_VCPU_GUEST' in '%s' are mutually "
9671 9672 9673 9674
                              "exclusive"), __FUNCTION__);
        goto error;
    }

9675 9676
    virCheckNonZeroArgGoto(nvcpus, error);

E
Eric Blake 已提交
9677 9678 9679 9680
    if ((unsigned short) nvcpus != nvcpus) {
        virLibDomainError(VIR_ERR_OVERFLOW, _("input too large: %u"), nvcpus);
        goto error;
    }
E
Eric Blake 已提交
9681 9682 9683 9684
    conn = domain->conn;

    if (conn->driver->domainSetVcpusFlags) {
        int ret;
9685
        ret = conn->driver->domainSetVcpusFlags(domain, nvcpus, flags);
E
Eric Blake 已提交
9686 9687 9688 9689 9690
        if (ret < 0)
            goto error;
        return ret;
    }

9691
    virReportUnsupportedError();
E
Eric Blake 已提交
9692 9693 9694 9695 9696 9697

error:
    virDispatchError(domain->conn);
    return -1;
}

9698

E
Eric Blake 已提交
9699 9700 9701
/**
 * virDomainGetVcpusFlags:
 * @domain: pointer to domain object, or NULL for Domain0
9702
 * @flags: bitwise-OR of virDomainVcpuFlags
E
Eric Blake 已提交
9703 9704 9705
 *
 * Query the number of virtual CPUs used by the domain.  Note that
 * this call may fail if the underlying virtualization hypervisor does
9706
 * not support it.  This function may require privileged access to the
E
Eric Blake 已提交
9707 9708
 * hypervisor.
 *
9709 9710 9711 9712 9713 9714 9715
 * If @flags includes VIR_DOMAIN_AFFECT_LIVE, this will query a
 * running domain (which will fail if domain is not active); if
 * it includes VIR_DOMAIN_AFFECT_CONFIG, this will query the XML
 * description of the domain.  It is an error to set both flags.
 * If neither flag is set (that is, VIR_DOMAIN_AFFECT_CURRENT),
 * then the configuration queried depends on whether the domain
 * is currently running.
E
Eric Blake 已提交
9716 9717 9718
 *
 * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then the maximum
 * virtual CPU limit is queried.  Otherwise, this call queries the
9719 9720
 * current virtual CPU count.
 *
9721 9722 9723
 * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of the processors
 * is modified in the guest instead of the hypervisor. This flag is only usable
 * on live domains. Guest agent may be needed for this flag to be available.
E
Eric Blake 已提交
9724
 *
9725
 * Returns the number of vCPUs in case of success, -1 in case of failure.
E
Eric Blake 已提交
9726 9727 9728 9729 9730
 */
int
virDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
{
    virConnectPtr conn;
9731

9732
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
E
Eric Blake 已提交
9733 9734 9735 9736

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9737
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
E
Eric Blake 已提交
9738
        virDispatchError(NULL);
9739
        return -1;
E
Eric Blake 已提交
9740 9741
    }

9742
    /* At most one of these two flags should be set.  */
9743 9744
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
9745
        virReportInvalidArg(flags,
9746 9747
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
9748
                            __FUNCTION__);
E
Eric Blake 已提交
9749 9750 9751 9752 9753 9754
        goto error;
    }
    conn = domain->conn;

    if (conn->driver->domainGetVcpusFlags) {
        int ret;
9755
        ret = conn->driver->domainGetVcpusFlags(domain, flags);
E
Eric Blake 已提交
9756 9757 9758 9759 9760
        if (ret < 0)
            goto error;
        return ret;
    }

9761
    virReportUnsupportedError();
E
Eric Blake 已提交
9762 9763 9764 9765 9766 9767

error:
    virDispatchError(domain->conn);
    return -1;
}

9768

9769 9770 9771 9772 9773
/**
 * virDomainPinVcpu:
 * @domain: pointer to domain object, or NULL for Domain0
 * @vcpu: virtual CPU number
 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN)
E
Eric Blake 已提交
9774 9775 9776
 *      Each bit set to 1 means that corresponding CPU is usable.
 *      Bytes are stored in little-endian order: CPU0-7, 8-15...
 *      In each byte, lowest CPU number is least significant bit.
9777
 * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in
O
Osier Yang 已提交
9778 9779 9780
 *      underlying virtualization system (Xen...).
 *      If maplen < size, missing bytes are set to zero.
 *      If maplen > size, failure code is returned.
9781
 *
9782
 * Dynamically change the real CPUs which can be allocated to a virtual CPU.
9783
 * This function may require privileged access to the hypervisor.
9784
 *
9785 9786 9787
 * This command only changes the runtime configuration of the domain,
 * so can only be called on an active domain.
 *
9788 9789 9790 9791 9792 9793
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainPinVcpu(virDomainPtr domain, unsigned int vcpu,
                 unsigned char *cpumap, int maplen)
{
9794
    virConnectPtr conn;
9795 9796 9797

    VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d",
                     vcpu, cpumap, maplen);
9798

9799 9800
    virResetLastError();

9801
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
9802
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
9803
        virDispatchError(NULL);
9804
        return -1;
9805
    }
9806
    virCheckReadOnlyGoto(domain->conn->flags, error);
9807

9808 9809 9810 9811 9812 9813
    virCheckNonNullArgGoto(cpumap, error);
    virCheckPositiveArgGoto(maplen, error);

    if ((unsigned short) vcpu != vcpu) {
        virLibDomainError(VIR_ERR_OVERFLOW, _("input too large: %u"), vcpu);
        goto error;
9814
    }
9815

9816 9817
    conn = domain->conn;

9818 9819
    if (conn->driver->domainPinVcpu) {
        int ret;
9820
        ret = conn->driver->domainPinVcpu(domain, vcpu, cpumap, maplen);
9821 9822 9823 9824
        if (ret < 0)
            goto error;
        return ret;
    }
9825

9826
    virReportUnsupportedError();
9827 9828

error:
9829
    virDispatchError(domain->conn);
9830
    return -1;
9831 9832
}

9833

9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845
/**
 * virDomainPinVcpuFlags:
 * @domain: pointer to domain object, or NULL for Domain0
 * @vcpu: virtual CPU number
 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN)
 *      Each bit set to 1 means that corresponding CPU is usable.
 *      Bytes are stored in little-endian order: CPU0-7, 8-15...
 *      In each byte, lowest CPU number is least significant bit.
 * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in
 *      underlying virtualization system (Xen...).
 *      If maplen < size, missing bytes are set to zero.
 *      If maplen > size, failure code is returned.
9846
 * @flags: bitwise-OR of virDomainModificationImpact
9847 9848
 *
 * Dynamically change the real CPUs which can be allocated to a virtual CPU.
9849
 * This function may require privileged access to the hypervisor.
9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861
 *
 * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
 * Both flags may be set.
 * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain
 * and may fail if domain is not alive.
 * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
 * and will fail for transient domains. If neither flag is specified (that is,
 * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies
 * persistent setup, while an active domain is hypervisor-dependent on whether
 * just live or both live and persistent state is changed.
 * Not all hypervisors can support all flag combinations.
 *
E
Eric Blake 已提交
9862
 * See also virDomainGetVcpuPinInfo for querying this information.
9863
 *
9864 9865 9866 9867 9868 9869 9870 9871 9872
 * Returns 0 in case of success, -1 in case of failure.
 *
 */
int
virDomainPinVcpuFlags(virDomainPtr domain, unsigned int vcpu,
                      unsigned char *cpumap, int maplen, unsigned int flags)
{
    virConnectPtr conn;

9873
    VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d, flags=%x",
9874 9875 9876 9877 9878 9879 9880 9881 9882 9883
                     vcpu, cpumap, maplen, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

9884
    virCheckReadOnlyGoto(domain->conn->flags, error);
9885

9886 9887 9888 9889 9890
    virCheckNonNullArgGoto(cpumap, error);
    virCheckPositiveArgGoto(maplen, error);

    if ((unsigned short) vcpu != vcpu) {
        virLibDomainError(VIR_ERR_OVERFLOW, _("input too large: %u"), vcpu);
9891 9892 9893 9894 9895 9896 9897
        goto error;
    }

    conn = domain->conn;

    if (conn->driver->domainPinVcpuFlags) {
        int ret;
9898
        ret = conn->driver->domainPinVcpuFlags(domain, vcpu, cpumap, maplen, flags);
9899 9900 9901 9902 9903
        if (ret < 0)
            goto error;
        return ret;
    }

9904
    virReportUnsupportedError();
9905 9906 9907 9908 9909 9910

error:
    virDispatchError(domain->conn);
    return -1;
}

9911

9912
/**
E
Eric Blake 已提交
9913
 * virDomainGetVcpuPinInfo:
9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925
 * @domain: pointer to domain object, or NULL for Domain0
 * @ncpumaps: the number of cpumap (listed first to match virDomainGetVcpus)
 * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this
 *     domain (in 8-bit bytes) (OUT)
 *     It's assumed there is <ncpumaps> cpumap in cpumaps array.
 *     The memory allocated to cpumaps must be (ncpumaps * maplen) bytes
 *     (ie: calloc(ncpumaps, maplen)).
 *     One cpumap inside cpumaps has the format described in
 *     virDomainPinVcpu() API.
 *     Must not be NULL.
 * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map.
 *     Must be positive.
9926
 * @flags: bitwise-OR of virDomainModificationImpact
9927 9928 9929 9930 9931 9932 9933 9934 9935 9936
 *     Must not be VIR_DOMAIN_AFFECT_LIVE and
 *     VIR_DOMAIN_AFFECT_CONFIG concurrently.
 *
 * Query the CPU affinity setting of all virtual CPUs of domain, store it
 * in cpumaps.
 *
 * Returns the number of virtual CPUs in case of success,
 * -1 in case of failure.
 */
int
9937 9938
virDomainGetVcpuPinInfo(virDomainPtr domain, int ncpumaps,
                        unsigned char *cpumaps, int maplen, unsigned int flags)
9939 9940 9941
{
    virConnectPtr conn;

9942
    VIR_DOMAIN_DEBUG(domain, "ncpumaps=%d, cpumaps=%p, maplen=%d, flags=%x",
9943 9944 9945 9946 9947 9948 9949 9950 9951 9952
                     ncpumaps, cpumaps, maplen, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

9953 9954 9955 9956
    virCheckNonNullArgGoto(cpumaps, error);
    virCheckPositiveArgGoto(ncpumaps, error);
    virCheckPositiveArgGoto(maplen, error);

E
Eric Blake 已提交
9957 9958 9959 9960 9961
    if (INT_MULTIPLY_OVERFLOW(ncpumaps, maplen)) {
        virLibDomainError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"),
                          ncpumaps, maplen);
        goto error;
    }
9962

9963 9964 9965
    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
9966
        virReportInvalidArg(flags,
9967 9968
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
9969
                            __FUNCTION__);
9970 9971
        goto error;
    }
9972 9973
    conn = domain->conn;

E
Eric Blake 已提交
9974
    if (conn->driver->domainGetVcpuPinInfo) {
9975
        int ret;
9976 9977
        ret = conn->driver->domainGetVcpuPinInfo(domain, ncpumaps,
                                                 cpumaps, maplen, flags);
9978 9979 9980 9981 9982
        if (ret < 0)
            goto error;
        return ret;
    }

9983
    virReportUnsupportedError();
9984 9985 9986 9987 9988 9989

error:
    virDispatchError(domain->conn);
    return -1;
}

9990

9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039
/**
 * virDomainPinEmulator:
 * @domain: pointer to domain object, or NULL for Domain0
 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN)
 *      Each bit set to 1 means that corresponding CPU is usable.
 *      Bytes are stored in little-endian order: CPU0-7, 8-15...
 *      In each byte, lowest CPU number is least significant bit.
 * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in
 *      underlying virtualization system (Xen...).
 *      If maplen < size, missing bytes are set to zero.
 *      If maplen > size, failure code is returned.
 * @flags: bitwise-OR of virDomainModificationImpact
 *
 * Dynamically change the real CPUs which can be allocated to all emulator
 * threads. This function may require privileged access to the hypervisor.
 *
 * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
 * Both flags may be set.
 * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain
 * and may fail if domain is not alive.
 * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
 * and will fail for transient domains. If neither flag is specified (that is,
 * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies
 * persistent setup, while an active domain is hypervisor-dependent on whether
 * just live or both live and persistent state is changed.
 * Not all hypervisors can support all flag combinations.
 *
 * See also virDomainGetEmulatorPinInfo for querying this information.
 *
 * Returns 0 in case of success, -1 in case of failure.
 *
 */
int
virDomainPinEmulator(virDomainPtr domain, unsigned char *cpumap,
                     int maplen, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=%x",
                     cpumap, maplen, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

10040
    virCheckReadOnlyGoto(domain->conn->flags, error);
10041

10042 10043
    virCheckNonNullArgGoto(cpumap, error);
    virCheckPositiveArgGoto(maplen, error);
10044 10045 10046 10047 10048

    conn = domain->conn;

    if (conn->driver->domainPinEmulator) {
        int ret;
10049
        ret = conn->driver->domainPinEmulator(domain, cpumap, maplen, flags);
10050 10051 10052 10053 10054
        if (ret < 0)
            goto error;
        return ret;
    }

10055
    virReportUnsupportedError();
10056 10057 10058 10059 10060 10061

error:
    virDispatchError(domain->conn);
    return -1;
}

10062

10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099
/**
 * virDomainGetEmulatorPinInfo:
 * @domain: pointer to domain object, or NULL for Domain0
 * @cpumap: pointer to a bit map of real CPUs for all emulator threads of
 *     this domain (in 8-bit bytes) (OUT)
 *     There is only one cpumap for all emulator threads.
 *     Must not be NULL.
 * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map.
 *     Must be positive.
 * @flags: bitwise-OR of virDomainModificationImpact
 *     Must not be VIR_DOMAIN_AFFECT_LIVE and
 *     VIR_DOMAIN_AFFECT_CONFIG concurrently.
 *
 * Query the CPU affinity setting of all emulator threads of domain, store
 * it in cpumap.
 *
 * Returns 1 in case of success,
 * 0 in case of no emulator threads are pined to pcpus,
 * -1 in case of failure.
 */
int
virDomainGetEmulatorPinInfo(virDomainPtr domain, unsigned char *cpumap,
                            int maplen, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=%x",
                     cpumap, maplen, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

10100 10101
    virCheckNonNullArgGoto(cpumap, error);
    virCheckPositiveArgGoto(maplen, error);
10102 10103 10104 10105

    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
10106 10107 10108 10109
        virReportInvalidArg(flags,
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
                            __FUNCTION__);
10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122
        goto error;
    }
    conn = domain->conn;

    if (conn->driver->domainGetEmulatorPinInfo) {
        int ret;
        ret = conn->driver->domainGetEmulatorPinInfo(domain, cpumap,
                                                     maplen, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

10123
    virReportUnsupportedError();
10124 10125 10126 10127 10128 10129

error:
    virDispatchError(domain->conn);
    return -1;
}

10130

10131 10132 10133 10134 10135
/**
 * virDomainGetVcpus:
 * @domain: pointer to domain object, or NULL for Domain0
 * @info: pointer to an array of virVcpuInfo structures (OUT)
 * @maxinfo: number of structures in info array
D
Dan Kenigsberg 已提交
10136
 * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this
10137
 *      domain (in 8-bit bytes) (OUT)
O
Osier Yang 已提交
10138 10139 10140 10141 10142
 *      If cpumaps is NULL, then no cpumap information is returned by the API.
 *      It's assumed there is <maxinfo> cpumap in cpumaps array.
 *      The memory allocated to cpumaps must be (maxinfo * maplen) bytes
 *      (ie: calloc(maxinfo, maplen)).
 *      One cpumap inside cpumaps has the format described in
10143 10144
 *      virDomainPinVcpu() API.
 * @maplen: number of bytes in one cpumap, from 1 up to size of CPU map in
O
Osier Yang 已提交
10145 10146
 *      underlying virtualization system (Xen...).
 *      Must be zero when cpumaps is NULL and positive when it is non-NULL.
10147
 *
10148
 * Extract information about virtual CPUs of domain, store it in info array
10149 10150 10151
 * and also in cpumaps if this pointer isn't NULL.  This call may fail
 * on an inactive domain.
 *
E
Eric Blake 已提交
10152
 * See also virDomainGetVcpuPinInfo for querying just cpumaps, including on
10153
 * an inactive domain.
10154 10155 10156 10157 10158
 *
 * Returns the number of info filled in case of success, -1 in case of failure.
 */
int
virDomainGetVcpus(virDomainPtr domain, virVcpuInfoPtr info, int maxinfo,
10159
                  unsigned char *cpumaps, int maplen)
10160
{
10161
    virConnectPtr conn;
10162 10163 10164

    VIR_DOMAIN_DEBUG(domain, "info=%p, maxinfo=%d, cpumaps=%p, maplen=%d",
                     info, maxinfo, cpumaps, maplen);
10165

10166 10167
    virResetLastError();

10168
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10169
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
10170
        virDispatchError(NULL);
10171
        return -1;
10172
    }
10173 10174
    virCheckNonNullArgGoto(info, error);
    virCheckPositiveArgGoto(maxinfo, error);
10175 10176 10177

    /* Ensure that domainGetVcpus (aka remoteDomainGetVcpus) does not
       try to memcpy anything into a NULL pointer.  */
10178 10179 10180 10181 10182
    if (cpumaps)
        virCheckPositiveArgGoto(maplen, error);
    else
        virCheckZeroArgGoto(maplen, error);

E
Eric Blake 已提交
10183 10184 10185 10186 10187
    if (cpumaps && INT_MULTIPLY_OVERFLOW(maxinfo, maplen)) {
        virLibDomainError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"),
                          maxinfo, maplen);
        goto error;
    }
10188

10189 10190
    conn = domain->conn;

10191 10192
    if (conn->driver->domainGetVcpus) {
        int ret;
10193 10194
        ret = conn->driver->domainGetVcpus(domain, info, maxinfo,
                                           cpumaps, maplen);
10195 10196 10197 10198
        if (ret < 0)
            goto error;
        return ret;
    }
10199

10200
    virReportUnsupportedError();
10201 10202

error:
10203
    virDispatchError(domain->conn);
10204
    return -1;
10205
}
10206

10207

10208 10209 10210
/**
 * virDomainGetMaxVcpus:
 * @domain: pointer to domain object
10211
 *
10212 10213
 * Provides the maximum number of virtual CPUs supported for
 * the guest VM. If the guest is inactive, this is basically
E
Eric Blake 已提交
10214
 * the same as virConnectGetMaxVcpus(). If the guest is running
10215
 * this will reflect the maximum number of virtual CPUs the
E
Eric Blake 已提交
10216
 * guest was booted with.  For more details, see virDomainGetVcpusFlags().
10217 10218 10219 10220
 *
 * Returns the maximum of virtual CPU or -1 in case of error.
 */
int
10221 10222
virDomainGetMaxVcpus(virDomainPtr domain)
{
10223
    virConnectPtr conn;
10224

10225
    VIR_DOMAIN_DEBUG(domain);
10226

10227 10228
    virResetLastError();

10229
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10230
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
10231
        virDispatchError(NULL);
10232
        return -1;
10233 10234 10235 10236
    }

    conn = domain->conn;

10237 10238
    if (conn->driver->domainGetMaxVcpus) {
        int ret;
10239
        ret = conn->driver->domainGetMaxVcpus(domain);
10240 10241 10242 10243
        if (ret < 0)
            goto error;
        return ret;
    }
10244

10245
    virReportUnsupportedError();
10246 10247

error:
10248
    virDispatchError(domain->conn);
10249
    return -1;
10250 10251
}

10252

10253 10254 10255 10256 10257
/**
 * virDomainGetSecurityLabel:
 * @domain: a domain object
 * @seclabel: pointer to a virSecurityLabel structure
 *
10258 10259 10260
 * Extract security label of an active domain. The 'label' field
 * in the @seclabel argument will be initialized to the empty
 * string if the domain is not running under a security model.
10261
 *
10262
 * Returns 0 in case of success, -1 in case of failure
10263 10264 10265 10266 10267 10268
 */
int
virDomainGetSecurityLabel(virDomainPtr domain, virSecurityLabelPtr seclabel)
{
    virConnectPtr conn;

10269 10270
    VIR_DOMAIN_DEBUG(domain, "seclabel=%p", seclabel);

10271 10272
    virResetLastError();

10273
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10274
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
10275
        virDispatchError(NULL);
10276 10277 10278
        return -1;
    }

10279
    virCheckNonNullArgGoto(seclabel, error);
10280 10281 10282

    conn = domain->conn;

10283 10284 10285 10286 10287 10288 10289 10290
    if (conn->driver->domainGetSecurityLabel) {
        int ret;
        ret = conn->driver->domainGetSecurityLabel(domain, seclabel);
        if (ret < 0)
            goto error;
        return ret;
    }

10291
    virReportUnsupportedError();
10292

10293
error:
10294
    virDispatchError(domain->conn);
10295
    return -1;
10296 10297
}

10298

M
Marcelo Cerri 已提交
10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318
/**
 * virDomainGetSecurityLabelList:
 * @domain: a domain object
 * @seclabels: will be auto-allocated and filled with domains' security labels.
 * Caller must free memory on return.
 *
 * Extract the security labels of an active domain. The 'label' field
 * in the @seclabels argument will be initialized to the empty
 * string if the domain is not running under a security model.
 *
 * Returns number of elemnets in @seclabels on success, -1 in case of failure.
 */
int
virDomainGetSecurityLabelList(virDomainPtr domain,
                              virSecurityLabelPtr* seclabels)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "seclabels=%p", seclabels);

10319 10320
    virResetLastError();

M
Marcelo Cerri 已提交
10321 10322 10323 10324 10325 10326
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

10327
    virCheckNonNullArgGoto(seclabels, error);
M
Marcelo Cerri 已提交
10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338

    conn = domain->conn;

    if (conn->driver->domainGetSecurityLabelList) {
        int ret;
        ret = conn->driver->domainGetSecurityLabelList(domain, seclabels);
        if (ret < 0)
            goto error;
        return ret;
    }

10339
    virReportUnsupportedError();
M
Marcelo Cerri 已提交
10340 10341 10342 10343 10344

error:
    virDispatchError(domain->conn);
    return -1;
}
10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389
/**
 * virDomainSetMetadata:
 * @domain: a domain object
 * @type: type of description, from virDomainMetadataType
 * @metadata: new metadata text
 * @key: XML namespace key, or NULL
 * @uri: XML namespace URI, or NULL
 * @flags: bitwise-OR of virDomainModificationImpact
 *
 * Sets the appropriate domain element given by @type to the
 * value of @description.  A @type of VIR_DOMAIN_METADATA_DESCRIPTION
 * is free-form text; VIR_DOMAIN_METADATA_TITLE is free-form, but no
 * newlines are permitted, and should be short (although the length is
 * not enforced). For these two options @key and @uri are irrelevant and
 * must be set to NULL.
 *
 * For type VIR_DOMAIN_METADATA_ELEMENT @metadata  must be well-formed
 * XML belonging to namespace defined by @uri with local name @key.
 *
 * Passing NULL for @metadata says to remove that element from the
 * domain XML (passing the empty string leaves the element present).
 *
 * The resulting metadata will be present in virDomainGetXMLDesc(),
 * as well as quick access through virDomainGetMetadata().
 *
 * @flags controls whether the live domain, persistent configuration,
 * or both will be modified.
 *
 * Returns 0 on success, -1 in case of failure.
 */
int
virDomainSetMetadata(virDomainPtr domain,
                     int type,
                     const char *metadata,
                     const char *key,
                     const char *uri,
                     unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain,
                     "type=%d, metadata='%s', key='%s', uri='%s', flags=%x",
                     type, NULLSTR(metadata), NULLSTR(key), NULLSTR(uri),
                     flags);

10390 10391
    virResetLastError();

10392 10393 10394 10395 10396 10397 10398
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        goto error;
    }

    conn = domain->conn;

10399
    virCheckReadOnlyGoto(conn->flags, error);
10400 10401 10402 10403

    switch (type) {
    case VIR_DOMAIN_METADATA_TITLE:
        if (metadata && strchr(metadata, '\n')) {
10404
            virReportInvalidArg(metadata,
10405 10406
                                _("metadata title in %s can't contain "
                                  "newlines"),
10407 10408
                                __FUNCTION__);
            goto error;
10409 10410 10411
        }
        /* fallthrough */
    case VIR_DOMAIN_METADATA_DESCRIPTION:
10412 10413
        virCheckNullArgGoto(uri, error);
        virCheckNullArgGoto(key, error);
10414 10415
        break;
    case VIR_DOMAIN_METADATA_ELEMENT:
10416
        virCheckNonNullArgGoto(uri, error);
10417 10418
        if (metadata)
            virCheckNonNullArgGoto(key, error);
10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433
        break;
    default:
        /* For future expansion */
        break;
    }

    if (conn->driver->domainSetMetadata) {
        int ret;
        ret = conn->driver->domainSetMetadata(domain, type, metadata, key, uri,
                                              flags);
        if (ret < 0)
            goto error;
        return ret;
    }

10434
    virReportUnsupportedError();
10435 10436 10437 10438 10439 10440

error:
    virDispatchError(domain->conn);
    return -1;
}

10441

10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475
/**
 * virDomainGetMetadata:
 * @domain: a domain object
 * @type: type of description, from virDomainMetadataType
 * @uri: XML namespace identifier
 * @flags: bitwise-OR of virDomainModificationImpact
 *
 * Retrieves the appropriate domain element given by @type.
 * If VIR_DOMAIN_METADATA_ELEMENT is requested parameter @uri
 * must be set to the name of the namespace the requested elements
 * belong to, otherwise must be NULL.
 *
 * If an element of the domain XML is not present, the resulting
 * error will be VIR_ERR_NO_DOMAIN_METADATA.  This method forms
 * a shortcut for seeing information from virDomainSetMetadata()
 * without having to go through virDomainGetXMLDesc().
 *
 * @flags controls whether the live domain or persistent
 * configuration will be queried.
 *
 * Returns the metadata string on success (caller must free),
 * or NULL in case of failure.
 */
char *
virDomainGetMetadata(virDomainPtr domain,
                     int type,
                     const char *uri,
                     unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "type=%d, uri='%s', flags=%x",
                     type, NULLSTR(uri), flags);

10476 10477
    virResetLastError();

10478 10479 10480 10481 10482 10483 10484
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        goto error;
    }

    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
10485
        virReportInvalidArg(flags,
10486 10487
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
10488
                            __FUNCTION__);
10489 10490 10491 10492 10493 10494
        goto error;
    }

    switch (type) {
    case VIR_DOMAIN_METADATA_TITLE:
    case VIR_DOMAIN_METADATA_DESCRIPTION:
10495
        virCheckNullArgGoto(uri, error);
10496 10497
        break;
    case VIR_DOMAIN_METADATA_ELEMENT:
10498
        virCheckNonNullArgGoto(uri, error);
10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513
        break;
    default:
        /* For future expansion */
        break;
    }

    conn = domain->conn;

    if (conn->driver->domainGetMetadata) {
        char *ret;
        if (!(ret = conn->driver->domainGetMetadata(domain, type, uri, flags)))
            goto error;
        return ret;
    }

10514
    virReportUnsupportedError();
10515 10516 10517 10518 10519 10520

error:
    virDispatchError(domain->conn);
    return NULL;
}

10521

10522 10523 10524 10525 10526
/**
 * virNodeGetSecurityModel:
 * @conn: a connection object
 * @secmodel: pointer to a virSecurityModel structure
 *
10527 10528 10529
 * Extract the security model of a hypervisor. The 'model' field
 * in the @secmodel argument may be initialized to the empty
 * string if the driver has not activated a security model.
10530
 *
10531
 * Returns 0 in case of success, -1 in case of failure
10532 10533 10534 10535
 */
int
virNodeGetSecurityModel(virConnectPtr conn, virSecurityModelPtr secmodel)
{
10536
    VIR_DEBUG("conn=%p secmodel=%p", conn, secmodel);
10537

10538 10539
    virResetLastError();

10540
    virCheckConnectReturn(conn, -1);
10541
    virCheckNonNullArgGoto(secmodel, error);
10542 10543 10544 10545 10546 10547 10548

    if (conn->driver->nodeGetSecurityModel) {
        int ret;
        ret = conn->driver->nodeGetSecurityModel(conn, secmodel);
        if (ret < 0)
            goto error;
        return ret;
10549 10550
    }

10551
    virReportUnsupportedError();
10552

10553
error:
10554
    virDispatchError(conn);
10555
    return -1;
10556
}
10557

10558

10559 10560 10561 10562
/**
 * virDomainAttachDevice:
 * @domain: pointer to domain object
 * @xml: pointer to XML description of one device
10563
 *
10564 10565
 * Create a virtual device attachment to backend.  This function,
 * having hotplug semantics, is only allowed on an active domain.
10566
 *
10567 10568 10569 10570
 * For compatibility, this method can also be used to change the media
 * in an existing CDROM/Floppy device, however, applications are
 * recommended to use the virDomainUpdateDeviceFlag method instead.
 *
10571 10572 10573
 * Returns 0 in case of success, -1 in case of failure.
 */
int
10574
virDomainAttachDevice(virDomainPtr domain, const char *xml)
10575 10576
{
    virConnectPtr conn;
10577 10578

    VIR_DOMAIN_DEBUG(domain, "xml=%s", xml);
10579

10580 10581
    virResetLastError();

10582
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10583
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
10584
        virDispatchError(NULL);
10585
        return -1;
10586
    }
10587

10588
    virCheckNonNullArgGoto(xml, error);
10589

10590
    virCheckReadOnlyGoto(domain->conn->flags, error);
10591 10592
    conn = domain->conn;

10593
    if (conn->driver->domainAttachDevice) {
J
Jim Fehlig 已提交
10594
       int ret;
10595
       ret = conn->driver->domainAttachDevice(domain, xml);
J
Jim Fehlig 已提交
10596 10597 10598 10599 10600
       if (ret < 0)
          goto error;
       return ret;
    }

10601
    virReportUnsupportedError();
J
Jim Fehlig 已提交
10602 10603 10604 10605 10606 10607

error:
    virDispatchError(domain->conn);
    return -1;
}

10608

J
Jim Fehlig 已提交
10609 10610 10611 10612
/**
 * virDomainAttachDeviceFlags:
 * @domain: pointer to domain object
 * @xml: pointer to XML description of one device
10613
 * @flags: bitwise-OR of virDomainDeviceModifyFlags
J
Jim Fehlig 已提交
10614 10615
 *
 * Attach a virtual device to a domain, using the flags parameter
10616
 * to control how the device is attached.  VIR_DOMAIN_AFFECT_CURRENT
J
Jim Fehlig 已提交
10617
 * specifies that the device allocation is made based on current domain
10618
 * state.  VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be
J
Jim Fehlig 已提交
10619
 * allocated to the active domain instance only and is not added to the
10620
 * persisted domain configuration.  VIR_DOMAIN_AFFECT_CONFIG
J
Jim Fehlig 已提交
10621 10622 10623 10624 10625 10626
 * specifies that the device shall be allocated to the persisted domain
 * configuration only.  Note that the target hypervisor must return an
 * error if unable to satisfy flags.  E.g. the hypervisor driver will
 * return failure if LIVE is specified but it only supports modifying the
 * persisted device allocation.
 *
10627 10628 10629 10630
 * For compatibility, this method can also be used to change the media
 * in an existing CDROM/Floppy device, however, applications are
 * recommended to use the virDomainUpdateDeviceFlag method instead.
 *
J
Jim Fehlig 已提交
10631 10632 10633 10634 10635 10636 10637
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainAttachDeviceFlags(virDomainPtr domain,
                           const char *xml, unsigned int flags)
{
    virConnectPtr conn;
10638

10639
    VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags);
J
Jim Fehlig 已提交
10640 10641 10642 10643

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10644
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
W
Wen Congyang 已提交
10645
        virDispatchError(NULL);
10646
        return -1;
J
Jim Fehlig 已提交
10647
    }
10648

10649
    virCheckNonNullArgGoto(xml, error);
10650

10651
    virCheckReadOnlyGoto(domain->conn->flags, error);
J
Jim Fehlig 已提交
10652 10653 10654
    conn = domain->conn;

    if (conn->driver->domainAttachDeviceFlags) {
10655
        int ret;
J
Jim Fehlig 已提交
10656
        ret = conn->driver->domainAttachDeviceFlags(domain, xml, flags);
10657 10658 10659 10660
        if (ret < 0)
            goto error;
        return ret;
    }
10661

10662
    virReportUnsupportedError();
10663 10664

error:
10665
    virDispatchError(domain->conn);
10666
    return -1;
10667 10668
}

10669

10670 10671 10672 10673
/**
 * virDomainDetachDevice:
 * @domain: pointer to domain object
 * @xml: pointer to XML description of one device
10674
 *
10675 10676
 * Destroy a virtual device attachment to backend.  This function,
 * having hot-unplug semantics, is only allowed on an active domain.
10677 10678 10679 10680
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
10681
virDomainDetachDevice(virDomainPtr domain, const char *xml)
10682 10683
{
    virConnectPtr conn;
10684 10685

    VIR_DOMAIN_DEBUG(domain, "xml=%s", xml);
10686

10687 10688
    virResetLastError();

10689
    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10690
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
10691
        virDispatchError(NULL);
10692
        return -1;
10693
    }
10694

10695
    virCheckNonNullArgGoto(xml, error);
10696

10697
    virCheckReadOnlyGoto(domain->conn->flags, error);
10698 10699
    conn = domain->conn;

10700 10701
    if (conn->driver->domainDetachDevice) {
        int ret;
10702
        ret = conn->driver->domainDetachDevice(domain, xml);
J
Jim Fehlig 已提交
10703 10704 10705 10706 10707
         if (ret < 0)
             goto error;
         return ret;
     }

10708
    virReportUnsupportedError();
J
Jim Fehlig 已提交
10709 10710 10711 10712 10713 10714

error:
    virDispatchError(domain->conn);
    return -1;
}

10715

J
Jim Fehlig 已提交
10716 10717 10718 10719
/**
 * virDomainDetachDeviceFlags:
 * @domain: pointer to domain object
 * @xml: pointer to XML description of one device
10720
 * @flags: bitwise-OR of virDomainDeviceModifyFlags
J
Jim Fehlig 已提交
10721 10722
 *
 * Detach a virtual device from a domain, using the flags parameter
10723
 * to control how the device is detached.  VIR_DOMAIN_AFFECT_CURRENT
J
Jim Fehlig 已提交
10724
 * specifies that the device allocation is removed based on current domain
10725
 * state.  VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be
J
Jim Fehlig 已提交
10726
 * deallocated from the active domain instance only and is not from the
10727
 * persisted domain configuration.  VIR_DOMAIN_AFFECT_CONFIG
J
Jim Fehlig 已提交
10728 10729 10730 10731 10732 10733
 * specifies that the device shall be deallocated from the persisted domain
 * configuration only.  Note that the target hypervisor must return an
 * error if unable to satisfy flags.  E.g. the hypervisor driver will
 * return failure if LIVE is specified but it only supports removing the
 * persisted device allocation.
 *
E
Eric Blake 已提交
10734 10735 10736 10737
 * Some hypervisors may prevent this operation if there is a current
 * block copy operation on the device being detached; in that case,
 * use virDomainBlockJobAbort() to stop the block copy first.
 *
10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753
 * Beware that depending on the hypervisor and device type, detaching a device
 * from a running domain may be asynchronous. That is, calling
 * virDomainDetachDeviceFlags may just request device removal while the device
 * is actually removed later (in cooperation with a guest OS). Previously,
 * this fact was ignored and the device could have been removed from domain
 * configuration before it was actually removed by the hypervisor causing
 * various failures on subsequent operations. To check whether the device was
 * successfully removed, either recheck domain configuration using
 * virDomainGetXMLDesc() or add handler for VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED
 * event. In case the device is already gone when virDomainDetachDeviceFlags
 * returns, the event is delivered before this API call ends. To help existing
 * clients work better in most cases, this API will try to transform an
 * asynchronous device removal that finishes shortly after the request into
 * a synchronous removal. In other words, this API may wait a bit for the
 * removal to complete in case it was not synchronous.
 *
J
Jim Fehlig 已提交
10754 10755 10756 10757 10758 10759 10760
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainDetachDeviceFlags(virDomainPtr domain,
                           const char *xml, unsigned int flags)
{
    virConnectPtr conn;
10761

10762
    VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags);
J
Jim Fehlig 已提交
10763 10764 10765 10766

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10767
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
W
Wen Congyang 已提交
10768
        virDispatchError(NULL);
10769
        return -1;
J
Jim Fehlig 已提交
10770
    }
10771

10772
    virCheckNonNullArgGoto(xml, error);
10773

10774
    virCheckReadOnlyGoto(domain->conn->flags, error);
J
Jim Fehlig 已提交
10775 10776 10777 10778 10779
    conn = domain->conn;

    if (conn->driver->domainDetachDeviceFlags) {
        int ret;
        ret = conn->driver->domainDetachDeviceFlags(domain, xml, flags);
10780 10781 10782 10783 10784
        if (ret < 0)
            goto error;
        return ret;
    }

10785
    virReportUnsupportedError();
10786 10787 10788 10789 10790 10791

error:
    virDispatchError(domain->conn);
    return -1;
}

10792

10793 10794 10795 10796
/**
 * virDomainUpdateDeviceFlags:
 * @domain: pointer to domain object
 * @xml: pointer to XML description of one device
10797
 * @flags: bitwise-OR of virDomainDeviceModifyFlags
10798 10799
 *
 * Change a virtual device on a domain, using the flags parameter
10800
 * to control how the device is changed.  VIR_DOMAIN_AFFECT_CURRENT
10801
 * specifies that the device change is made based on current domain
10802
 * state.  VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be
10803
 * changed on the active domain instance only and is not added to the
10804
 * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG
10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821
 * specifies that the device shall be changed on the persisted domain
 * configuration only.  Note that the target hypervisor must return an
 * error if unable to satisfy flags.  E.g. the hypervisor driver will
 * return failure if LIVE is specified but it only supports modifying the
 * persisted device allocation.
 *
 * This method is used for actions such changing CDROM/Floppy device
 * media, altering the graphics configuration such as password,
 * reconfiguring the NIC device backend connectivity, etc.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virDomainUpdateDeviceFlags(virDomainPtr domain,
                           const char *xml, unsigned int flags)
{
    virConnectPtr conn;
10822

10823
    VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags);
10824 10825 10826 10827

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
10828
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
W
Wen Congyang 已提交
10829
        virDispatchError(NULL);
10830
        return -1;
10831
    }
10832

10833
    virCheckNonNullArgGoto(xml, error);
10834

10835
    virCheckReadOnlyGoto(domain->conn->flags, error);
10836 10837 10838 10839 10840
    conn = domain->conn;

    if (conn->driver->domainUpdateDeviceFlags) {
        int ret;
        ret = conn->driver->domainUpdateDeviceFlags(domain, xml, flags);
10841 10842 10843 10844
        if (ret < 0)
            goto error;
        return ret;
    }
10845

10846
    virReportUnsupportedError();
10847 10848

error:
10849
    virDispatchError(domain->conn);
10850
    return -1;
10851
}
10852

10853

10854 10855 10856 10857 10858 10859 10860 10861 10862 10863
/**
 * virNodeGetCellsFreeMemory:
 * @conn: pointer to the hypervisor connection
 * @freeMems: pointer to the array of unsigned long long
 * @startCell: index of first cell to return freeMems info on.
 * @maxCells: Maximum number of cells for which freeMems information can
 *            be returned.
 *
 * This call returns the amount of free memory in one or more NUMA cells.
 * The @freeMems array must be allocated by the caller and will be filled
10864
 * with the amount of free memory in bytes for each cell requested,
10865 10866 10867 10868 10869 10870 10871 10872 10873 10874
 * starting with startCell (in freeMems[0]), up to either
 * (startCell + maxCells), or the number of additional cells in the node,
 * whichever is smaller.
 *
 * Returns the number of entries filled in freeMems, or -1 in case of error.
 */
int
virNodeGetCellsFreeMemory(virConnectPtr conn, unsigned long long *freeMems,
                          int startCell, int maxCells)
{
10875
    VIR_DEBUG("conn=%p, freeMems=%p, startCell=%d, maxCells=%d",
10876 10877
          conn, freeMems, startCell, maxCells);

10878 10879
    virResetLastError();

10880
    virCheckConnectReturn(conn, -1);
10881 10882 10883
    virCheckNonNullArgGoto(freeMems, error);
    virCheckPositiveArgGoto(maxCells, error);
    virCheckNonNegativeArgGoto(startCell, error);
10884

10885 10886
    if (conn->driver->nodeGetCellsFreeMemory) {
        int ret;
10887
        ret = conn->driver->nodeGetCellsFreeMemory(conn, freeMems, startCell, maxCells);
10888 10889 10890 10891
        if (ret < 0)
            goto error;
        return ret;
    }
10892

10893
    virReportUnsupportedError();
10894 10895

error:
10896
    virDispatchError(conn);
10897 10898 10899
    return -1;
}

10900

10901 10902 10903 10904
/**
 * virNetworkGetConnect:
 * @net: pointer to a network
 *
10905
 * Provides the connection pointer associated with a network.  The
10906 10907 10908
 * reference counter on the connection is not increased by this
 * call.
 *
10909 10910 10911 10912
 * WARNING: When writing libvirt bindings in other languages, do
 * not use this function.  Instead, store the connection and
 * the network object together.
 *
10913 10914 10915
 * Returns the virConnectPtr or NULL in case of failure.
 */
virConnectPtr
10916
virNetworkGetConnect(virNetworkPtr net)
10917
{
10918
    VIR_DEBUG("net=%p", net);
10919

10920 10921
    virResetLastError();

10922
    if (!VIR_IS_CONNECTED_NETWORK(net)) {
10923
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
10924
        virDispatchError(NULL);
10925 10926 10927 10928 10929
        return NULL;
    }
    return net->conn;
}

10930

10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977
/**
 * virConnectListAllNetworks:
 * @conn: Pointer to the hypervisor connection.
 * @nets: Pointer to a variable to store the array containing the network
 *        objects or NULL if the list is not required (just returns number
 *        of networks).
 * @flags: bitwise-OR of virConnectListAllNetworksFlags.
 *
 * Collect the list of networks, and allocate an array to store those
 * objects. This API solves the race inherent between virConnectListNetworks
 * and virConnectListDefinedNetworks.
 *
 * Normally, all networks are returned; however, @flags can be used to
 * filter the results for a smaller list of targeted networks.  The valid
 * flags are divided into groups, where each group contains bits that
 * describe mutually exclusive attributes of a network, and where all bits
 * within a group describe all possible networks.
 *
 * The first group of @flags is VIR_CONNECT_LIST_NETWORKS_ACTIVE (up) and
 * VIR_CONNECT_LIST_NETWORKS_INACTIVE (down) to filter the networks by state.
 *
 * The second group of @flags is VIR_CONNECT_LIST_NETWORKS_PERSISTENT (defined)
 * and VIR_CONNECT_LIST_NETWORKS_TRANSIENT (running but not defined), to filter
 * the networks by whether they have persistent config or not.
 *
 * The third group of @flags is VIR_CONNECT_LIST_NETWORKS_AUTOSTART
 * and VIR_CONNECT_LIST_NETWORKS_NO_AUTOSTART, to filter the networks by
 * whether they are marked as autostart or not.
 *
 * Returns the number of networks found or -1 and sets @nets to  NULL in case
 * of error.  On success, the array stored into @nets is guaranteed to have an
 * extra allocated element set to NULL but not included in the return count,
 * to make iteration easier.  The caller is responsible for calling
 * virNetworkFree() on each array element, then calling free() on @nets.
 */
int
virConnectListAllNetworks(virConnectPtr conn,
                          virNetworkPtr **nets,
                          unsigned int flags)
{
    VIR_DEBUG("conn=%p, nets=%p, flags=%x", conn, nets, flags);

    virResetLastError();

    if (nets)
        *nets = NULL;

10978
    virCheckConnectReturn(conn, -1);
10979 10980

    if (conn->networkDriver &&
10981
        conn->networkDriver->connectListAllNetworks) {
10982
        int ret;
10983
        ret = conn->networkDriver->connectListAllNetworks(conn, nets, flags);
10984 10985 10986 10987 10988
        if (ret < 0)
            goto error;
        return ret;
    }

10989
    virReportUnsupportedError();
10990 10991 10992 10993 10994 10995 10996

error:
    virDispatchError(conn);
    return -1;
}


10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007
/**
 * virConnectNumOfNetworks:
 * @conn: pointer to the hypervisor connection
 *
 * Provides the number of active networks.
 *
 * Returns the number of network found or -1 in case of error
 */
int
virConnectNumOfNetworks(virConnectPtr conn)
{
11008
    VIR_DEBUG("conn=%p", conn);
11009

11010 11011
    virResetLastError();

11012
    virCheckConnectReturn(conn, -1);
11013

11014
    if (conn->networkDriver && conn->networkDriver->connectNumOfNetworks) {
11015
        int ret;
11016
        ret = conn->networkDriver->connectNumOfNetworks(conn);
11017 11018 11019 11020
        if (ret < 0)
            goto error;
        return ret;
    }
11021

11022
    virReportUnsupportedError();
11023 11024

error:
11025
    virDispatchError(conn);
11026
    return -1;
11027 11028
}

11029

11030 11031 11032 11033 11034 11035 11036 11037
/**
 * virConnectListNetworks:
 * @conn: pointer to the hypervisor connection
 * @names: array to collect the list of names of active networks
 * @maxnames: size of @names
 *
 * Collect the list of active networks, and store their names in @names
 *
11038 11039 11040 11041 11042 11043
 * For more control over the results, see virConnectListAllNetworks().
 *
 * Returns the number of networks found or -1 in case of error.  Note that
 * this command is inherently racy; a network can be started between a call
 * to virConnectNumOfNetworks() and this call; you are only guaranteed that
 * all currently active networks were listed if the return is less than
J
John Ferlan 已提交
11044
 * @maxnames. The client must call free() on each returned name.
11045 11046
 */
int
11047
virConnectListNetworks(virConnectPtr conn, char **const names, int maxnames)
11048
{
11049
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
11050

11051 11052
    virResetLastError();

11053
    virCheckConnectReturn(conn, -1);
11054 11055
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
11056

11057
    if (conn->networkDriver && conn->networkDriver->connectListNetworks) {
11058
        int ret;
11059
        ret = conn->networkDriver->connectListNetworks(conn, names, maxnames);
11060 11061 11062 11063
        if (ret < 0)
            goto error;
        return ret;
    }
11064

11065
    virReportUnsupportedError();
11066 11067

error:
11068
    virDispatchError(conn);
11069
    return -1;
11070 11071
}

11072

11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083
/**
 * virConnectNumOfDefinedNetworks:
 * @conn: pointer to the hypervisor connection
 *
 * Provides the number of inactive networks.
 *
 * Returns the number of networks found or -1 in case of error
 */
int
virConnectNumOfDefinedNetworks(virConnectPtr conn)
{
11084
    VIR_DEBUG("conn=%p", conn);
11085

11086 11087
    virResetLastError();

11088
    virCheckConnectReturn(conn, -1);
11089

11090
    if (conn->networkDriver && conn->networkDriver->connectNumOfDefinedNetworks) {
11091
        int ret;
11092
        ret = conn->networkDriver->connectNumOfDefinedNetworks(conn);
11093 11094 11095 11096
        if (ret < 0)
            goto error;
        return ret;
    }
11097

11098
    virReportUnsupportedError();
11099 11100

error:
11101
    virDispatchError(conn);
11102
    return -1;
11103 11104
}

11105

11106 11107 11108 11109 11110 11111 11112 11113
/**
 * virConnectListDefinedNetworks:
 * @conn: pointer to the hypervisor connection
 * @names: pointer to an array to store the names
 * @maxnames: size of the array
 *
 * list the inactive networks, stores the pointers to the names in @names
 *
11114 11115 11116 11117 11118 11119 11120
 * For more control over the results, see virConnectListAllNetworks().
 *
 * Returns the number of names provided in the array or -1 in case of error.
 * Note that this command is inherently racy; a network can be defined between
 * a call to virConnectNumOfDefinedNetworks() and this call; you are only
 * guaranteed that all currently defined networks were listed if the return
 * is less than @maxnames.  The client must call free() on each returned name.
11121 11122
 */
int
11123
virConnectListDefinedNetworks(virConnectPtr conn, char **const names,
11124 11125
                              int maxnames)
{
11126
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
11127

11128 11129
    virResetLastError();

11130
    virCheckConnectReturn(conn, -1);
11131 11132
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
11133

11134
    if (conn->networkDriver && conn->networkDriver->connectListDefinedNetworks) {
11135
        int ret;
11136
        ret = conn->networkDriver->connectListDefinedNetworks(conn, names, maxnames);
11137 11138 11139 11140
        if (ret < 0)
            goto error;
        return ret;
    }
11141

11142
    virReportUnsupportedError();
11143 11144

error:
11145
    virDispatchError(conn);
11146
    return -1;
11147 11148
}

11149

11150 11151 11152 11153 11154 11155 11156
/**
 * virNetworkLookupByName:
 * @conn: pointer to the hypervisor connection
 * @name: name for the network
 *
 * Try to lookup a network on the given hypervisor based on its name.
 *
11157 11158
 * Returns a new network object or NULL in case of failure.  If the
 * network cannot be found, then VIR_ERR_NO_NETWORK error is raised.
11159 11160 11161 11162
 */
virNetworkPtr
virNetworkLookupByName(virConnectPtr conn, const char *name)
{
11163
    VIR_DEBUG("conn=%p, name=%s", conn, name);
11164

11165 11166
    virResetLastError();

11167
    virCheckConnectReturn(conn, NULL);
11168
    virCheckNonNullArgGoto(name, error);
11169

11170 11171
    if (conn->networkDriver && conn->networkDriver->networkLookupByName) {
        virNetworkPtr ret;
11172
        ret = conn->networkDriver->networkLookupByName(conn, name);
11173 11174 11175 11176
        if (!ret)
            goto error;
        return ret;
    }
11177

11178
    virReportUnsupportedError();
11179 11180

error:
11181
    virDispatchError(conn);
11182
    return NULL;
11183 11184
}

11185

11186 11187 11188 11189 11190 11191 11192
/**
 * virNetworkLookupByUUID:
 * @conn: pointer to the hypervisor connection
 * @uuid: the raw UUID for the network
 *
 * Try to lookup a network on the given hypervisor based on its UUID.
 *
11193 11194
 * Returns a new network object or NULL in case of failure.  If the
 * network cannot be found, then VIR_ERR_NO_NETWORK error is raised.
11195 11196 11197 11198
 */
virNetworkPtr
virNetworkLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
11199
    VIR_UUID_DEBUG(conn, uuid);
11200

11201 11202
    virResetLastError();

11203
    virCheckConnectReturn(conn, NULL);
11204
    virCheckNonNullArgGoto(uuid, error);
11205

11206 11207
    if (conn->networkDriver && conn->networkDriver->networkLookupByUUID){
        virNetworkPtr ret;
11208
        ret = conn->networkDriver->networkLookupByUUID(conn, uuid);
11209 11210 11211 11212
        if (!ret)
            goto error;
        return ret;
    }
11213

11214
    virReportUnsupportedError();
11215 11216

error:
11217
    virDispatchError(conn);
11218
    return NULL;
11219 11220
}

11221

11222 11223 11224 11225 11226 11227 11228
/**
 * virNetworkLookupByUUIDString:
 * @conn: pointer to the hypervisor connection
 * @uuidstr: the string UUID for the network
 *
 * Try to lookup a network on the given hypervisor based on its UUID.
 *
11229 11230
 * Returns a new network object or NULL in case of failure.  If the
 * network cannot be found, then VIR_ERR_NO_NETWORK error is raised.
11231 11232 11233 11234 11235
 */
virNetworkPtr
virNetworkLookupByUUIDString(virConnectPtr conn, const char *uuidstr)
{
    unsigned char uuid[VIR_UUID_BUFLEN];
11236
    VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr));
11237

11238 11239
    virResetLastError();

11240
    virCheckConnectReturn(conn, NULL);
11241
    virCheckNonNullArgGoto(uuidstr, error);
11242

11243
    if (virUUIDParse(uuidstr, uuid) < 0) {
11244 11245 11246
        virReportInvalidArg(uuidstr,
                            _("uuidstr in %s must be a valid UUID"),
                            __FUNCTION__);
11247
        goto error;
11248 11249 11250
    }

    return virNetworkLookupByUUID(conn, &uuid[0]);
11251 11252

error:
11253
    virDispatchError(conn);
11254
    return NULL;
11255 11256
}

11257

11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270
/**
 * virNetworkCreateXML:
 * @conn: pointer to the hypervisor connection
 * @xmlDesc: an XML description of the network
 *
 * Create and start a new virtual network, based on an XML description
 * similar to the one returned by virNetworkGetXMLDesc()
 *
 * Returns a new network object or NULL in case of failure
 */
virNetworkPtr
virNetworkCreateXML(virConnectPtr conn, const char *xmlDesc)
{
11271
    VIR_DEBUG("conn=%p, xmlDesc=%s", conn, xmlDesc);
11272

11273 11274
    virResetLastError();

11275
    virCheckConnectReturn(conn, NULL);
11276
    virCheckNonNullArgGoto(xmlDesc, error);
11277
    virCheckReadOnlyGoto(conn->flags, error);
11278

11279 11280
    if (conn->networkDriver && conn->networkDriver->networkCreateXML) {
        virNetworkPtr ret;
11281
        ret = conn->networkDriver->networkCreateXML(conn, xmlDesc);
11282 11283 11284 11285
        if (!ret)
            goto error;
        return ret;
    }
11286

11287
    virReportUnsupportedError();
11288 11289

error:
11290
    virDispatchError(conn);
11291
    return NULL;
11292 11293
}

11294

11295 11296 11297 11298 11299 11300 11301 11302 11303 11304
/**
 * virNetworkDefineXML:
 * @conn: pointer to the hypervisor connection
 * @xml: the XML description for the network, preferably in UTF-8
 *
 * Define a network, but does not create it
 *
 * Returns NULL in case of error, a pointer to the network otherwise
 */
virNetworkPtr
11305 11306
virNetworkDefineXML(virConnectPtr conn, const char *xml)
{
11307
    VIR_DEBUG("conn=%p, xml=%s", conn, xml);
11308

11309 11310
    virResetLastError();

11311
    virCheckConnectReturn(conn, NULL);
11312
    virCheckReadOnlyGoto(conn->flags, error);
11313
    virCheckNonNullArgGoto(xml, error);
11314

11315 11316
    if (conn->networkDriver && conn->networkDriver->networkDefineXML) {
        virNetworkPtr ret;
11317
        ret = conn->networkDriver->networkDefineXML(conn, xml);
11318 11319 11320 11321
        if (!ret)
            goto error;
        return ret;
    }
11322

11323
    virReportUnsupportedError();
11324 11325

error:
11326
    virDispatchError(conn);
11327
    return NULL;
11328 11329
}

11330

11331 11332 11333 11334 11335 11336 11337 11338 11339
/**
 * virNetworkUndefine:
 * @network: pointer to a defined network
 *
 * Undefine a network but does not stop it if it is running
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
11340 11341
virNetworkUndefine(virNetworkPtr network)
{
11342
    virConnectPtr conn;
11343
    VIR_DEBUG("network=%p", network);
11344

11345 11346
    virResetLastError();

11347
    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11348
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11349
        virDispatchError(NULL);
11350
        return -1;
11351 11352
    }
    conn = network->conn;
11353
    virCheckReadOnlyGoto(conn->flags, error);
11354

11355 11356
    if (conn->networkDriver && conn->networkDriver->networkUndefine) {
        int ret;
11357
        ret = conn->networkDriver->networkUndefine(network);
11358 11359 11360 11361
        if (ret < 0)
            goto error;
        return ret;
    }
11362

11363
    virReportUnsupportedError();
11364 11365 11366 11367 11368 11369

error:
    virDispatchError(network->conn);
    return -1;
}

11370

11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409
/**
 * virNetworkUpdate:
 * @network: pointer to a defined network
 * @section: which section of the network to update
 *           (see virNetworkUpdateSection for descriptions)
 * @command: what action to perform (add/delete/modify)
 *           (see virNetworkUpdateCommand for descriptions)
 * @parentIndex: which parent element, if there are multiple parents
 *           of the same type (e.g. which <ip> element when modifying
 *           a <dhcp>/<host> element), or "-1" for "don't care" or
 *           "automatically find appropriate one".
 * @xml: the XML description for the network, preferably in UTF-8
 * @flags: bitwise OR of virNetworkUpdateFlags.
 *
 * Update the definition of an existing network, either its live
 * running state, its persistent configuration, or both.
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
virNetworkUpdate(virNetworkPtr network,
                 unsigned int command, /* virNetworkUpdateCommand */
                 unsigned int section, /* virNetworkUpdateSection */
                 int parentIndex,
                 const char *xml,
                 unsigned int flags)
{
    virConnectPtr conn;
    VIR_DEBUG("network=%p, section=%d, parentIndex=%d, xml=%s, flags=0x%x",
              network, section, parentIndex, xml, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(network)) {
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = network->conn;
11410
    virCheckReadOnlyGoto(conn->flags, error);
11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422

    virCheckNonNullArgGoto(xml, error);

    if (conn->networkDriver && conn->networkDriver->networkUpdate) {
        int ret;
        ret = conn->networkDriver->networkUpdate(network, section, command,
                                                 parentIndex, xml, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

11423
    virReportUnsupportedError();
11424 11425

error:
11426
    virDispatchError(network->conn);
11427
    return -1;
11428 11429
}

11430

11431 11432 11433 11434 11435 11436 11437 11438 11439 11440
/**
 * virNetworkCreate:
 * @network: pointer to a defined network
 *
 * Create and start a defined network. If the call succeed the network
 * moves from the defined to the running networks pools.
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
11441 11442
virNetworkCreate(virNetworkPtr network)
{
11443
    virConnectPtr conn;
11444
    VIR_DEBUG("network=%p", network);
11445

11446 11447
    virResetLastError();

11448
    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11449
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11450
        virDispatchError(NULL);
11451
        return -1;
11452 11453
    }
    conn = network->conn;
11454
    virCheckReadOnlyGoto(conn->flags, error);
11455

11456 11457
    if (conn->networkDriver && conn->networkDriver->networkCreate) {
        int ret;
11458
        ret = conn->networkDriver->networkCreate(network);
11459 11460 11461 11462
        if (ret < 0)
            goto error;
        return ret;
    }
11463

11464
    virReportUnsupportedError();
11465 11466

error:
11467
    virDispatchError(network->conn);
11468
    return -1;
11469 11470
}

11471

11472 11473 11474 11475 11476
/**
 * virNetworkDestroy:
 * @network: a network object
 *
 * Destroy the network object. The running instance is shutdown if not down
11477 11478 11479
 * already and all resources used by it are given back to the hypervisor. This
 * does not free the associated virNetworkPtr object.
 * This function may require privileged access
11480 11481 11482 11483 11484 11485 11486
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virNetworkDestroy(virNetworkPtr network)
{
    virConnectPtr conn;
11487
    VIR_DEBUG("network=%p", network);
11488

11489 11490
    virResetLastError();

11491
    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11492
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11493
        virDispatchError(NULL);
11494
        return -1;
11495 11496 11497
    }

    conn = network->conn;
11498
    virCheckReadOnlyGoto(conn->flags, error);
11499

11500 11501
    if (conn->networkDriver && conn->networkDriver->networkDestroy) {
        int ret;
11502
        ret = conn->networkDriver->networkDestroy(network);
11503 11504 11505 11506
        if (ret < 0)
            goto error;
        return ret;
    }
11507

11508
    virReportUnsupportedError();
11509 11510

error:
11511
    virDispatchError(network->conn);
11512
    return -1;
11513 11514
}

11515

11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527
/**
 * virNetworkFree:
 * @network: a network object
 *
 * Free the network object. The running instance is kept alive.
 * The data structure is freed and should not be used thereafter.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virNetworkFree(virNetworkPtr network)
{
11528
    VIR_DEBUG("network=%p", network);
11529

11530 11531 11532
    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11533
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11534
        virDispatchError(NULL);
11535
        return -1;
11536
    }
11537
    virObjectUnref(network);
11538
    return 0;
11539 11540
}

11541

11542 11543
/**
 * virNetworkRef:
D
Daniel Veillard 已提交
11544
 * @network: the network to hold a reference on
11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555
 *
 * Increment the reference count on the network. For each
 * additional call to this method, there shall be a corresponding
 * call to virNetworkFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
 * it. ie, each new thread using a network would increment
 * the reference count.
D
Daniel Veillard 已提交
11556 11557
 *
 * Returns 0 in case of success, -1 in case of failure.
11558 11559 11560 11561
 */
int
virNetworkRef(virNetworkPtr network)
{
11562 11563 11564
    VIR_DEBUG("network=%p refs=%d", network,
              network ? network->object.u.s.refs : 0);

11565 11566
    virResetLastError();

11567
    if ((!VIR_IS_CONNECTED_NETWORK(network))) {
11568
        virLibConnError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11569
        virDispatchError(NULL);
11570
        return -1;
11571
    }
11572
    virObjectRef(network);
11573 11574 11575
    return 0;
}

11576

11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588
/**
 * virNetworkGetName:
 * @network: a network object
 *
 * Get the public name for that network
 *
 * Returns a pointer to the name or NULL, the string need not be deallocated
 * its lifetime will be the same as the network object.
 */
const char *
virNetworkGetName(virNetworkPtr network)
{
11589
    VIR_DEBUG("network=%p", network);
11590

11591 11592
    virResetLastError();

11593
    if (!VIR_IS_NETWORK(network)) {
11594
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11595
        virDispatchError(NULL);
11596
        return NULL;
11597
    }
11598
    return network->name;
11599 11600
}

11601

11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613
/**
 * virNetworkGetUUID:
 * @network: a network object
 * @uuid: pointer to a VIR_UUID_BUFLEN bytes array
 *
 * Get the UUID for a network
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virNetworkGetUUID(virNetworkPtr network, unsigned char *uuid)
{
11614
    VIR_DEBUG("network=%p, uuid=%p", network, uuid);
11615

11616 11617
    virResetLastError();

11618
    if (!VIR_IS_NETWORK(network)) {
11619
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11620
        virDispatchError(NULL);
11621
        return -1;
11622
    }
11623
    virCheckNonNullArgGoto(uuid, error);
11624 11625 11626

    memcpy(uuid, &network->uuid[0], VIR_UUID_BUFLEN);

11627
    return 0;
11628 11629

error:
11630
    virDispatchError(network->conn);
11631
    return -1;
11632 11633
}

11634

11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647
/**
 * virNetworkGetUUIDString:
 * @network: a network object
 * @buf: pointer to a VIR_UUID_STRING_BUFLEN bytes array
 *
 * Get the UUID for a network as string. For more information about
 * UUID see RFC4122.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virNetworkGetUUIDString(virNetworkPtr network, char *buf)
{
11648
    VIR_DEBUG("network=%p, buf=%p", network, buf);
11649

11650 11651
    virResetLastError();

11652
    if (!VIR_IS_NETWORK(network)) {
11653
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11654
        virDispatchError(NULL);
11655
        return -1;
11656
    }
11657
    virCheckNonNullArgGoto(buf, error);
11658

E
Eric Blake 已提交
11659
    virUUIDFormat(network->uuid, buf);
11660
    return 0;
11661 11662

error:
11663
    virDispatchError(network->conn);
11664
    return -1;
11665 11666
}

11667

11668 11669 11670
/**
 * virNetworkGetXMLDesc:
 * @network: a network object
11671
 * @flags: bitwise-OR of virNetworkXMLFlags
11672 11673 11674 11675
 *
 * Provide an XML description of the network. The description may be reused
 * later to relaunch the network with virNetworkCreateXML().
 *
11676 11677 11678 11679 11680
 * Normally, if a network included a physical function, the output includes
 * all virtual functions tied to that physical interface.  If @flags includes
 * VIR_NETWORK_XML_INACTIVE, then the expansion of virtual interfaces is
 * not performed.
 *
11681 11682 11683 11684
 * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
11685
virNetworkGetXMLDesc(virNetworkPtr network, unsigned int flags)
11686
{
11687
    virConnectPtr conn;
11688
    VIR_DEBUG("network=%p, flags=%x", network, flags);
11689

11690 11691 11692
    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11693
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11694
        virDispatchError(NULL);
11695
        return NULL;
11696 11697
    }

11698 11699
    conn = network->conn;

11700
    if (conn->networkDriver && conn->networkDriver->networkGetXMLDesc) {
11701
        char *ret;
11702
        ret = conn->networkDriver->networkGetXMLDesc(network, flags);
11703 11704 11705 11706
        if (!ret)
            goto error;
        return ret;
    }
11707

11708
    virReportUnsupportedError();
11709 11710

error:
11711
    virDispatchError(network->conn);
11712
    return NULL;
11713
}
11714

11715

11716 11717 11718 11719
/**
 * virNetworkGetBridgeName:
 * @network: a network object
 *
11720
 * Provides a bridge interface name to which a domain may connect
11721 11722 11723 11724 11725 11726 11727 11728
 * a network interface in order to join the network.
 *
 * Returns a 0 terminated interface name, or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
virNetworkGetBridgeName(virNetworkPtr network)
{
11729
    virConnectPtr conn;
11730
    VIR_DEBUG("network=%p", network);
11731

11732 11733 11734
    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11735
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11736
        virDispatchError(NULL);
11737
        return NULL;
11738 11739
    }

11740 11741
    conn = network->conn;

11742 11743
    if (conn->networkDriver && conn->networkDriver->networkGetBridgeName) {
        char *ret;
11744
        ret = conn->networkDriver->networkGetBridgeName(network);
11745 11746 11747 11748
        if (!ret)
            goto error;
        return ret;
    }
11749

11750
    virReportUnsupportedError();
11751 11752

error:
11753
    virDispatchError(network->conn);
11754
    return NULL;
11755
}
11756

11757

11758 11759 11760
/**
 * virNetworkGetAutostart:
 * @network: a network object
11761
 * @autostart: the value returned
11762
 *
11763
 * Provides a boolean value indicating whether the network
11764 11765 11766 11767 11768 11769 11770
 * configured to be automatically started when the host
 * machine boots.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virNetworkGetAutostart(virNetworkPtr network,
11771 11772 11773
                       int *autostart)
{
    virConnectPtr conn;
11774
    VIR_DEBUG("network=%p, autostart=%p", network, autostart);
11775

11776 11777 11778
    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11779
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11780
        virDispatchError(NULL);
11781
        return -1;
11782
    }
11783
    virCheckNonNullArgGoto(autostart, error);
11784

11785 11786
    conn = network->conn;

11787 11788
    if (conn->networkDriver && conn->networkDriver->networkGetAutostart) {
        int ret;
11789
        ret = conn->networkDriver->networkGetAutostart(network, autostart);
11790 11791 11792 11793
        if (ret < 0)
            goto error;
        return ret;
    }
11794

11795
    virReportUnsupportedError();
11796 11797

error:
11798
    virDispatchError(network->conn);
11799
    return -1;
11800 11801
}

11802

11803 11804 11805
/**
 * virNetworkSetAutostart:
 * @network: a network object
11806
 * @autostart: whether the network should be automatically started 0 or 1
11807 11808 11809 11810 11811 11812 11813 11814
 *
 * Configure the network to be automatically started
 * when the host machine boots.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virNetworkSetAutostart(virNetworkPtr network,
11815 11816 11817
                       int autostart)
{
    virConnectPtr conn;
11818
    VIR_DEBUG("network=%p, autostart=%d", network, autostart);
11819

11820 11821 11822
    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(network)) {
11823
        virLibNetworkError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
11824
        virDispatchError(NULL);
11825
        return -1;
11826 11827
    }

11828
    virCheckReadOnlyGoto(network->conn->flags, error);
11829

11830 11831
    conn = network->conn;

11832 11833
    if (conn->networkDriver && conn->networkDriver->networkSetAutostart) {
        int ret;
11834
        ret = conn->networkDriver->networkSetAutostart(network, autostart);
11835 11836 11837 11838
        if (ret < 0)
            goto error;
        return ret;
    }
11839

11840
    virReportUnsupportedError();
11841 11842

error:
11843
    virDispatchError(network->conn);
11844
    return -1;
11845
}
11846

11847

D
Daniel Veillard 已提交
11848 11849
/**
 * virInterfaceGetConnect:
L
Laine Stump 已提交
11850
 * @iface: pointer to an interface
D
Daniel Veillard 已提交
11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862
 *
 * Provides the connection pointer associated with an interface.  The
 * reference counter on the connection is not increased by this
 * call.
 *
 * WARNING: When writing libvirt bindings in other languages, do
 * not use this function.  Instead, store the connection and
 * the interface object together.
 *
 * Returns the virConnectPtr or NULL in case of failure.
 */
virConnectPtr
11863
virInterfaceGetConnect(virInterfacePtr iface)
D
Daniel Veillard 已提交
11864
{
11865
    VIR_DEBUG("iface=%p", iface);
D
Daniel Veillard 已提交
11866 11867 11868

    virResetLastError();

11869
    if (!VIR_IS_CONNECTED_INTERFACE(iface)) {
11870
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
11871
        virDispatchError(NULL);
D
Daniel Veillard 已提交
11872 11873
        return NULL;
    }
11874
    return iface->conn;
D
Daniel Veillard 已提交
11875 11876
}

11877

11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916
/**
 * virConnectListAllInterfaces:
 * @conn: Pointer to the hypervisor connection.
 * @ifaces: Pointer to a variable to store the array containing the interface
 *          objects or NULL if the list is not required (just returns number
 *          of interfaces).
 * @flags: bitwise-OR of virConnectListAllInterfacesFlags.
 *
 * Collect the list of interfaces, and allocate an array to store those
 * objects. This API solves the race inherent between virConnectListInterfaces
 * and virConnectListDefinedInterfaces.
 *
 * Normally, all interfaces are returned; however, @flags can be used to
 * filter the results for a smaller list of targeted interfaces.  The valid
 * flags are divided into groups, where each group contains bits that
 * describe mutually exclusive attributes of a interface, and where all bits
 * within a group describe all possible interfaces.
 *
 * The only group of @flags is VIR_CONNECT_LIST_INTERFACES_ACTIVE (up) and
 * VIR_CONNECT_LIST_INTERFACES_INACTIVE (down) to filter the interfaces by state.
 *
 * Returns the number of interfaces found or -1 and sets @ifaces to  NULL in case
 * of error.  On success, the array stored into @ifaces is guaranteed to have an
 * extra allocated element set to NULL but not included in the return count,
 * to make iteration easier.  The caller is responsible for calling
 * virStorageInterfaceFree() on each array element, then calling free() on @ifaces.
 */
int
virConnectListAllInterfaces(virConnectPtr conn,
                            virInterfacePtr **ifaces,
                            unsigned int flags)
{
    VIR_DEBUG("conn=%p, ifaces=%p, flags=%x", conn, ifaces, flags);

    virResetLastError();

    if (ifaces)
        *ifaces = NULL;

11917
    virCheckConnectReturn(conn, -1);
11918 11919

    if (conn->interfaceDriver &&
11920
        conn->interfaceDriver->connectListAllInterfaces) {
11921
        int ret;
11922
        ret = conn->interfaceDriver->connectListAllInterfaces(conn, ifaces, flags);
11923 11924 11925 11926 11927
        if (ret < 0)
            goto error;
        return ret;
    }

11928
    virReportUnsupportedError();
11929 11930 11931 11932 11933 11934

error:
    virDispatchError(conn);
    return -1;
}

11935

D
Daniel Veillard 已提交
11936 11937 11938 11939
/**
 * virConnectNumOfInterfaces:
 * @conn: pointer to the hypervisor connection
 *
11940
 * Provides the number of active interfaces on the physical host.
D
Daniel Veillard 已提交
11941
 *
11942
 * Returns the number of active interfaces found or -1 in case of error
D
Daniel Veillard 已提交
11943 11944 11945 11946
 */
int
virConnectNumOfInterfaces(virConnectPtr conn)
{
11947
    VIR_DEBUG("conn=%p", conn);
D
Daniel Veillard 已提交
11948 11949 11950

    virResetLastError();

11951
    virCheckConnectReturn(conn, -1);
D
Daniel Veillard 已提交
11952

11953
    if (conn->interfaceDriver && conn->interfaceDriver->connectNumOfInterfaces) {
D
Daniel Veillard 已提交
11954
        int ret;
11955
        ret = conn->interfaceDriver->connectNumOfInterfaces(conn);
D
Daniel Veillard 已提交
11956 11957 11958 11959 11960
        if (ret < 0)
            goto error;
        return ret;
    }

11961
    virReportUnsupportedError();
D
Daniel Veillard 已提交
11962 11963

error:
11964
    virDispatchError(conn);
D
Daniel Veillard 已提交
11965 11966 11967
    return -1;
}

11968

D
Daniel Veillard 已提交
11969 11970 11971 11972 11973 11974
/**
 * virConnectListInterfaces:
 * @conn: pointer to the hypervisor connection
 * @names: array to collect the list of names of interfaces
 * @maxnames: size of @names
 *
11975 11976
 * Collect the list of active physical host interfaces,
 * and store their names in @names
D
Daniel Veillard 已提交
11977
 *
11978 11979 11980 11981 11982 11983
 * For more control over the results, see virConnectListAllInterfaces().
 *
 * Returns the number of interfaces found or -1 in case of error.  Note that
 * this command is inherently racy; a interface can be started between a call
 * to virConnectNumOfInterfaces() and this call; you are only guaranteed that
 * all currently active interfaces were listed if the return is less than
J
John Ferlan 已提交
11984
 * @maxnames. The client must call free() on each returned name.
D
Daniel Veillard 已提交
11985 11986 11987 11988
 */
int
virConnectListInterfaces(virConnectPtr conn, char **const names, int maxnames)
{
11989
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
D
Daniel Veillard 已提交
11990 11991 11992

    virResetLastError();

11993
    virCheckConnectReturn(conn, -1);
11994 11995
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
D
Daniel Veillard 已提交
11996

11997
    if (conn->interfaceDriver && conn->interfaceDriver->connectListInterfaces) {
D
Daniel Veillard 已提交
11998
        int ret;
11999
        ret = conn->interfaceDriver->connectListInterfaces(conn, names, maxnames);
D
Daniel Veillard 已提交
12000 12001 12002 12003 12004
        if (ret < 0)
            goto error;
        return ret;
    }

12005
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12006 12007

error:
12008
    virDispatchError(conn);
D
Daniel Veillard 已提交
12009 12010 12011
    return -1;
}

12012

12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023
/**
 * virConnectNumOfDefinedInterfaces:
 * @conn: pointer to the hypervisor connection
 *
 * Provides the number of defined (inactive) interfaces on the physical host.
 *
 * Returns the number of defined interface found or -1 in case of error
 */
int
virConnectNumOfDefinedInterfaces(virConnectPtr conn)
{
12024
    VIR_DEBUG("conn=%p", conn);
12025 12026 12027

    virResetLastError();

12028
    virCheckConnectReturn(conn, -1);
12029

12030
    if (conn->interfaceDriver && conn->interfaceDriver->connectNumOfDefinedInterfaces) {
12031
        int ret;
12032
        ret = conn->interfaceDriver->connectNumOfDefinedInterfaces(conn);
12033 12034 12035 12036 12037
        if (ret < 0)
            goto error;
        return ret;
    }

12038
    virReportUnsupportedError();
12039 12040

error:
12041
    virDispatchError(conn);
12042 12043 12044
    return -1;
}

12045

12046 12047 12048 12049 12050 12051 12052 12053 12054
/**
 * virConnectListDefinedInterfaces:
 * @conn: pointer to the hypervisor connection
 * @names: array to collect the list of names of interfaces
 * @maxnames: size of @names
 *
 * Collect the list of defined (inactive) physical host interfaces,
 * and store their names in @names.
 *
12055 12056 12057 12058 12059 12060 12061
 * For more control over the results, see virConnectListAllInterfaces().
 *
 * Returns the number of names provided in the array or -1 in case of error.
 * Note that this command is inherently racy; a interface can be defined between
 * a call to virConnectNumOfDefinedInterfaces() and this call; you are only
 * guaranteed that all currently defined interfaces were listed if the return
 * is less than @maxnames.  The client must call free() on each returned name.
12062 12063 12064 12065 12066 12067
 */
int
virConnectListDefinedInterfaces(virConnectPtr conn,
                                char **const names,
                                int maxnames)
{
12068
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
12069 12070 12071

    virResetLastError();

12072
    virCheckConnectReturn(conn, -1);
12073 12074
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
12075

12076
    if (conn->interfaceDriver && conn->interfaceDriver->connectListDefinedInterfaces) {
12077
        int ret;
12078
        ret = conn->interfaceDriver->connectListDefinedInterfaces(conn, names, maxnames);
12079 12080 12081 12082 12083
        if (ret < 0)
            goto error;
        return ret;
    }

12084
    virReportUnsupportedError();
12085 12086

error:
12087
    virDispatchError(conn);
12088 12089 12090
    return -1;
}

12091

D
Daniel Veillard 已提交
12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104
/**
 * virInterfaceLookupByName:
 * @conn: pointer to the hypervisor connection
 * @name: name for the interface
 *
 * Try to lookup an interface on the given hypervisor based on its name.
 *
 * Returns a new interface object or NULL in case of failure.  If the
 * interface cannot be found, then VIR_ERR_NO_INTERFACE error is raised.
 */
virInterfacePtr
virInterfaceLookupByName(virConnectPtr conn, const char *name)
{
12105
    VIR_DEBUG("conn=%p, name=%s", conn, name);
D
Daniel Veillard 已提交
12106 12107 12108

    virResetLastError();

12109
    virCheckConnectReturn(conn, NULL);
12110
    virCheckNonNullArgGoto(name, error);
D
Daniel Veillard 已提交
12111 12112 12113

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceLookupByName) {
        virInterfacePtr ret;
12114
        ret = conn->interfaceDriver->interfaceLookupByName(conn, name);
D
Daniel Veillard 已提交
12115 12116 12117 12118 12119
        if (!ret)
            goto error;
        return ret;
    }

12120
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12121 12122

error:
12123
    virDispatchError(conn);
D
Daniel Veillard 已提交
12124 12125 12126
    return NULL;
}

12127

D
Daniel Veillard 已提交
12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140
/**
 * virInterfaceLookupByMACString:
 * @conn: pointer to the hypervisor connection
 * @macstr: the MAC for the interface (null-terminated ASCII format)
 *
 * Try to lookup an interface on the given hypervisor based on its MAC.
 *
 * Returns a new interface object or NULL in case of failure.  If the
 * interface cannot be found, then VIR_ERR_NO_INTERFACE error is raised.
 */
virInterfacePtr
virInterfaceLookupByMACString(virConnectPtr conn, const char *macstr)
{
12141
    VIR_DEBUG("conn=%p, macstr=%s", conn, macstr);
D
Daniel Veillard 已提交
12142 12143 12144

    virResetLastError();

12145
    virCheckConnectReturn(conn, NULL);
12146
    virCheckNonNullArgGoto(macstr, error);
D
Daniel Veillard 已提交
12147 12148 12149

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceLookupByMACString) {
        virInterfacePtr ret;
12150
        ret = conn->interfaceDriver->interfaceLookupByMACString(conn, macstr);
D
Daniel Veillard 已提交
12151 12152 12153 12154 12155
        if (!ret)
            goto error;
        return ret;
    }

12156
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12157 12158

error:
12159
    virDispatchError(conn);
D
Daniel Veillard 已提交
12160 12161 12162
    return NULL;
}

12163

D
Daniel Veillard 已提交
12164 12165
/**
 * virInterfaceGetName:
L
Laine Stump 已提交
12166
 * @iface: an interface object
D
Daniel Veillard 已提交
12167 12168 12169 12170 12171 12172 12173
 *
 * Get the public name for that interface
 *
 * Returns a pointer to the name or NULL, the string need not be deallocated
 * its lifetime will be the same as the interface object.
 */
const char *
12174
virInterfaceGetName(virInterfacePtr iface)
D
Daniel Veillard 已提交
12175
{
12176
    VIR_DEBUG("iface=%p", iface);
D
Daniel Veillard 已提交
12177 12178 12179

    virResetLastError();

12180
    if (!VIR_IS_INTERFACE(iface)) {
12181
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12182
        virDispatchError(NULL);
12183
        return NULL;
D
Daniel Veillard 已提交
12184
    }
12185
    return iface->name;
D
Daniel Veillard 已提交
12186 12187
}

12188

D
Daniel Veillard 已提交
12189 12190
/**
 * virInterfaceGetMACString:
L
Laine Stump 已提交
12191
 * @iface: an interface object
D
Daniel Veillard 已提交
12192
 *
L
Laine Stump 已提交
12193
 * Get the MAC for an interface as string. For more information about
D
Daniel Veillard 已提交
12194 12195 12196 12197 12198 12199 12200
 * MAC see RFC4122.
 *
 * Returns a pointer to the MAC address (in null-terminated ASCII
 * format) or NULL, the string need not be deallocated its lifetime
 * will be the same as the interface object.
 */
const char *
12201
virInterfaceGetMACString(virInterfacePtr iface)
D
Daniel Veillard 已提交
12202
{
12203
    VIR_DEBUG("iface=%p", iface);
D
Daniel Veillard 已提交
12204 12205 12206

    virResetLastError();

12207
    if (!VIR_IS_INTERFACE(iface)) {
12208
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12209
        virDispatchError(NULL);
12210
        return NULL;
D
Daniel Veillard 已提交
12211
    }
12212
    return iface->mac;
D
Daniel Veillard 已提交
12213 12214
}

12215

D
Daniel Veillard 已提交
12216 12217
/**
 * virInterfaceGetXMLDesc:
L
Laine Stump 已提交
12218
 * @iface: an interface object
12219
 * @flags: bitwise-OR of extraction flags. Current valid bits:
12220 12221 12222 12223
 *
 *      VIR_INTERFACE_XML_INACTIVE - return the static configuration,
 *                                   suitable for use redefining the
 *                                   interface via virInterfaceDefineXML()
D
Daniel Veillard 已提交
12224
 *
12225 12226 12227 12228 12229
 * Provide an XML description of the interface. If
 * VIR_INTERFACE_XML_INACTIVE is set, the description may be reused
 * later to redefine the interface with virInterfaceDefineXML(). If it
 * is not set, the ip address and netmask will be the current live
 * setting of the interface, not the settings from the config files.
D
Daniel Veillard 已提交
12230 12231 12232 12233 12234
 *
 * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
12235
virInterfaceGetXMLDesc(virInterfacePtr iface, unsigned int flags)
D
Daniel Veillard 已提交
12236 12237
{
    virConnectPtr conn;
12238
    VIR_DEBUG("iface=%p, flags=%x", iface, flags);
D
Daniel Veillard 已提交
12239 12240 12241

    virResetLastError();

12242
    if (!VIR_IS_CONNECTED_INTERFACE(iface)) {
12243
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12244
        virDispatchError(NULL);
12245
        return NULL;
D
Daniel Veillard 已提交
12246 12247
    }

12248
    conn = iface->conn;
D
Daniel Veillard 已提交
12249 12250 12251

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceGetXMLDesc) {
        char *ret;
12252
        ret = conn->interfaceDriver->interfaceGetXMLDesc(iface, flags);
D
Daniel Veillard 已提交
12253 12254 12255 12256 12257
        if (!ret)
            goto error;
        return ret;
    }

12258
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12259 12260

error:
12261
    virDispatchError(iface->conn);
D
Daniel Veillard 已提交
12262 12263 12264
    return NULL;
}

12265

D
Daniel Veillard 已提交
12266 12267 12268 12269
/**
 * virInterfaceDefineXML:
 * @conn: pointer to the hypervisor connection
 * @xml: the XML description for the interface, preferably in UTF-8
12270
 * @flags: extra flags; not used yet, so callers should always pass 0
D
Daniel Veillard 已提交
12271
 *
12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282
 * Define an interface (or modify existing interface configuration).
 *
 * Normally this change in the interface configuration is immediately
 * permanent/persistent, but if virInterfaceChangeBegin() has been
 * previously called (i.e. if an interface config transaction is
 * open), the new interface definition will only become permanent if
 * virInterfaceChangeCommit() is called prior to the next reboot of
 * the system running libvirtd. Prior to that time, it can be
 * explicitly removed using virInterfaceChangeRollback(), or will be
 * automatically removed during the next reboot of the system running
 * libvirtd.
D
Daniel Veillard 已提交
12283 12284 12285 12286 12287 12288
 *
 * Returns NULL in case of error, a pointer to the interface otherwise
 */
virInterfacePtr
virInterfaceDefineXML(virConnectPtr conn, const char *xml, unsigned int flags)
{
12289
    VIR_DEBUG("conn=%p, xml=%s, flags=%x", conn, xml, flags);
D
Daniel Veillard 已提交
12290 12291 12292

    virResetLastError();

12293
    virCheckConnectReturn(conn, NULL);
12294
    virCheckReadOnlyGoto(conn->flags, error);
12295
    virCheckNonNullArgGoto(xml, error);
D
Daniel Veillard 已提交
12296 12297 12298

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceDefineXML) {
        virInterfacePtr ret;
12299
        ret = conn->interfaceDriver->interfaceDefineXML(conn, xml, flags);
D
Daniel Veillard 已提交
12300 12301 12302 12303 12304
        if (!ret)
            goto error;
        return ret;
    }

12305
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12306 12307

error:
12308
    virDispatchError(conn);
D
Daniel Veillard 已提交
12309 12310 12311
    return NULL;
}

12312

D
Daniel Veillard 已提交
12313 12314
/**
 * virInterfaceUndefine:
12315
 * @iface: pointer to a defined interface
D
Daniel Veillard 已提交
12316 12317 12318 12319
 *
 * Undefine an interface, ie remove it from the config.
 * This does not free the associated virInterfacePtr object.
 *
12320 12321 12322 12323 12324 12325 12326 12327 12328 12329
 * Normally this change in the interface configuration is
 * permanent/persistent, but if virInterfaceChangeBegin() has been
 * previously called (i.e. if an interface config transaction is
 * open), the removal of the interface definition will only become
 * permanent if virInterfaceChangeCommit() is called prior to the next
 * reboot of the system running libvirtd. Prior to that time, the
 * definition can be explicitly restored using
 * virInterfaceChangeRollback(), or will be automatically restored
 * during the next reboot of the system running libvirtd.
 *
D
Daniel Veillard 已提交
12330 12331 12332
 * Returns 0 in case of success, -1 in case of error
 */
int
12333 12334
virInterfaceUndefine(virInterfacePtr iface)
{
D
Daniel Veillard 已提交
12335
    virConnectPtr conn;
12336
    VIR_DEBUG("iface=%p", iface);
D
Daniel Veillard 已提交
12337 12338 12339

    virResetLastError();

12340
    if (!VIR_IS_CONNECTED_INTERFACE(iface)) {
12341
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12342
        virDispatchError(NULL);
12343
        return -1;
D
Daniel Veillard 已提交
12344
    }
12345
    conn = iface->conn;
12346
    virCheckReadOnlyGoto(conn->flags, error);
D
Daniel Veillard 已提交
12347 12348 12349

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceUndefine) {
        int ret;
12350
        ret = conn->interfaceDriver->interfaceUndefine(iface);
D
Daniel Veillard 已提交
12351 12352 12353 12354 12355
        if (ret < 0)
            goto error;
        return ret;
    }

12356
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12357 12358

error:
12359
    virDispatchError(iface->conn);
D
Daniel Veillard 已提交
12360 12361 12362
    return -1;
}

12363

D
Daniel Veillard 已提交
12364 12365
/**
 * virInterfaceCreate:
12366
 * @iface: pointer to a defined interface
12367
 * @flags: extra flags; not used yet, so callers should always pass 0
D
Daniel Veillard 已提交
12368
 *
12369
 * Activate an interface (i.e. call "ifup").
D
Daniel Veillard 已提交
12370
 *
12371 12372 12373 12374
 * If there was an open network config transaction at the time this
 * interface was defined (that is, if virInterfaceChangeBegin() had
 * been called), the interface will be brought back down (and then
 * undefined) if virInterfaceChangeRollback() is called.
W
Wangyufei (A) 已提交
12375
 *
D
Daniel Veillard 已提交
12376 12377 12378
 * Returns 0 in case of success, -1 in case of error
 */
int
12379
virInterfaceCreate(virInterfacePtr iface, unsigned int flags)
D
Daniel Veillard 已提交
12380 12381
{
    virConnectPtr conn;
12382
    VIR_DEBUG("iface=%p, flags=%x", iface, flags);
D
Daniel Veillard 已提交
12383 12384 12385

    virResetLastError();

12386
    if (!VIR_IS_CONNECTED_INTERFACE(iface)) {
12387
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12388
        virDispatchError(NULL);
12389
        return -1;
D
Daniel Veillard 已提交
12390
    }
12391
    conn = iface->conn;
12392
    virCheckReadOnlyGoto(conn->flags, error);
D
Daniel Veillard 已提交
12393 12394 12395

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceCreate) {
        int ret;
12396
        ret = conn->interfaceDriver->interfaceCreate(iface, flags);
D
Daniel Veillard 已提交
12397 12398 12399 12400 12401
        if (ret < 0)
            goto error;
        return ret;
    }

12402
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12403 12404

error:
12405
    virDispatchError(iface->conn);
D
Daniel Veillard 已提交
12406 12407 12408
    return -1;
}

12409

D
Daniel Veillard 已提交
12410 12411
/**
 * virInterfaceDestroy:
12412
 * @iface: an interface object
12413
 * @flags: extra flags; not used yet, so callers should always pass 0
D
Daniel Veillard 已提交
12414 12415 12416 12417 12418
 *
 * deactivate an interface (ie call "ifdown")
 * This does not remove the interface from the config, and
 * does not free the associated virInterfacePtr object.
 *
12419 12420 12421 12422 12423 12424 12425

 * If there is an open network config transaction at the time this
 * interface is destroyed (that is, if virInterfaceChangeBegin() had
 * been called), and if the interface is later undefined and then
 * virInterfaceChangeRollback() is called, the restoral of the
 * interface definition will also bring the interface back up.
 *
D
Daniel Veillard 已提交
12426 12427 12428
 * Returns 0 in case of success and -1 in case of failure.
 */
int
12429
virInterfaceDestroy(virInterfacePtr iface, unsigned int flags)
D
Daniel Veillard 已提交
12430 12431
{
    virConnectPtr conn;
12432
    VIR_DEBUG("iface=%p, flags=%x", iface, flags);
D
Daniel Veillard 已提交
12433 12434 12435

    virResetLastError();

12436
    if (!VIR_IS_CONNECTED_INTERFACE(iface)) {
12437
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12438
        virDispatchError(NULL);
12439
        return -1;
D
Daniel Veillard 已提交
12440 12441
    }

12442
    conn = iface->conn;
12443
    virCheckReadOnlyGoto(conn->flags, error);
D
Daniel Veillard 已提交
12444 12445 12446

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceDestroy) {
        int ret;
12447
        ret = conn->interfaceDriver->interfaceDestroy(iface, flags);
D
Daniel Veillard 已提交
12448 12449 12450 12451 12452
        if (ret < 0)
            goto error;
        return ret;
    }

12453
    virReportUnsupportedError();
D
Daniel Veillard 已提交
12454 12455

error:
12456
    virDispatchError(iface->conn);
D
Daniel Veillard 已提交
12457 12458 12459
    return -1;
}

12460

D
Daniel Veillard 已提交
12461 12462
/**
 * virInterfaceRef:
12463
 * @iface: the interface to hold a reference on
D
Daniel Veillard 已提交
12464 12465 12466 12467 12468 12469 12470 12471 12472
 *
 * Increment the reference count on the interface. For each
 * additional call to this method, there shall be a corresponding
 * call to virInterfaceFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
L
Laine Stump 已提交
12473
 * it. ie, each new thread using an interface would increment
D
Daniel Veillard 已提交
12474 12475 12476 12477 12478
 * the reference count.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
12479
virInterfaceRef(virInterfacePtr iface)
D
Daniel Veillard 已提交
12480
{
12481 12482
    VIR_DEBUG("iface=%p refs=%d", iface, iface ? iface->object.u.s.refs : 0);

12483 12484
    virResetLastError();

12485
    if ((!VIR_IS_CONNECTED_INTERFACE(iface))) {
12486
        virLibConnError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12487
        virDispatchError(NULL);
12488
        return -1;
D
Daniel Veillard 已提交
12489
    }
12490
    virObjectRef(iface);
D
Daniel Veillard 已提交
12491 12492 12493
    return 0;
}

12494

D
Daniel Veillard 已提交
12495 12496
/**
 * virInterfaceFree:
L
Laine Stump 已提交
12497
 * @iface: an interface object
D
Daniel Veillard 已提交
12498 12499 12500 12501 12502 12503 12504
 *
 * Free the interface object. The interface itself is unaltered.
 * The data structure is freed and should not be used thereafter.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
12505
virInterfaceFree(virInterfacePtr iface)
D
Daniel Veillard 已提交
12506
{
12507
    VIR_DEBUG("iface=%p", iface);
D
Daniel Veillard 已提交
12508 12509 12510

    virResetLastError();

12511
    if (!VIR_IS_CONNECTED_INTERFACE(iface)) {
12512
        virLibInterfaceError(VIR_ERR_INVALID_INTERFACE, __FUNCTION__);
12513
        virDispatchError(NULL);
12514
        return -1;
D
Daniel Veillard 已提交
12515
    }
12516
    virObjectUnref(iface);
12517
    return 0;
D
Daniel Veillard 已提交
12518 12519
}

12520

12521 12522 12523
/**
 * virInterfaceChangeBegin:
 * @conn: pointer to hypervisor connection
12524
 * @flags: extra flags; not used yet, so callers should always pass 0
12525
 *
Y
Yuri Chornoivan 已提交
12526
 * This function creates a restore point to which one can return
12527 12528
 * later by calling virInterfaceChangeRollback(). This function should
 * be called before any transaction with interface configuration.
Y
Yuri Chornoivan 已提交
12529
 * Once it is known that a new configuration works, it can be committed via
12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540
 * virInterfaceChangeCommit(), which frees the restore point.
 *
 * If virInterfaceChangeBegin() is called when a transaction is
 * already opened, this function will fail, and a
 * VIR_ERR_INVALID_OPERATION will be logged.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virInterfaceChangeBegin(virConnectPtr conn, unsigned int flags)
{
12541
    VIR_DEBUG("conn=%p, flags=%x", conn, flags);
12542 12543 12544

    virResetLastError();

12545
    virCheckConnectReturn(conn, -1);
12546
    virCheckReadOnlyGoto(conn->flags, error);
12547 12548 12549 12550 12551 12552 12553 12554 12555

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceChangeBegin) {
        int ret;
        ret = conn->interfaceDriver->interfaceChangeBegin(conn, flags);
        if (ret < 0)
           goto error;
        return ret;
    }

12556
    virReportUnsupportedError();
12557 12558 12559 12560 12561 12562

error:
    virDispatchError(conn);
    return -1;
}

12563

12564 12565 12566
/**
 * virInterfaceChangeCommit:
 * @conn: pointer to hypervisor connection
12567
 * @flags: extra flags; not used yet, so callers should always pass 0
12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580
 *
 * This commits the changes made to interfaces and frees the restore point
 * created by virInterfaceChangeBegin().
 *
 * If virInterfaceChangeCommit() is called when a transaction is not
 * opened, this function will fail, and a VIR_ERR_INVALID_OPERATION
 * will be logged.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virInterfaceChangeCommit(virConnectPtr conn, unsigned int flags)
{
12581
    VIR_DEBUG("conn=%p, flags=%x", conn, flags);
12582 12583 12584

    virResetLastError();

12585
    virCheckConnectReturn(conn, -1);
12586
    virCheckReadOnlyGoto(conn->flags, error);
12587 12588 12589 12590 12591 12592 12593 12594 12595

    if (conn->interfaceDriver && conn->interfaceDriver->interfaceChangeCommit) {
        int ret;
        ret = conn->interfaceDriver->interfaceChangeCommit(conn, flags);
        if (ret < 0)
           goto error;
        return ret;
    }

12596
    virReportUnsupportedError();
12597 12598 12599 12600 12601 12602

error:
    virDispatchError(conn);
    return -1;
}

12603

12604 12605 12606
/**
 * virInterfaceChangeRollback:
 * @conn: pointer to hypervisor connection
12607
 * @flags: extra flags; not used yet, so callers should always pass 0
12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620
 *
 * This cancels changes made to interfaces settings by restoring previous
 * state created by virInterfaceChangeBegin().
 *
 * If virInterfaceChangeRollback() is called when a transaction is not
 * opened, this function will fail, and a VIR_ERR_INVALID_OPERATION
 * will be logged.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virInterfaceChangeRollback(virConnectPtr conn, unsigned int flags)
{
12621
    VIR_DEBUG("conn=%p, flags=%x", conn, flags);
12622 12623 12624

    virResetLastError();

12625
    virCheckConnectReturn(conn, -1);
12626
    virCheckReadOnlyGoto(conn->flags, error);
12627 12628 12629 12630 12631 12632 12633 12634 12635 12636

    if (conn->interfaceDriver &&
        conn->interfaceDriver->interfaceChangeRollback) {
        int ret;
        ret = conn->interfaceDriver->interfaceChangeRollback(conn, flags);
        if (ret < 0)
           goto error;
        return ret;
    }

12637
    virReportUnsupportedError();
12638 12639 12640 12641 12642 12643

error:
    virDispatchError(conn);
    return -1;
}

12644 12645 12646

/**
 * virStoragePoolGetConnect:
12647
 * @pool: pointer to a pool
12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659
 *
 * Provides the connection pointer associated with a storage pool.  The
 * reference counter on the connection is not increased by this
 * call.
 *
 * WARNING: When writing libvirt bindings in other languages, do
 * not use this function.  Instead, store the connection and
 * the pool object together.
 *
 * Returns the virConnectPtr or NULL in case of failure.
 */
virConnectPtr
12660
virStoragePoolGetConnect(virStoragePoolPtr pool)
12661
{
12662
    VIR_DEBUG("pool=%p", pool);
12663

12664 12665
    virResetLastError();

12666
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
12667
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
12668
        virDispatchError(NULL);
12669 12670 12671 12672 12673
        return NULL;
    }
    return pool->conn;
}

12674

12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736
/**
 * virConnectListAllStoragePools:
 * @conn: Pointer to the hypervisor connection.
 * @pools: Pointer to a variable to store the array containing storage pool
 *         objects or NULL if the list is not required (just returns number
 *         of pools).
 * @flags: bitwise-OR of virConnectListAllStoragePoolsFlags.
 *
 * Collect the list of storage pools, and allocate an array to store those
 * objects. This API solves the race inherent between
 * virConnectListStoragePools and virConnectListDefinedStoragePools.
 *
 * Normally, all storage pools are returned; however, @flags can be used to
 * filter the results for a smaller list of targeted pools.  The valid
 * flags are divided into groups, where each group contains bits that
 * describe mutually exclusive attributes of a pool, and where all bits
 * within a group describe all possible pools.
 *
 * The first group of @flags is VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE (online)
 * and VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE (offline) to filter the pools
 * by state.
 *
 * The second group of @flags is VIR_CONNECT_LIST_STORAGE_POOLS_PERSITENT
 * (defined) and VIR_CONNECT_LIST_STORAGE_POOLS_TRANSIENT (running but not
 * defined), to filter the pools by whether they have persistent config or not.
 *
 * The third group of @flags is VIR_CONNECT_LIST_STORAGE_POOLS_AUTOSTART
 * and VIR_CONNECT_LIST_STORAGE_POOLS_NO_AUTOSTART, to filter the pools by
 * whether they are marked as autostart or not.
 *
 * The last group of @flags is provided to filter the pools by the types,
 * the flags include:
 * VIR_CONNECT_LIST_STORAGE_POOLS_DIR
 * VIR_CONNECT_LIST_STORAGE_POOLS_FS
 * VIR_CONNECT_LIST_STORAGE_POOLS_NETFS
 * VIR_CONNECT_LIST_STORAGE_POOLS_LOGICAL
 * VIR_CONNECT_LIST_STORAGE_POOLS_DISK
 * VIR_CONNECT_LIST_STORAGE_POOLS_ISCSI
 * VIR_CONNECT_LIST_STORAGE_POOLS_SCSI
 * VIR_CONNECT_LIST_STORAGE_POOLS_MPATH
 * VIR_CONNECT_LIST_STORAGE_POOLS_RBD
 * VIR_CONNECT_LIST_STORAGE_POOLS_SHEEPDOG
 *
 * Returns the number of storage pools found or -1 and sets @pools to
 * NULL in case of error.  On success, the array stored into @pools is
 * guaranteed to have an extra allocated element set to NULL but not included
 * in the return count, to make iteration easier.  The caller is responsible
 * for calling virStoragePoolFree() on each array element, then calling
 * free() on @pools.
 */
int
virConnectListAllStoragePools(virConnectPtr conn,
                              virStoragePoolPtr **pools,
                              unsigned int flags)
{
    VIR_DEBUG("conn=%p, pools=%p, flags=%x", conn, pools, flags);

    virResetLastError();

    if (pools)
        *pools = NULL;

12737
    virCheckConnectReturn(conn, -1);
12738 12739

    if (conn->storageDriver &&
12740
        conn->storageDriver->connectListAllStoragePools) {
12741
        int ret;
12742
        ret = conn->storageDriver->connectListAllStoragePools(conn, pools, flags);
12743 12744 12745 12746 12747
        if (ret < 0)
            goto error;
        return ret;
    }

12748
    virReportUnsupportedError();
12749 12750 12751 12752 12753 12754

error:
    virDispatchError(conn);
    return -1;
}

12755

12756 12757 12758 12759 12760 12761 12762 12763 12764
/**
 * virConnectNumOfStoragePools:
 * @conn: pointer to hypervisor connection
 *
 * Provides the number of active storage pools
 *
 * Returns the number of pools found, or -1 on error
 */
int
O
Osier Yang 已提交
12765
virConnectNumOfStoragePools(virConnectPtr conn)
12766
{
12767
    VIR_DEBUG("conn=%p", conn);
12768

12769 12770
    virResetLastError();

12771
    virCheckConnectReturn(conn, -1);
12772

12773
    if (conn->storageDriver && conn->storageDriver->connectNumOfStoragePools) {
12774
        int ret;
12775
        ret = conn->storageDriver->connectNumOfStoragePools(conn);
12776 12777 12778 12779
        if (ret < 0)
            goto error;
        return ret;
    }
12780

12781
    virReportUnsupportedError();
12782 12783

error:
12784
    virDispatchError(conn);
12785 12786 12787
    return -1;
}

12788

12789 12790 12791 12792 12793 12794
/**
 * virConnectListStoragePools:
 * @conn: pointer to hypervisor connection
 * @names: array of char * to fill with pool names (allocated by caller)
 * @maxnames: size of the names array
 *
12795 12796 12797 12798 12799
 * Provides the list of names of active storage pools up to maxnames.
 * If there are more than maxnames, the remaining names will be silently
 * ignored.
 *
 * For more control over the results, see virConnectListAllStoragePools().
12800
 *
12801 12802 12803 12804
 * Returns the number of pools found or -1 in case of error.  Note that
 * this command is inherently racy; a pool can be started between a call to
 * virConnectNumOfStoragePools() and this call; you are only guaranteed
 * that all currently active pools were listed if the return is less than
J
John Ferlan 已提交
12805
 * @maxnames. The client must call free() on each returned name.
12806 12807
 */
int
O
Osier Yang 已提交
12808 12809 12810
virConnectListStoragePools(virConnectPtr conn,
                           char **const names,
                           int maxnames)
12811
{
12812
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
12813

12814 12815
    virResetLastError();

12816
    virCheckConnectReturn(conn, -1);
12817 12818
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
12819

12820
    if (conn->storageDriver && conn->storageDriver->connectListStoragePools) {
12821
        int ret;
12822
        ret = conn->storageDriver->connectListStoragePools(conn, names, maxnames);
12823 12824 12825 12826
        if (ret < 0)
            goto error;
        return ret;
    }
12827

12828
    virReportUnsupportedError();
12829

12830
error:
12831
    virDispatchError(conn);
12832
    return -1;
12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846
}


/**
 * virConnectNumOfDefinedStoragePools:
 * @conn: pointer to hypervisor connection
 *
 * Provides the number of inactive storage pools
 *
 * Returns the number of pools found, or -1 on error
 */
int
virConnectNumOfDefinedStoragePools(virConnectPtr conn)
{
12847
    VIR_DEBUG("conn=%p", conn);
12848

12849 12850
    virResetLastError();

12851
    virCheckConnectReturn(conn, -1);
12852

12853
    if (conn->storageDriver && conn->storageDriver->connectNumOfDefinedStoragePools) {
12854
        int ret;
12855
        ret = conn->storageDriver->connectNumOfDefinedStoragePools(conn);
12856 12857 12858 12859
        if (ret < 0)
            goto error;
        return ret;
    }
12860

12861
    virReportUnsupportedError();
12862 12863

error:
12864
    virDispatchError(conn);
12865 12866 12867 12868 12869 12870 12871 12872 12873 12874
    return -1;
}


/**
 * virConnectListDefinedStoragePools:
 * @conn: pointer to hypervisor connection
 * @names: array of char * to fill with pool names (allocated by caller)
 * @maxnames: size of the names array
 *
12875 12876 12877
 * Provides the list of names of inactive storage pools up to maxnames.
 * If there are more than maxnames, the remaining names will be silently
 * ignored.
12878
 *
12879 12880 12881 12882 12883 12884 12885
 * For more control over the results, see virConnectListAllStoragePools().
 *
 * Returns the number of names provided in the array or -1 in case of error.
 * Note that this command is inherently racy; a pool can be defined between
 * a call to virConnectNumOfDefinedStoragePools() and this call; you are only
 * guaranteed that all currently defined pools were listed if the return
 * is less than @maxnames.  The client must call free() on each returned name.
12886 12887 12888 12889 12890 12891
 */
int
virConnectListDefinedStoragePools(virConnectPtr conn,
                                  char **const names,
                                  int maxnames)
{
12892
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
12893

12894 12895
    virResetLastError();

12896
    virCheckConnectReturn(conn, -1);
12897 12898
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
12899

12900
    if (conn->storageDriver && conn->storageDriver->connectListDefinedStoragePools) {
12901
        int ret;
12902
        ret = conn->storageDriver->connectListDefinedStoragePools(conn, names, maxnames);
12903 12904 12905 12906
        if (ret < 0)
            goto error;
        return ret;
    }
12907

12908
    virReportUnsupportedError();
12909 12910

error:
12911
    virDispatchError(conn);
12912 12913 12914 12915
    return -1;
}


12916 12917 12918 12919 12920
/**
 * virConnectFindStoragePoolSources:
 * @conn: pointer to hypervisor connection
 * @type: type of storage pool sources to discover
 * @srcSpec: XML document specifying discovery source
12921
 * @flags: extra flags; not used yet, so callers should always pass 0
12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942
 *
 * Talks to a storage backend and attempts to auto-discover the set of
 * available storage pool sources. e.g. For iSCSI this would be a set of
 * iSCSI targets. For NFS this would be a list of exported paths.  The
 * srcSpec (optional for some storage pool types, e.g. local ones) is
 * an instance of the storage pool's source element specifying where
 * to look for the pools.
 *
 * srcSpec is not required for some types (e.g., those querying
 * local storage resources only)
 *
 * Returns an xml document consisting of a SourceList element
 * containing a source document appropriate to the given pool
 * type for each discovered source.
 */
char *
virConnectFindStoragePoolSources(virConnectPtr conn,
                                 const char *type,
                                 const char *srcSpec,
                                 unsigned int flags)
{
12943
    VIR_DEBUG("conn=%p, type=%s, src=%s, flags=%x",
O
Osier Yang 已提交
12944
              conn, NULLSTR(type), NULLSTR(srcSpec), flags);
12945 12946 12947

    virResetLastError();

12948
    virCheckConnectReturn(conn, NULL);
12949
    virCheckNonNullArgGoto(type, error);
12950
    virCheckReadOnlyGoto(conn->flags, error);
12951

12952
    if (conn->storageDriver && conn->storageDriver->connectFindStoragePoolSources) {
12953
        char *ret;
12954
        ret = conn->storageDriver->connectFindStoragePoolSources(conn, type, srcSpec, flags);
12955 12956 12957 12958
        if (!ret)
            goto error;
        return ret;
    }
12959

12960
    virReportUnsupportedError();
12961 12962

error:
12963
    virDispatchError(conn);
12964 12965 12966 12967
    return NULL;
}


12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980
/**
 * virStoragePoolLookupByName:
 * @conn: pointer to hypervisor connection
 * @name: name of pool to fetch
 *
 * Fetch a storage pool based on its unique name
 *
 * Returns a virStoragePoolPtr object, or NULL if no matching pool is found
 */
virStoragePoolPtr
virStoragePoolLookupByName(virConnectPtr conn,
                           const char *name)
{
12981
    VIR_DEBUG("conn=%p, name=%s", conn, name);
12982

12983 12984
    virResetLastError();

12985
    virCheckConnectReturn(conn, NULL);
12986
    virCheckNonNullArgGoto(name, error);
12987

12988
    if (conn->storageDriver && conn->storageDriver->storagePoolLookupByName) {
12989
        virStoragePoolPtr ret;
12990
        ret = conn->storageDriver->storagePoolLookupByName(conn, name);
12991 12992 12993 12994
        if (!ret)
            goto error;
        return ret;
    }
12995

12996
    virReportUnsupportedError();
12997 12998

error:
12999
    virDispatchError(conn);
13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016
    return NULL;
}


/**
 * virStoragePoolLookupByUUID:
 * @conn: pointer to hypervisor connection
 * @uuid: globally unique id of pool to fetch
 *
 * Fetch a storage pool based on its globally unique id
 *
 * Returns a virStoragePoolPtr object, or NULL if no matching pool is found
 */
virStoragePoolPtr
virStoragePoolLookupByUUID(virConnectPtr conn,
                           const unsigned char *uuid)
{
13017
    VIR_UUID_DEBUG(conn, uuid);
13018

13019 13020
    virResetLastError();

13021
    virCheckConnectReturn(conn, NULL);
13022
    virCheckNonNullArgGoto(uuid, error);
13023

13024
    if (conn->storageDriver && conn->storageDriver->storagePoolLookupByUUID) {
13025
        virStoragePoolPtr ret;
13026
        ret = conn->storageDriver->storagePoolLookupByUUID(conn, uuid);
13027 13028 13029 13030
        if (!ret)
            goto error;
        return ret;
    }
13031

13032
    virReportUnsupportedError();
13033

13034
error:
13035
    virDispatchError(conn);
13036
    return NULL;
13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050
}


/**
 * virStoragePoolLookupByUUIDString:
 * @conn: pointer to hypervisor connection
 * @uuidstr: globally unique id of pool to fetch
 *
 * Fetch a storage pool based on its globally unique id
 *
 * Returns a virStoragePoolPtr object, or NULL if no matching pool is found
 */
virStoragePoolPtr
virStoragePoolLookupByUUIDString(virConnectPtr conn,
13051
                                 const char *uuidstr)
13052 13053
{
    unsigned char uuid[VIR_UUID_BUFLEN];
13054
    VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr));
13055

13056 13057
    virResetLastError();

13058
    virCheckConnectReturn(conn, NULL);
13059
    virCheckNonNullArgGoto(uuidstr, error);
13060 13061

    if (virUUIDParse(uuidstr, uuid) < 0) {
13062 13063 13064
        virReportInvalidArg(uuidstr,
                            _("uuidstr in %s must be a valid UUID"),
                            __FUNCTION__);
13065
        goto error;
13066 13067 13068
    }

    return virStoragePoolLookupByUUID(conn, uuid);
13069 13070

error:
13071
    virDispatchError(conn);
13072
    return NULL;
13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086
}


/**
 * virStoragePoolLookupByVolume:
 * @vol: pointer to storage volume
 *
 * Fetch a storage pool which contains a particular volume
 *
 * Returns a virStoragePoolPtr object, or NULL if no matching pool is found
 */
virStoragePoolPtr
virStoragePoolLookupByVolume(virStorageVolPtr vol)
{
13087
    VIR_DEBUG("vol=%p", vol);
13088

13089 13090 13091
    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_VOL(vol)) {
13092
        virLibConnError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
13093
        virDispatchError(NULL);
13094
        return NULL;
13095 13096
    }

13097
    if (vol->conn->storageDriver && vol->conn->storageDriver->storagePoolLookupByVolume) {
13098
        virStoragePoolPtr ret;
13099
        ret = vol->conn->storageDriver->storagePoolLookupByVolume(vol);
13100 13101 13102 13103
        if (!ret)
            goto error;
        return ret;
    }
13104

13105
    virReportUnsupportedError();
13106

13107
error:
13108
    virDispatchError(vol->conn);
13109
    return NULL;
13110 13111
}

13112

13113 13114 13115 13116
/**
 * virStoragePoolCreateXML:
 * @conn: pointer to hypervisor connection
 * @xmlDesc: XML description for new pool
13117
 * @flags: extra flags; not used yet, so callers should always pass 0
13118 13119
 *
 * Create a new storage based on its XML description. The
D
Daniel Veillard 已提交
13120
 * pool is not persistent, so its definition will disappear
13121 13122 13123 13124 13125 13126 13127 13128 13129
 * when it is destroyed, or if the host is restarted
 *
 * Returns a virStoragePoolPtr object, or NULL if creation failed
 */
virStoragePoolPtr
virStoragePoolCreateXML(virConnectPtr conn,
                        const char *xmlDesc,
                        unsigned int flags)
{
E
Eric Blake 已提交
13130
    VIR_DEBUG("conn=%p, xmlDesc=%s, flags=%x", conn, xmlDesc, flags);
13131

13132 13133
    virResetLastError();

13134
    virCheckConnectReturn(conn, NULL);
13135
    virCheckNonNullArgGoto(xmlDesc, error);
13136
    virCheckReadOnlyGoto(conn->flags, error);
13137

13138
    if (conn->storageDriver && conn->storageDriver->storagePoolCreateXML) {
13139
        virStoragePoolPtr ret;
13140
        ret = conn->storageDriver->storagePoolCreateXML(conn, xmlDesc, flags);
13141 13142 13143 13144
        if (!ret)
            goto error;
        return ret;
    }
13145

13146
    virReportUnsupportedError();
13147 13148

error:
13149
    virDispatchError(conn);
13150 13151 13152
    return NULL;
}

13153

13154 13155 13156 13157
/**
 * virStoragePoolDefineXML:
 * @conn: pointer to hypervisor connection
 * @xml: XML description for new pool
13158
 * @flags: extra flags; not used yet, so callers should always pass 0
13159 13160
 *
 * Define a new inactive storage pool based on its XML description. The
D
Daniel Veillard 已提交
13161
 * pool is persistent, until explicitly undefined.
13162 13163 13164 13165 13166 13167 13168 13169
 *
 * Returns a virStoragePoolPtr object, or NULL if creation failed
 */
virStoragePoolPtr
virStoragePoolDefineXML(virConnectPtr conn,
                        const char *xml,
                        unsigned int flags)
{
E
Eric Blake 已提交
13170
    VIR_DEBUG("conn=%p, xml=%s, flags=%x", conn, xml, flags);
13171

13172 13173
    virResetLastError();

13174
    virCheckConnectReturn(conn, NULL);
13175
    virCheckReadOnlyGoto(conn->flags, error);
13176
    virCheckNonNullArgGoto(xml, error);
13177

13178
    if (conn->storageDriver && conn->storageDriver->storagePoolDefineXML) {
13179
        virStoragePoolPtr ret;
13180
        ret = conn->storageDriver->storagePoolDefineXML(conn, xml, flags);
13181 13182 13183 13184
        if (!ret)
            goto error;
        return ret;
    }
13185

13186
    virReportUnsupportedError();
13187

13188
error:
13189
    virDispatchError(conn);
13190
    return NULL;
13191 13192
}

13193

13194 13195 13196
/**
 * virStoragePoolBuild:
 * @pool: pointer to storage pool
13197
 * @flags: bitwise-OR of virStoragePoolBuildFlags
O
Osier Yang 已提交
13198 13199 13200
 *
 * Currently only filesystem pool accepts flags VIR_STORAGE_POOL_BUILD_OVERWRITE
 * and VIR_STORAGE_POOL_BUILD_NO_OVERWRITE.
13201 13202 13203 13204 13205 13206 13207 13208 13209 13210
 *
 * Build the underlying storage pool
 *
 * Returns 0 on success, or -1 upon failure
 */
int
virStoragePoolBuild(virStoragePoolPtr pool,
                    unsigned int flags)
{
    virConnectPtr conn;
13211
    VIR_DEBUG("pool=%p, flags=%x", pool, flags);
13212

13213 13214
    virResetLastError();

13215
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13216
        virLibStoragePoolError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
13217
        virDispatchError(NULL);
13218
        return -1;
13219 13220
    }
    conn = pool->conn;
13221
    virCheckReadOnlyGoto(conn->flags, error);
13222

13223
    if (conn->storageDriver && conn->storageDriver->storagePoolBuild) {
13224
        int ret;
13225
        ret = conn->storageDriver->storagePoolBuild(pool, flags);
13226 13227 13228 13229
        if (ret < 0)
            goto error;
        return ret;
    }
13230

13231
    virReportUnsupportedError();
13232

13233
error:
13234
    virDispatchError(pool->conn);
13235
    return -1;
13236 13237 13238 13239 13240 13241 13242 13243 13244
}


/**
 * virStoragePoolUndefine:
 * @pool: pointer to storage pool
 *
 * Undefine an inactive storage pool
 *
13245
 * Returns 0 on success, -1 on failure
13246 13247 13248 13249 13250
 */
int
virStoragePoolUndefine(virStoragePoolPtr pool)
{
    virConnectPtr conn;
13251
    VIR_DEBUG("pool=%p", pool);
13252

13253 13254
    virResetLastError();

13255
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13256
        virLibStoragePoolError(VIR_ERR_INVALID_NETWORK, __FUNCTION__);
13257
        virDispatchError(NULL);
13258
        return -1;
13259 13260
    }
    conn = pool->conn;
13261
    virCheckReadOnlyGoto(conn->flags, error);
13262

13263
    if (conn->storageDriver && conn->storageDriver->storagePoolUndefine) {
13264
        int ret;
13265
        ret = conn->storageDriver->storagePoolUndefine(pool);
13266 13267 13268 13269
        if (ret < 0)
            goto error;
        return ret;
    }
13270

13271
    virReportUnsupportedError();
13272

13273
error:
13274
    virDispatchError(pool->conn);
13275
    return -1;
13276 13277 13278 13279 13280 13281
}


/**
 * virStoragePoolCreate:
 * @pool: pointer to storage pool
13282
 * @flags: extra flags; not used yet, so callers should always pass 0
13283 13284 13285 13286 13287 13288 13289 13290 13291 13292
 *
 * Starts an inactive storage pool
 *
 * Returns 0 on success, or -1 if it could not be started
 */
int
virStoragePoolCreate(virStoragePoolPtr pool,
                     unsigned int flags)
{
    virConnectPtr conn;
E
Eric Blake 已提交
13293
    VIR_DEBUG("pool=%p, flags=%x", pool, flags);
13294

13295 13296
    virResetLastError();

13297
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13298
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13299
        virDispatchError(NULL);
13300
        return -1;
13301 13302
    }
    conn = pool->conn;
13303
    virCheckReadOnlyGoto(conn->flags, error);
13304

13305
    if (conn->storageDriver && conn->storageDriver->storagePoolCreate) {
13306
        int ret;
13307
        ret = conn->storageDriver->storagePoolCreate(pool, flags);
13308 13309 13310 13311
        if (ret < 0)
            goto error;
        return ret;
    }
13312

13313
    virReportUnsupportedError();
13314

13315
error:
13316
    virDispatchError(pool->conn);
13317
    return -1;
13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336
}


/**
 * virStoragePoolDestroy:
 * @pool: pointer to storage pool
 *
 * Destroy an active storage pool. This will deactivate the
 * pool on the host, but keep any persistent config associated
 * with it. If it has a persistent config it can later be
 * restarted with virStoragePoolCreate(). This does not free
 * the associated virStoragePoolPtr object.
 *
 * Returns 0 on success, or -1 if it could not be destroyed
 */
int
virStoragePoolDestroy(virStoragePoolPtr pool)
{
    virConnectPtr conn;
13337
    VIR_DEBUG("pool=%p", pool);
13338

13339 13340
    virResetLastError();

13341
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13342
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13343
        virDispatchError(NULL);
13344
        return -1;
13345 13346 13347
    }

    conn = pool->conn;
13348
    virCheckReadOnlyGoto(conn->flags, error);
13349

13350
    if (conn->storageDriver && conn->storageDriver->storagePoolDestroy) {
13351
        int ret;
13352
        ret = conn->storageDriver->storagePoolDestroy(pool);
13353 13354 13355 13356
        if (ret < 0)
            goto error;
        return ret;
    }
13357

13358
    virReportUnsupportedError();
13359 13360

error:
13361
    virDispatchError(pool->conn);
13362 13363 13364
    return -1;
}

13365

13366 13367 13368
/**
 * virStoragePoolDelete:
 * @pool: pointer to storage pool
13369
 * @flags: bitwise-OR of virStoragePoolDeleteFlags
13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381
 *
 * Delete the underlying pool resources. This is
 * a non-recoverable operation. The virStoragePoolPtr object
 * itself is not free'd.
 *
 * Returns 0 on success, or -1 if it could not be obliterate
 */
int
virStoragePoolDelete(virStoragePoolPtr pool,
                     unsigned int flags)
{
    virConnectPtr conn;
13382
    VIR_DEBUG("pool=%p, flags=%x", pool, flags);
13383

13384 13385
    virResetLastError();

13386
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13387
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13388
        virDispatchError(NULL);
13389
        return -1;
13390 13391 13392
    }

    conn = pool->conn;
13393
    virCheckReadOnlyGoto(conn->flags, error);
13394

13395
    if (conn->storageDriver && conn->storageDriver->storagePoolDelete) {
13396
        int ret;
13397
        ret = conn->storageDriver->storagePoolDelete(pool, flags);
13398 13399 13400 13401
        if (ret < 0)
            goto error;
        return ret;
    }
13402

13403
    virReportUnsupportedError();
13404 13405

error:
13406
    virDispatchError(pool->conn);
13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422
    return -1;
}


/**
 * virStoragePoolFree:
 * @pool: pointer to storage pool
 *
 * Free a storage pool object, releasing all memory associated with
 * it. Does not change the state of the pool on the host.
 *
 * Returns 0 on success, or -1 if it could not be free'd.
 */
int
virStoragePoolFree(virStoragePoolPtr pool)
{
13423
    VIR_DEBUG("pool=%p", pool);
13424

13425 13426 13427
    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13428
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13429
        virDispatchError(NULL);
13430
        return -1;
13431
    }
13432
    virObjectUnref(pool);
13433
    return 0;
13434 13435 13436 13437

}


13438 13439
/**
 * virStoragePoolRef:
D
Daniel Veillard 已提交
13440
 * @pool: the pool to hold a reference on
13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451
 *
 * Increment the reference count on the pool. For each
 * additional call to this method, there shall be a corresponding
 * call to virStoragePoolFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
 * it. ie, each new thread using a pool would increment
 * the reference count.
D
Daniel Veillard 已提交
13452 13453
 *
 * Returns 0 in case of success, -1 in case of failure.
13454 13455 13456 13457
 */
int
virStoragePoolRef(virStoragePoolPtr pool)
{
13458 13459
    VIR_DEBUG("pool=%p refs=%d", pool, pool ? pool->object.u.s.refs : 0);

13460 13461
    virResetLastError();

13462
    if ((!VIR_IS_CONNECTED_STORAGE_POOL(pool))) {
13463
        virLibConnError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13464
        virDispatchError(NULL);
13465
        return -1;
13466
    }
13467
    virObjectRef(pool);
13468 13469 13470
    return 0;
}

13471

13472 13473 13474
/**
 * virStoragePoolRefresh:
 * @pool: pointer to storage pool
13475
 * @flags: extra flags; not used yet, so callers should always pass 0
13476 13477 13478 13479 13480
 *
 * Request that the pool refresh its list of volumes. This may
 * involve communicating with a remote server, and/or initializing
 * new devices at the OS layer
 *
13481
 * Returns 0 if the volume list was refreshed, -1 on failure
13482 13483 13484 13485 13486 13487
 */
int
virStoragePoolRefresh(virStoragePoolPtr pool,
                      unsigned int flags)
{
    virConnectPtr conn;
E
Eric Blake 已提交
13488
    VIR_DEBUG("pool=%p, flags=%x", pool, flags);
13489

13490 13491
    virResetLastError();

13492
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13493
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13494
        virDispatchError(NULL);
13495
        return -1;
13496 13497 13498
    }

    conn = pool->conn;
13499
    virCheckReadOnlyGoto(conn->flags, error);
13500

13501
    if (conn->storageDriver && conn->storageDriver->storagePoolRefresh) {
13502
        int ret;
13503
        ret = conn->storageDriver->storagePoolRefresh(pool, flags);
13504 13505 13506 13507
        if (ret < 0)
            goto error;
        return ret;
    }
13508

13509
    virReportUnsupportedError();
13510 13511

error:
13512
    virDispatchError(pool->conn);
13513 13514 13515 13516 13517 13518 13519 13520 13521 13522
    return -1;
}


/**
 * virStoragePoolGetName:
 * @pool: pointer to storage pool
 *
 * Fetch the locally unique name of the storage pool
 *
13523
 * Returns the name of the pool, or NULL on error
13524 13525 13526 13527
 */
const char*
virStoragePoolGetName(virStoragePoolPtr pool)
{
13528
    VIR_DEBUG("pool=%p", pool);
13529

13530 13531
    virResetLastError();

13532
    if (!VIR_IS_STORAGE_POOL(pool)) {
13533
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13534
        virDispatchError(NULL);
13535
        return NULL;
13536
    }
13537
    return pool->name;
13538 13539 13540 13541 13542 13543 13544 13545 13546 13547
}


/**
 * virStoragePoolGetUUID:
 * @pool: pointer to storage pool
 * @uuid: buffer of VIR_UUID_BUFLEN bytes in size
 *
 * Fetch the globally unique ID of the storage pool
 *
13548
 * Returns 0 on success, or -1 on error;
13549 13550 13551 13552 13553
 */
int
virStoragePoolGetUUID(virStoragePoolPtr pool,
                      unsigned char *uuid)
{
13554
    VIR_DEBUG("pool=%p, uuid=%p", pool, uuid);
13555

13556 13557
    virResetLastError();

13558
    if (!VIR_IS_STORAGE_POOL(pool)) {
13559
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13560
        virDispatchError(NULL);
13561
        return -1;
13562
    }
13563
    virCheckNonNullArgGoto(uuid, error);
13564 13565 13566

    memcpy(uuid, &pool->uuid[0], VIR_UUID_BUFLEN);

13567
    return 0;
13568

13569
error:
13570
    virDispatchError(pool->conn);
13571
    return -1;
13572 13573
}

13574

13575 13576 13577 13578 13579 13580 13581
/**
 * virStoragePoolGetUUIDString:
 * @pool: pointer to storage pool
 * @buf: buffer of VIR_UUID_STRING_BUFLEN bytes in size
 *
 * Fetch the globally unique ID of the storage pool as a string
 *
13582
 * Returns 0 on success, or -1 on error;
13583 13584 13585 13586 13587
 */
int
virStoragePoolGetUUIDString(virStoragePoolPtr pool,
                            char *buf)
{
13588
    VIR_DEBUG("pool=%p, buf=%p", pool, buf);
13589

13590 13591
    virResetLastError();

13592
    if (!VIR_IS_STORAGE_POOL(pool)) {
13593
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13594
        virDispatchError(NULL);
13595
        return -1;
13596
    }
13597
    virCheckNonNullArgGoto(buf, error);
13598

E
Eric Blake 已提交
13599
    virUUIDFormat(pool->uuid, buf);
13600
    return 0;
13601

13602
error:
13603
    virDispatchError(pool->conn);
13604
    return -1;
13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615
}


/**
 * virStoragePoolGetInfo:
 * @pool: pointer to storage pool
 * @info: pointer at which to store info
 *
 * Get volatile information about the storage pool
 * such as free space / usage summary
 *
13616
 * Returns 0 on success, or -1 on failure.
13617 13618 13619 13620 13621 13622
 */
int
virStoragePoolGetInfo(virStoragePoolPtr pool,
                      virStoragePoolInfoPtr info)
{
    virConnectPtr conn;
13623
    VIR_DEBUG("pool=%p, info=%p", pool, info);
13624

13625 13626
    virResetLastError();

13627
    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13628
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13629
        virDispatchError(NULL);
13630
        return -1;
13631
    }
13632
    virCheckNonNullArgGoto(info, error);
13633 13634 13635 13636 13637

    memset(info, 0, sizeof(virStoragePoolInfo));

    conn = pool->conn;

13638
    if (conn->storageDriver->storagePoolGetInfo) {
13639
        int ret;
13640
        ret = conn->storageDriver->storagePoolGetInfo(pool, info);
13641 13642 13643 13644
        if (ret < 0)
            goto error;
        return ret;
    }
13645

13646
    virReportUnsupportedError();
13647

13648
error:
13649
    virDispatchError(pool->conn);
13650
    return -1;
13651 13652 13653 13654 13655 13656
}


/**
 * virStoragePoolGetXMLDesc:
 * @pool: pointer to storage pool
13657
 * @flags: bitwise-OR of virStorageXMLFlags
13658 13659 13660 13661 13662
 *
 * Fetch an XML document describing all aspects of the
 * storage pool. This is suitable for later feeding back
 * into the virStoragePoolCreateXML method.
 *
13663
 * Returns a XML document, or NULL on error
13664 13665 13666 13667 13668 13669
 */
char *
virStoragePoolGetXMLDesc(virStoragePoolPtr pool,
                         unsigned int flags)
{
    virConnectPtr conn;
13670
    VIR_DEBUG("pool=%p, flags=%x", pool, flags);
13671

13672 13673 13674
    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13675
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13676
        virDispatchError(NULL);
13677
        return NULL;
13678 13679 13680 13681
    }

    conn = pool->conn;

13682
    if (conn->storageDriver && conn->storageDriver->storagePoolGetXMLDesc) {
13683
        char *ret;
13684
        ret = conn->storageDriver->storagePoolGetXMLDesc(pool, flags);
13685 13686 13687 13688
        if (!ret)
            goto error;
        return ret;
    }
13689

13690
    virReportUnsupportedError();
13691

13692
error:
13693
    virDispatchError(pool->conn);
13694
    return NULL;
13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705
}


/**
 * virStoragePoolGetAutostart:
 * @pool: pointer to storage pool
 * @autostart: location in which to store autostart flag
 *
 * Fetches the value of the autostart flag, which determines
 * whether the pool is automatically started at boot time
 *
13706
 * Returns 0 on success, -1 on failure
13707 13708 13709 13710 13711 13712
 */
int
virStoragePoolGetAutostart(virStoragePoolPtr pool,
                           int *autostart)
{
    virConnectPtr conn;
13713
    VIR_DEBUG("pool=%p, autostart=%p", pool, autostart);
13714

13715 13716 13717
    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13718
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13719
        virDispatchError(NULL);
13720
        return -1;
13721
    }
13722
    virCheckNonNullArgGoto(autostart, error);
13723 13724 13725

    conn = pool->conn;

13726
    if (conn->storageDriver && conn->storageDriver->storagePoolGetAutostart) {
13727
        int ret;
13728
        ret = conn->storageDriver->storagePoolGetAutostart(pool, autostart);
13729 13730 13731 13732
        if (ret < 0)
            goto error;
        return ret;
    }
13733

13734
    virReportUnsupportedError();
13735 13736

error:
13737
    virDispatchError(pool->conn);
13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748
    return -1;
}


/**
 * virStoragePoolSetAutostart:
 * @pool: pointer to storage pool
 * @autostart: new flag setting
 *
 * Sets the autostart flag
 *
13749
 * Returns 0 on success, -1 on failure
13750 13751 13752 13753 13754 13755
 */
int
virStoragePoolSetAutostart(virStoragePoolPtr pool,
                           int autostart)
{
    virConnectPtr conn;
13756
    VIR_DEBUG("pool=%p, autostart=%d", pool, autostart);
13757

13758 13759 13760
    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
13761
        virLibStoragePoolError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13762
        virDispatchError(NULL);
13763
        return -1;
13764 13765
    }

13766
    virCheckReadOnlyGoto(pool->conn->flags, error);
13767

13768 13769
    conn = pool->conn;

13770
    if (conn->storageDriver && conn->storageDriver->storagePoolSetAutostart) {
13771
        int ret;
13772
        ret = conn->storageDriver->storagePoolSetAutostart(pool, autostart);
13773 13774 13775 13776
        if (ret < 0)
            goto error;
        return ret;
    }
13777

13778
    virReportUnsupportedError();
13779 13780

error:
13781
    virDispatchError(pool->conn);
13782 13783 13784
    return -1;
}

13785

13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819
/**
 * virStoragePoolListAllVolumes:
 * @pool: Pointer to storage pool
 * @vols: Pointer to a variable to store the array containing storage volume
 *        objects or NULL if the list is not required (just returns number
 *        of volumes).
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Collect the list of storage volumes, and allocate an array to store those
 * objects.
 *
 * Returns the number of storage volumes found or -1 and sets @vols to
 * NULL in case of error.  On success, the array stored into @vols is
 * guaranteed to have an extra allocated element set to NULL but not included
 * in the return count, to make iteration easier.  The caller is responsible
 * for calling virStorageVolFree() on each array element, then calling
 * free() on @vols.
 */
int
virStoragePoolListAllVolumes(virStoragePoolPtr pool,
                             virStorageVolPtr **vols,
                             unsigned int flags)
{
    VIR_DEBUG("pool=%p, vols=%p, flags=%x", pool, vols, flags);

    virResetLastError();

    if (!VIR_IS_STORAGE_POOL(pool)) {
        virLibConnError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    if (pool->conn->storageDriver &&
13820
        pool->conn->storageDriver->storagePoolListAllVolumes) {
13821
        int ret;
13822
        ret = pool->conn->storageDriver->storagePoolListAllVolumes(pool, vols, flags);
13823 13824 13825 13826 13827
        if (ret < 0)
            goto error;
        return ret;
    }

13828
    virReportUnsupportedError();
13829 13830 13831 13832 13833

error:
    virDispatchError(pool->conn);
    return -1;
}
13834

13835

13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846
/**
 * virStoragePoolNumOfVolumes:
 * @pool: pointer to storage pool
 *
 * Fetch the number of storage volumes within a pool
 *
 * Returns the number of storage pools, or -1 on failure
 */
int
virStoragePoolNumOfVolumes(virStoragePoolPtr pool)
{
13847
    VIR_DEBUG("pool=%p", pool);
13848

13849 13850
    virResetLastError();

13851
    if (!VIR_IS_STORAGE_POOL(pool)) {
13852
        virLibConnError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13853
        virDispatchError(NULL);
13854
        return -1;
13855 13856
    }

13857
    if (pool->conn->storageDriver && pool->conn->storageDriver->storagePoolNumOfVolumes) {
13858
        int ret;
13859
        ret = pool->conn->storageDriver->storagePoolNumOfVolumes(pool);
13860 13861 13862 13863
        if (ret < 0)
            goto error;
        return ret;
    }
13864

13865
    virReportUnsupportedError();
13866 13867

error:
13868
    virDispatchError(pool->conn);
13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881
    return -1;
}


/**
 * virStoragePoolListVolumes:
 * @pool: pointer to storage pool
 * @names: array in which to storage volume names
 * @maxnames: size of names array
 *
 * Fetch list of storage volume names, limiting to
 * at most maxnames.
 *
13882 13883
 * To list the volume objects directly, see virStoragePoolListAllVolumes().
 *
13884 13885 13886 13887 13888 13889 13890
 * Returns the number of names fetched, or -1 on error
 */
int
virStoragePoolListVolumes(virStoragePoolPtr pool,
                          char **const names,
                          int maxnames)
{
13891
    VIR_DEBUG("pool=%p, names=%p, maxnames=%d", pool, names, maxnames);
13892

13893 13894
    virResetLastError();

13895
    if (!VIR_IS_STORAGE_POOL(pool)) {
13896
        virLibConnError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
13897
        virDispatchError(NULL);
13898
        return -1;
13899 13900
    }

13901 13902
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
13903

13904
    if (pool->conn->storageDriver && pool->conn->storageDriver->storagePoolListVolumes) {
13905
        int ret;
13906
        ret = pool->conn->storageDriver->storagePoolListVolumes(pool, names, maxnames);
13907 13908 13909 13910
        if (ret < 0)
            goto error;
        return ret;
    }
13911

13912
    virReportUnsupportedError();
13913 13914

error:
13915
    virDispatchError(pool->conn);
13916 13917 13918 13919 13920 13921
    return -1;
}


/**
 * virStorageVolGetConnect:
13922
 * @vol: pointer to a pool
13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934
 *
 * Provides the connection pointer associated with a storage volume.  The
 * reference counter on the connection is not increased by this
 * call.
 *
 * WARNING: When writing libvirt bindings in other languages, do
 * not use this function.  Instead, store the connection and
 * the volume object together.
 *
 * Returns the virConnectPtr or NULL in case of failure.
 */
virConnectPtr
13935
virStorageVolGetConnect(virStorageVolPtr vol)
13936
{
13937
    VIR_DEBUG("vol=%p", vol);
13938

13939 13940
    virResetLastError();

13941
    if (!VIR_IS_STORAGE_VOL(vol)) {
13942
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
13943
        virDispatchError(NULL);
13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957
        return NULL;
    }
    return vol->conn;
}


/**
 * virStorageVolLookupByName:
 * @pool: pointer to storage pool
 * @name: name of storage volume
 *
 * Fetch a pointer to a storage volume based on its name
 * within a pool
 *
13958
 * Returns a storage volume, or NULL if not found / error
13959 13960 13961 13962 13963
 */
virStorageVolPtr
virStorageVolLookupByName(virStoragePoolPtr pool,
                          const char *name)
{
13964
    VIR_DEBUG("pool=%p, name=%s", pool, name);
13965

13966 13967
    virResetLastError();

13968
    if (!VIR_IS_STORAGE_POOL(pool)) {
13969
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
13970
        virDispatchError(NULL);
13971
        return NULL;
13972
    }
13973 13974

    virCheckNonNullArgGoto(name, error);
13975

13976
    if (pool->conn->storageDriver && pool->conn->storageDriver->storageVolLookupByName) {
13977
        virStorageVolPtr ret;
13978
        ret = pool->conn->storageDriver->storageVolLookupByName(pool, name);
13979 13980 13981 13982
        if (!ret)
            goto error;
        return ret;
    }
13983

13984
    virReportUnsupportedError();
13985 13986

error:
13987
    virDispatchError(pool->conn);
13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999
    return NULL;
}


/**
 * virStorageVolLookupByKey:
 * @conn: pointer to hypervisor connection
 * @key: globally unique key
 *
 * Fetch a pointer to a storage volume based on its
 * globally unique key
 *
14000
 * Returns a storage volume, or NULL if not found / error
14001 14002 14003 14004 14005
 */
virStorageVolPtr
virStorageVolLookupByKey(virConnectPtr conn,
                         const char *key)
{
14006
    VIR_DEBUG("conn=%p, key=%s", conn, key);
14007

14008 14009
    virResetLastError();

14010
    virCheckConnectReturn(conn, NULL);
14011
    virCheckNonNullArgGoto(key, error);
14012

14013
    if (conn->storageDriver && conn->storageDriver->storageVolLookupByKey) {
14014
        virStorageVolPtr ret;
14015
        ret = conn->storageDriver->storageVolLookupByKey(conn, key);
14016 14017 14018 14019
        if (!ret)
            goto error;
        return ret;
    }
14020

14021
    virReportUnsupportedError();
14022 14023

error:
14024
    virDispatchError(conn);
14025 14026 14027
    return NULL;
}

14028

14029 14030 14031 14032 14033 14034 14035 14036
/**
 * virStorageVolLookupByPath:
 * @conn: pointer to hypervisor connection
 * @path: locally unique path
 *
 * Fetch a pointer to a storage volume based on its
 * locally (host) unique path
 *
14037
 * Returns a storage volume, or NULL if not found / error
14038 14039 14040 14041 14042
 */
virStorageVolPtr
virStorageVolLookupByPath(virConnectPtr conn,
                          const char *path)
{
14043
    VIR_DEBUG("conn=%p, path=%s", conn, path);
14044

14045 14046
    virResetLastError();

14047
    virCheckConnectReturn(conn, NULL);
14048
    virCheckNonNullArgGoto(path, error);
14049

14050
    if (conn->storageDriver && conn->storageDriver->storageVolLookupByPath) {
14051
        virStorageVolPtr ret;
14052
        ret = conn->storageDriver->storageVolLookupByPath(conn, path);
14053 14054 14055 14056
        if (!ret)
            goto error;
        return ret;
    }
14057

14058
    virReportUnsupportedError();
14059 14060

error:
14061
    virDispatchError(conn);
14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072
    return NULL;
}


/**
 * virStorageVolGetName:
 * @vol: pointer to storage volume
 *
 * Fetch the storage volume name. This is unique
 * within the scope of a pool
 *
14073
 * Returns the volume name, or NULL on error
14074 14075 14076 14077
 */
const char*
virStorageVolGetName(virStorageVolPtr vol)
{
14078
    VIR_DEBUG("vol=%p", vol);
14079

14080 14081
    virResetLastError();

14082
    if (!VIR_IS_STORAGE_VOL(vol)) {
14083
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14084
        virDispatchError(NULL);
14085
        return NULL;
14086
    }
14087
    return vol->name;
14088 14089 14090 14091 14092 14093 14094 14095
}


/**
 * virStorageVolGetKey:
 * @vol: pointer to storage volume
 *
 * Fetch the storage volume key. This is globally
14096
 * unique, so the same volume will have the same
14097 14098
 * key no matter what host it is accessed from
 *
14099
 * Returns the volume key, or NULL on error
14100 14101 14102 14103
 */
const char*
virStorageVolGetKey(virStorageVolPtr vol)
{
14104
    VIR_DEBUG("vol=%p", vol);
14105

14106 14107
    virResetLastError();

14108
    if (!VIR_IS_STORAGE_VOL(vol)) {
14109
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14110
        virDispatchError(NULL);
14111
        return NULL;
14112
    }
14113
    return vol->key;
14114 14115 14116 14117 14118 14119
}


/**
 * virStorageVolCreateXML:
 * @pool: pointer to storage pool
E
Eric Blake 已提交
14120
 * @xmlDesc: description of volume to create
14121
 * @flags: bitwise-OR of virStorageVolCreateFlags
14122 14123 14124
 *
 * Create a storage volume within a pool based
 * on an XML description. Not all pools support
14125 14126 14127 14128 14129 14130
 * creation of volumes.
 *
 * Since 1.0.1 VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA
 * in flags can be used to get higher performance with
 * qcow2 image files which don't support full preallocation,
 * by creating a sparse image file with metadata.
14131
 *
14132
 * Returns the storage volume, or NULL on error
14133 14134 14135
 */
virStorageVolPtr
virStorageVolCreateXML(virStoragePoolPtr pool,
E
Eric Blake 已提交
14136
                       const char *xmlDesc,
14137 14138
                       unsigned int flags)
{
E
Eric Blake 已提交
14139
    VIR_DEBUG("pool=%p, xmlDesc=%s, flags=%x", pool, xmlDesc, flags);
14140

14141 14142
    virResetLastError();

14143
    if (!VIR_IS_STORAGE_POOL(pool)) {
14144
        virLibConnError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
14145
        virDispatchError(NULL);
14146
        return NULL;
14147 14148
    }

E
Eric Blake 已提交
14149
    virCheckNonNullArgGoto(xmlDesc, error);
14150

14151
    virCheckReadOnlyGoto(pool->conn->flags, error);
14152

14153
    if (pool->conn->storageDriver && pool->conn->storageDriver->storageVolCreateXML) {
14154
        virStorageVolPtr ret;
14155
        ret = pool->conn->storageDriver->storageVolCreateXML(pool, xmlDesc, flags);
14156 14157 14158 14159
        if (!ret)
            goto error;
        return ret;
    }
14160

14161
    virReportUnsupportedError();
14162 14163

error:
14164
    virDispatchError(pool->conn);
14165 14166 14167 14168
    return NULL;
}


14169 14170 14171
/**
 * virStorageVolCreateXMLFrom:
 * @pool: pointer to parent pool for the new volume
E
Eric Blake 已提交
14172
 * @xmlDesc: description of volume to create
14173
 * @clonevol: storage volume to use as input
14174
 * @flags: bitwise-OR of virStorageVolCreateFlags
14175 14176 14177 14178 14179 14180
 *
 * Create a storage volume in the parent pool, using the
 * 'clonevol' volume as input. Information for the new
 * volume (name, perms)  are passed via a typical volume
 * XML description.
 *
14181 14182 14183 14184 14185
 * Since 1.0.1 VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA
 * in flags can be used to get higher performance with
 * qcow2 image files which don't support full preallocation,
 * by creating a sparse image file with metadata.
 *
14186
 * Returns the storage volume, or NULL on error
14187 14188 14189
 */
virStorageVolPtr
virStorageVolCreateXMLFrom(virStoragePoolPtr pool,
E
Eric Blake 已提交
14190
                           const char *xmlDesc,
14191 14192 14193
                           virStorageVolPtr clonevol,
                           unsigned int flags)
{
E
Eric Blake 已提交
14194 14195
    VIR_DEBUG("pool=%p, xmlDesc=%s, clonevol=%p, flags=%x",
              pool, xmlDesc, clonevol, flags);
14196 14197 14198 14199

    virResetLastError();

    if (!VIR_IS_STORAGE_POOL(pool)) {
14200
        virLibConnError(VIR_ERR_INVALID_STORAGE_POOL, __FUNCTION__);
14201
        virDispatchError(NULL);
14202
        return NULL;
14203 14204 14205
    }

    if (!VIR_IS_STORAGE_VOL(clonevol)) {
14206
        virLibConnError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14207
        goto error;
14208 14209
    }

E
Eric Blake 已提交
14210
    virCheckNonNullArgGoto(xmlDesc, error);
14211
    virCheckReadOnlyGoto(pool->conn->flags | clonevol->conn->flags, error);
14212 14213

    if (pool->conn->storageDriver &&
14214
        pool->conn->storageDriver->storageVolCreateXMLFrom) {
14215
        virStorageVolPtr ret;
14216
        ret = pool->conn->storageDriver->storageVolCreateXMLFrom(pool, xmlDesc,
14217
                                                          clonevol, flags);
14218 14219 14220 14221 14222
        if (!ret)
            goto error;
        return ret;
    }

14223
    virReportUnsupportedError();
14224 14225

error:
14226
    virDispatchError(pool->conn);
14227 14228 14229 14230
    return NULL;
}


14231 14232 14233 14234 14235 14236
/**
 * virStorageVolDownload:
 * @vol: pointer to volume to download from
 * @stream: stream to use as output
 * @offset: position in @vol to start reading from
 * @length: limit on amount of data to download
14237
 * @flags: extra flags; not used yet, so callers should always pass 0
14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257
 *
 * Download the content of the volume as a stream. If @length
 * is zero, then the remaining contents of the volume after
 * @offset will be downloaded.
 *
 * This call sets up an asynchronous stream; subsequent use of
 * stream APIs is necessary to transfer the actual data,
 * determine how much data is successfully transferred, and
 * detect any errors. The results will be unpredictable if
 * another active stream is writing to the storage volume.
 *
 * Returns 0, or -1 upon error.
 */
int
virStorageVolDownload(virStorageVolPtr vol,
                      virStreamPtr stream,
                      unsigned long long offset,
                      unsigned long long length,
                      unsigned int flags)
{
E
Eric Blake 已提交
14258
    VIR_DEBUG("vol=%p, stream=%p, offset=%llu, length=%llu, flags=%x",
14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272
              vol, stream, offset, length, flags);

    virResetLastError();

    if (!VIR_IS_STORAGE_VOL(vol)) {
        virLibConnError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
        return -1;
    }

    if (!VIR_IS_STREAM(stream)) {
        virLibConnError(VIR_ERR_INVALID_STREAM, __FUNCTION__);
        return -1;
    }

14273
    virCheckReadOnlyGoto(vol->conn->flags | stream->conn->flags, error);
14274 14275

    if (vol->conn->storageDriver &&
14276
        vol->conn->storageDriver->storageVolDownload) {
14277
        int ret;
14278
        ret = vol->conn->storageDriver->storageVolDownload(vol,
O
Osier Yang 已提交
14279 14280 14281 14282
                                                           stream,
                                                           offset,
                                                           length,
                                                           flags);
14283 14284 14285 14286 14287
        if (ret < 0)
            goto error;
        return ret;
    }

14288
    virReportUnsupportedError();
14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301

error:
    virDispatchError(vol->conn);
    return -1;
}


/**
 * virStorageVolUpload:
 * @vol: pointer to volume to upload
 * @stream: stream to use as input
 * @offset: position to start writing to
 * @length: limit on amount of data to upload
14302
 * @flags: extra flags; not used yet, so callers should always pass 0
14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324
 *
 * Upload new content to the volume from a stream. This call
 * will fail if @offset + @length exceeds the size of the
 * volume. Otherwise, if @length is non-zero, an error
 * will be raised if an attempt is made to upload greater
 * than @length bytes of data.
 *
 * This call sets up an asynchronous stream; subsequent use of
 * stream APIs is necessary to transfer the actual data,
 * determine how much data is successfully transferred, and
 * detect any errors. The results will be unpredictable if
 * another active stream is writing to the storage volume.
 *
 * Returns 0, or -1 upon error.
 */
int
virStorageVolUpload(virStorageVolPtr vol,
                    virStreamPtr stream,
                    unsigned long long offset,
                    unsigned long long length,
                    unsigned int flags)
{
E
Eric Blake 已提交
14325
    VIR_DEBUG("vol=%p, stream=%p, offset=%llu, length=%llu, flags=%x",
14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339
              vol, stream, offset, length, flags);

    virResetLastError();

    if (!VIR_IS_STORAGE_VOL(vol)) {
        virLibConnError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
        return -1;
    }

    if (!VIR_IS_STREAM(stream)) {
        virLibConnError(VIR_ERR_INVALID_STREAM, __FUNCTION__);
        return -1;
    }

14340
    virCheckReadOnlyGoto(vol->conn->flags | stream->conn->flags, error);
14341 14342

    if (vol->conn->storageDriver &&
14343
        vol->conn->storageDriver->storageVolUpload) {
14344
        int ret;
14345
        ret = vol->conn->storageDriver->storageVolUpload(vol,
14346 14347 14348 14349 14350 14351 14352 14353 14354
                                                  stream,
                                                  offset,
                                                  length,
                                                  flags);
        if (ret < 0)
            goto error;
        return ret;
    }

14355
    virReportUnsupportedError();
14356 14357 14358 14359 14360 14361 14362

error:
    virDispatchError(vol->conn);
    return -1;
}


14363 14364 14365
/**
 * virStorageVolDelete:
 * @vol: pointer to storage volume
14366
 * @flags: extra flags; not used yet, so callers should always pass 0
14367 14368 14369
 *
 * Delete the storage volume from the pool
 *
14370
 * Returns 0 on success, or -1 on error
14371 14372 14373 14374 14375 14376
 */
int
virStorageVolDelete(virStorageVolPtr vol,
                    unsigned int flags)
{
    virConnectPtr conn;
14377
    VIR_DEBUG("vol=%p, flags=%x", vol, flags);
14378

14379 14380
    virResetLastError();

14381
    if (!VIR_IS_CONNECTED_STORAGE_VOL(vol)) {
14382
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14383
        virDispatchError(NULL);
14384
        return -1;
14385 14386 14387
    }

    conn = vol->conn;
14388
    virCheckReadOnlyGoto(conn->flags, error);
14389

14390
    if (conn->storageDriver && conn->storageDriver->storageVolDelete) {
14391
        int ret;
14392
        ret = conn->storageDriver->storageVolDelete(vol, flags);
14393 14394 14395 14396
        if (ret < 0)
            goto error;
        return ret;
    }
14397

14398
    virReportUnsupportedError();
14399 14400

error:
14401
    virDispatchError(vol->conn);
14402 14403 14404 14405
    return -1;
}


14406 14407 14408
/**
 * virStorageVolWipe:
 * @vol: pointer to storage volume
14409
 * @flags: extra flags; not used yet, so callers should always pass 0
14410 14411 14412 14413 14414 14415 14416 14417 14418 14419
 *
 * Ensure data previously on a volume is not accessible to future reads
 *
 * Returns 0 on success, or -1 on error
 */
int
virStorageVolWipe(virStorageVolPtr vol,
                  unsigned int flags)
{
    virConnectPtr conn;
14420
    VIR_DEBUG("vol=%p, flags=%x", vol, flags);
14421 14422 14423 14424

    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_VOL(vol)) {
14425
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14426
        virDispatchError(NULL);
14427
        return -1;
14428 14429 14430
    }

    conn = vol->conn;
14431
    virCheckReadOnlyGoto(conn->flags, error);
14432

14433
    if (conn->storageDriver && conn->storageDriver->storageVolWipe) {
14434
        int ret;
14435
        ret = conn->storageDriver->storageVolWipe(vol, flags);
14436 14437 14438 14439 14440 14441
        if (ret < 0) {
            goto error;
        }
        return ret;
    }

14442
    virReportUnsupportedError();
14443 14444 14445 14446 14447 14448 14449

error:
    virDispatchError(vol->conn);
    return -1;
}


14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477
/**
 * virStorageVolWipePattern:
 * @vol: pointer to storage volume
 * @algorithm: one of virStorageVolWipeAlgorithm
 * @flags: future flags, use 0 for now
 *
 * Similar to virStorageVolWipe, but one can choose
 * between different wiping algorithms.
 *
 * Returns 0 on success, or -1 on error.
 */
int
virStorageVolWipePattern(virStorageVolPtr vol,
                         unsigned int algorithm,
                         unsigned int flags)
{
    virConnectPtr conn;
    VIR_DEBUG("vol=%p, algorithm=%u, flags=%x", vol, algorithm, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_VOL(vol)) {
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = vol->conn;
14478
    virCheckReadOnlyGoto(conn->flags, error);
14479

14480
    if (conn->storageDriver && conn->storageDriver->storageVolWipePattern) {
14481
        int ret;
14482
        ret = conn->storageDriver->storageVolWipePattern(vol, algorithm, flags);
14483 14484 14485 14486 14487 14488
        if (ret < 0) {
            goto error;
        }
        return ret;
    }

14489
    virReportUnsupportedError();
14490 14491 14492 14493 14494 14495

error:
    virDispatchError(vol->conn);
    return -1;
}

14496

14497 14498 14499 14500 14501
/**
 * virStorageVolFree:
 * @vol: pointer to storage volume
 *
 * Release the storage volume handle. The underlying
14502
 * storage volume continues to exist.
14503
 *
14504
 * Returns 0 on success, or -1 on error
14505 14506 14507 14508
 */
int
virStorageVolFree(virStorageVolPtr vol)
{
14509
    VIR_DEBUG("vol=%p", vol);
14510

14511 14512
    virResetLastError();

14513
    if (!VIR_IS_STORAGE_VOL(vol)) {
14514
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14515
        virDispatchError(NULL);
14516
        return -1;
14517
    }
14518
    virObjectUnref(vol);
14519
    return 0;
14520 14521 14522
}


14523 14524
/**
 * virStorageVolRef:
D
Daniel Veillard 已提交
14525
 * @vol: the vol to hold a reference on
14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536
 *
 * Increment the reference count on the vol. For each
 * additional call to this method, there shall be a corresponding
 * call to virStorageVolFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
 * it. ie, each new thread using a vol would increment
 * the reference count.
D
Daniel Veillard 已提交
14537 14538
 *
 * Returns 0 in case of success, -1 in case of failure.
14539 14540 14541 14542
 */
int
virStorageVolRef(virStorageVolPtr vol)
{
14543 14544
    VIR_DEBUG("vol=%p refs=%d", vol, vol ? vol->object.u.s.refs : 0);

14545 14546
    virResetLastError();

14547
    if ((!VIR_IS_CONNECTED_STORAGE_VOL(vol))) {
14548
        virLibConnError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14549
        virDispatchError(NULL);
14550
        return -1;
14551
    }
14552
    virObjectRef(vol);
14553 14554 14555
    return 0;
}

14556

14557 14558 14559 14560 14561 14562 14563 14564
/**
 * virStorageVolGetInfo:
 * @vol: pointer to storage volume
 * @info: pointer at which to store info
 *
 * Fetches volatile information about the storage
 * volume such as its current allocation
 *
14565
 * Returns 0 on success, or -1 on failure
14566 14567 14568 14569 14570 14571
 */
int
virStorageVolGetInfo(virStorageVolPtr vol,
                     virStorageVolInfoPtr info)
{
    virConnectPtr conn;
14572
    VIR_DEBUG("vol=%p, info=%p", vol, info);
14573

14574 14575
    virResetLastError();

14576
    if (!VIR_IS_CONNECTED_STORAGE_VOL(vol)) {
14577
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14578
        virDispatchError(NULL);
14579
        return -1;
14580
    }
14581
    virCheckNonNullArgGoto(info, error);
14582 14583 14584 14585 14586

    memset(info, 0, sizeof(virStorageVolInfo));

    conn = vol->conn;

14587
    if (conn->storageDriver->storageVolGetInfo){
14588
        int ret;
14589
        ret = conn->storageDriver->storageVolGetInfo(vol, info);
14590 14591 14592 14593
        if (ret < 0)
            goto error;
        return ret;
    }
14594

14595
    virReportUnsupportedError();
14596 14597

error:
14598
    virDispatchError(vol->conn);
14599 14600 14601 14602 14603 14604 14605
    return -1;
}


/**
 * virStorageVolGetXMLDesc:
 * @vol: pointer to storage volume
14606
 * @flags: extra flags; not used yet, so callers should always pass 0
14607 14608 14609 14610
 *
 * Fetch an XML document describing all aspects of
 * the storage volume
 *
14611
 * Returns the XML document, or NULL on error
14612 14613 14614 14615 14616 14617
 */
char *
virStorageVolGetXMLDesc(virStorageVolPtr vol,
                        unsigned int flags)
{
    virConnectPtr conn;
14618
    VIR_DEBUG("vol=%p, flags=%x", vol, flags);
14619

14620 14621
    virResetLastError();

14622
    if (!VIR_IS_STORAGE_VOL(vol)) {
14623
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14624
        virDispatchError(NULL);
14625
        return NULL;
14626 14627 14628 14629
    }

    conn = vol->conn;

14630
    if (conn->storageDriver && conn->storageDriver->storageVolGetXMLDesc) {
14631
        char *ret;
14632
        ret = conn->storageDriver->storageVolGetXMLDesc(vol, flags);
14633 14634 14635 14636
        if (!ret)
            goto error;
        return ret;
    }
14637

14638
    virReportUnsupportedError();
14639

14640
error:
14641
    virDispatchError(vol->conn);
14642
    return NULL;
14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655
}


/**
 * virStorageVolGetPath:
 * @vol: pointer to storage volume
 *
 * Fetch the storage volume path. Depending on the pool
 * configuration this is either persistent across hosts,
 * or dynamically assigned at pool startup. Consult
 * pool documentation for information on getting the
 * persistent naming
 *
14656 14657
 * Returns the storage volume path, or NULL on error. The
 * caller must free() the returned path after use.
14658 14659 14660 14661 14662
 */
char *
virStorageVolGetPath(virStorageVolPtr vol)
{
    virConnectPtr conn;
14663
    VIR_DEBUG("vol=%p", vol);
14664

14665 14666
    virResetLastError();

14667
    if (!VIR_IS_STORAGE_VOL(vol)) {
14668
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
14669
        virDispatchError(NULL);
14670
        return NULL;
14671 14672 14673 14674
    }

    conn = vol->conn;

14675
    if (conn->storageDriver && conn->storageDriver->storageVolGetPath) {
14676
        char *ret;
14677
        ret = conn->storageDriver->storageVolGetPath(vol);
14678 14679 14680 14681
        if (!ret)
            goto error;
        return ret;
    }
14682

14683
    virReportUnsupportedError();
14684 14685

error:
14686
    virDispatchError(vol->conn);
14687 14688
    return NULL;
}
14689

14690

14691 14692 14693 14694 14695 14696 14697 14698 14699
/**
 * virStorageVolResize:
 * @vol: pointer to storage volume
 * @capacity: new capacity, in bytes
 * @flags: bitwise-OR of virStorageVolResizeFlags
 *
 * Changes the capacity of the storage volume @vol to @capacity. The
 * operation will fail if the new capacity requires allocation that would
 * exceed the remaining free space in the parent pool.  The contents of
14700 14701
 * the new capacity will appear as all zero bytes. The capacity value will
 * be rounded to the granularity supported by the hypervisor.
14702 14703 14704 14705 14706 14707 14708 14709
 *
 * Normally, the operation will attempt to affect capacity with a minimum
 * impact on allocation (that is, the default operation favors a sparse
 * resize).  If @flags contains VIR_STORAGE_VOL_RESIZE_ALLOCATE, then the
 * operation will ensure that allocation is sufficient for the new
 * capacity; this may make the operation take noticeably longer.
 *
 * Normally, the operation treats @capacity as the new size in bytes;
A
Alex Jia 已提交
14710
 * but if @flags contains VIR_STORAGE_VOL_RESIZE_DELTA, then @capacity
14711 14712 14713 14714 14715
 * represents the size difference to add to the current size.  It is
 * up to the storage pool implementation whether unaligned requests are
 * rounded up to the next valid boundary, or rejected.
 *
 * Normally, this operation should only be used to enlarge capacity;
A
Alex Jia 已提交
14716
 * but if @flags contains VIR_STORAGE_VOL_RESIZE_SHRINK, it is possible to
14717
 * attempt a reduction in capacity even though it might cause data loss.
A
Alex Jia 已提交
14718
 * If VIR_STORAGE_VOL_RESIZE_DELTA is also present, then @capacity is
E
Eric Blake 已提交
14719 14720 14721
 * subtracted from the current size; without it, @capacity represents
 * the absolute new size regardless of whether it is larger or smaller
 * than the current size.
14722 14723 14724 14725 14726
 *
 * Returns 0 on success, or -1 on error.
 */
int
virStorageVolResize(virStorageVolPtr vol,
E
Eric Blake 已提交
14727
                    unsigned long long capacity,
14728 14729 14730
                    unsigned int flags)
{
    virConnectPtr conn;
E
Eric Blake 已提交
14731
    VIR_DEBUG("vol=%p capacity=%llu flags=%x", vol, capacity, flags);
14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742

    virResetLastError();

    if (!VIR_IS_STORAGE_VOL(vol)) {
        virLibStorageVolError(VIR_ERR_INVALID_STORAGE_VOL, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = vol->conn;

14743
    virCheckReadOnlyGoto(conn->flags, error);
14744

E
Eric Blake 已提交
14745 14746 14747
    /* Zero capacity is only valid with either delta or shrink.  */
    if (capacity == 0 && !((flags & VIR_STORAGE_VOL_RESIZE_DELTA) ||
                           (flags & VIR_STORAGE_VOL_RESIZE_SHRINK))) {
14748
        virReportInvalidArg(capacity,
14749 14750
                            _("capacity in %s cannot be zero without 'delta' "
                              "or 'shrink' flags set"),
14751
                            __FUNCTION__);
14752 14753 14754
        goto error;
    }

14755
    if (conn->storageDriver && conn->storageDriver->storageVolResize) {
14756
        int ret;
14757
        ret = conn->storageDriver->storageVolResize(vol, capacity, flags);
14758 14759 14760 14761 14762
        if (ret < 0)
            goto error;
        return ret;
    }

14763
    virReportUnsupportedError();
14764 14765 14766 14767 14768

error:
    virDispatchError(vol->conn);
    return -1;
}
14769

14770

14771 14772 14773 14774
/**
 * virNodeNumOfDevices:
 * @conn: pointer to the hypervisor connection
 * @cap: capability name
14775
 * @flags: extra flags; not used yet, so callers should always pass 0
14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786
 *
 * Provides the number of node devices.
 *
 * If the optional 'cap'  argument is non-NULL, then the count
 * will be restricted to devices with the specified capability
 *
 * Returns the number of node devices or -1 in case of error
 */
int
virNodeNumOfDevices(virConnectPtr conn, const char *cap, unsigned int flags)
{
14787
    VIR_DEBUG("conn=%p, cap=%s, flags=%x", conn, NULLSTR(cap), flags);
14788

14789 14790
    virResetLastError();

14791
    virCheckConnectReturn(conn, -1);
14792

14793
    if (conn->nodeDeviceDriver && conn->nodeDeviceDriver->nodeNumOfDevices) {
14794
        int ret;
14795
        ret = conn->nodeDeviceDriver->nodeNumOfDevices(conn, cap, flags);
14796 14797 14798 14799
        if (ret < 0)
            goto error;
        return ret;
    }
14800

14801
    virReportUnsupportedError();
14802 14803

error:
14804
    virDispatchError(conn);
14805 14806 14807
    return -1;
}

14808

14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836
/**
 * virConnectListAllNodeDevices:
 * @conn: Pointer to the hypervisor connection.
 * @devices: Pointer to a variable to store the array containing the node
 *           device objects or NULL if the list is not required (just returns
 *           number of node devices).
 * @flags: bitwise-OR of virConnectListAllNodeDevices.
 *
 * Collect the list of node devices, and allocate an array to store those
 * objects.
 *
 * Normally, all node devices are returned; however, @flags can be used to
 * filter the results for a smaller list of targeted node devices.  The valid
 * flags are divided into groups, where each group contains bits that
 * describe mutually exclusive attributes of a node device, and where all bits
 * within a group describe all possible node devices.
 *
 * Only one group of the @flags is provided to filter the node devices by
 * capability type, flags include:
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_SYSTEM
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_PCI_DEV
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_USB_DEV
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_USB_INTERFACE
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_NET
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI_HOST
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI_TARGET
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_STORAGE
14837 14838
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_FC_HOST
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_VPORTS
14839
 *   VIR_CONNECT_LIST_NODE_DEVICES_CAP_SCSI_GENERIC
14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859
 *
 * Returns the number of node devices found or -1 and sets @devices to NULL in
 * case of error.  On success, the array stored into @devices is guaranteed to
 * have an extra allocated element set to NULL but not included in the return
 * count, to make iteration easier.  The caller is responsible for calling
 * virNodeDeviceFree() on each array element, then calling free() on
 * @devices.
 */
int
virConnectListAllNodeDevices(virConnectPtr conn,
                             virNodeDevicePtr **devices,
                             unsigned int flags)
{
    VIR_DEBUG("conn=%p, devices=%p, flags=%x", conn, devices, flags);

    virResetLastError();

    if (devices)
        *devices = NULL;

14860
    virCheckConnectReturn(conn, -1);
14861

14862 14863
    if (conn->nodeDeviceDriver &&
        conn->nodeDeviceDriver->connectListAllNodeDevices) {
14864
        int ret;
14865
        ret = conn->nodeDeviceDriver->connectListAllNodeDevices(conn, devices, flags);
14866 14867 14868 14869 14870
        if (ret < 0)
            goto error;
        return ret;
    }

14871
    virReportUnsupportedError();
14872 14873 14874 14875 14876

error:
    virDispatchError(conn);
    return -1;
}
14877

14878

14879 14880 14881 14882 14883 14884
/**
 * virNodeListDevices:
 * @conn: pointer to the hypervisor connection
 * @cap: capability name
 * @names: array to collect the list of node device names
 * @maxnames: size of @names
14885
 * @flags: extra flags; not used yet, so callers should always pass 0
14886 14887 14888
 *
 * Collect the list of node devices, and store their names in @names
 *
14889 14890
 * For more control over the results, see virConnectListAllNodeDevices().
 *
14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901
 * If the optional 'cap'  argument is non-NULL, then the count
 * will be restricted to devices with the specified capability
 *
 * Returns the number of node devices found or -1 in case of error
 */
int
virNodeListDevices(virConnectPtr conn,
                   const char *cap,
                   char **const names, int maxnames,
                   unsigned int flags)
{
14902
    VIR_DEBUG("conn=%p, cap=%s, names=%p, maxnames=%d, flags=%x",
14903 14904
          conn, cap, names, maxnames, flags);

14905 14906
    virResetLastError();

14907
    virCheckConnectReturn(conn, -1);
14908 14909
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
14910

14911
    if (conn->nodeDeviceDriver && conn->nodeDeviceDriver->nodeListDevices) {
14912
        int ret;
14913
        ret = conn->nodeDeviceDriver->nodeListDevices(conn, cap, names, maxnames, flags);
14914 14915 14916 14917
        if (ret < 0)
            goto error;
        return ret;
    }
14918

14919
    virReportUnsupportedError();
14920 14921

error:
14922
    virDispatchError(conn);
14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935
    return -1;
}


/**
 * virNodeDeviceLookupByName:
 * @conn: pointer to the hypervisor connection
 * @name: unique device name
 *
 * Lookup a node device by its name.
 *
 * Returns a virNodeDevicePtr if found, NULL otherwise.
 */
14936 14937
virNodeDevicePtr
virNodeDeviceLookupByName(virConnectPtr conn, const char *name)
14938
{
14939
    VIR_DEBUG("conn=%p, name=%p", conn, name);
14940

14941 14942
    virResetLastError();

14943
    virCheckConnectReturn(conn, NULL);
14944
    virCheckNonNullArgGoto(name, error);
14945

14946
    if (conn->nodeDeviceDriver && conn->nodeDeviceDriver->nodeDeviceLookupByName) {
14947
        virNodeDevicePtr ret;
14948
        ret = conn->nodeDeviceDriver->nodeDeviceLookupByName(conn, name);
14949 14950 14951 14952
        if (!ret)
            goto error;
        return ret;
    }
14953

14954
    virReportUnsupportedError();
14955 14956

error:
14957
    virDispatchError(conn);
14958 14959 14960
    return NULL;
}

14961

14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982
/**
 * virNodeDeviceLookupSCSIHostByWWN:
 * @conn: pointer to the hypervisor connection
 * @wwnn: WWNN of the SCSI Host.
 * @wwpn: WWPN of the SCSI Host.
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Lookup SCSI Host which is capable with 'fc_host' by its WWNN and WWPN.
 *
 * Returns a virNodeDevicePtr if found, NULL otherwise.
 */
virNodeDevicePtr
virNodeDeviceLookupSCSIHostByWWN(virConnectPtr conn,
                                 const char *wwnn,
                                 const char *wwpn,
                                 unsigned int flags)
{
    VIR_DEBUG("conn=%p, wwnn=%p, wwpn=%p, flags=%x", conn, wwnn, wwpn, flags);

    virResetLastError();

14983
    virCheckConnectReturn(conn, NULL);
14984 14985 14986
    virCheckNonNullArgGoto(wwnn, error);
    virCheckNonNullArgGoto(wwpn, error);

14987 14988
    if (conn->nodeDeviceDriver &&
        conn->nodeDeviceDriver->nodeDeviceLookupSCSIHostByWWN) {
14989
        virNodeDevicePtr ret;
14990
        ret = conn->nodeDeviceDriver->nodeDeviceLookupSCSIHostByWWN(conn, wwnn,
14991 14992 14993 14994 14995 14996
                                                             wwpn, flags);
        if (!ret)
            goto error;
        return ret;
    }

14997
    virReportUnsupportedError();
14998 14999 15000 15001 15002

error:
    virDispatchError(conn);
    return NULL;
}
15003

15004

15005 15006 15007
/**
 * virNodeDeviceGetXMLDesc:
 * @dev: pointer to the node device
15008
 * @flags: extra flags; not used yet, so callers should always pass 0
15009 15010 15011 15012
 *
 * Fetch an XML document describing all aspects of
 * the device.
 *
15013
 * Returns the XML document, or NULL on error
15014
 */
15015 15016
char *
virNodeDeviceGetXMLDesc(virNodeDevicePtr dev, unsigned int flags)
15017
{
E
Eric Blake 已提交
15018
    VIR_DEBUG("dev=%p, conn=%p, flags=%x", dev, dev ? dev->conn : NULL, flags);
15019

15020 15021
    virResetLastError();

15022
    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15023
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15024
        virDispatchError(NULL);
15025 15026 15027
        return NULL;
    }

15028
    if (dev->conn->nodeDeviceDriver && dev->conn->nodeDeviceDriver->nodeDeviceGetXMLDesc) {
15029
        char *ret;
15030
        ret = dev->conn->nodeDeviceDriver->nodeDeviceGetXMLDesc(dev, flags);
15031 15032 15033 15034
        if (!ret)
            goto error;
        return ret;
    }
15035

15036
    virReportUnsupportedError();
15037 15038

error:
15039
    virDispatchError(dev->conn);
15040 15041 15042 15043 15044 15045 15046 15047
    return NULL;
}


/**
 * virNodeDeviceGetName:
 * @dev: the device
 *
D
Daniel Veillard 已提交
15048 15049 15050
 * Just return the device name
 *
 * Returns the device name or NULL in case of error
15051
 */
15052 15053
const char *
virNodeDeviceGetName(virNodeDevicePtr dev)
15054
{
15055
    VIR_DEBUG("dev=%p, conn=%p", dev, dev ? dev->conn : NULL);
15056

15057 15058
    virResetLastError();

15059
    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15060
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15061
        virDispatchError(NULL);
15062 15063 15064 15065 15066 15067
        return NULL;
    }

    return dev->name;
}

15068

15069 15070 15071 15072
/**
 * virNodeDeviceGetParent:
 * @dev: the device
 *
D
Daniel Veillard 已提交
15073 15074
 * Accessor for the parent of the device
 *
15075 15076 15077
 * Returns the name of the device's parent, or NULL if the
 * device has no parent.
 */
15078 15079
const char *
virNodeDeviceGetParent(virNodeDevicePtr dev)
15080
{
15081
    VIR_DEBUG("dev=%p, conn=%p", dev, dev ? dev->conn : NULL);
15082

15083 15084
    virResetLastError();

15085
    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15086
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15087
        virDispatchError(NULL);
15088 15089 15090
        return NULL;
    }

15091
    if (!dev->parent) {
15092 15093
        if (dev->conn->nodeDeviceDriver && dev->conn->nodeDeviceDriver->nodeDeviceGetParent) {
            dev->parent = dev->conn->nodeDeviceDriver->nodeDeviceGetParent(dev);
15094
        } else {
15095
            virReportUnsupportedError();
15096
            virDispatchError(dev->conn);
15097 15098 15099 15100
            return NULL;
        }
    }
    return dev->parent;
15101 15102
}

15103

15104 15105 15106 15107
/**
 * virNodeDeviceNumOfCaps:
 * @dev: the device
 *
D
Daniel Veillard 已提交
15108 15109
 * Accessor for the number of capabilities supported by the device.
 *
15110 15111
 * Returns the number of capabilities supported by the device.
 */
15112 15113
int
virNodeDeviceNumOfCaps(virNodeDevicePtr dev)
15114
{
15115
    VIR_DEBUG("dev=%p, conn=%p", dev, dev ? dev->conn : NULL);
15116

15117 15118
    virResetLastError();

15119
    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15120
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15121
        virDispatchError(NULL);
15122 15123 15124
        return -1;
    }

15125
    if (dev->conn->nodeDeviceDriver && dev->conn->nodeDeviceDriver->nodeDeviceNumOfCaps) {
15126
        int ret;
15127
        ret = dev->conn->nodeDeviceDriver->nodeDeviceNumOfCaps(dev);
15128 15129 15130 15131
        if (ret < 0)
            goto error;
        return ret;
    }
15132

15133
    virReportUnsupportedError();
15134 15135

error:
15136
    virDispatchError(dev->conn);
15137 15138 15139
    return -1;
}

15140

15141 15142 15143 15144 15145 15146 15147 15148 15149 15150
/**
 * virNodeDeviceListCaps:
 * @dev: the device
 * @names: array to collect the list of capability names
 * @maxnames: size of @names
 *
 * Lists the names of the capabilities supported by the device.
 *
 * Returns the number of capability names listed in @names.
 */
15151 15152 15153 15154
int
virNodeDeviceListCaps(virNodeDevicePtr dev,
                      char **const names,
                      int maxnames)
15155
{
15156
    VIR_DEBUG("dev=%p, conn=%p, names=%p, maxnames=%d",
15157 15158
          dev, dev ? dev->conn : NULL, names, maxnames);

15159 15160
    virResetLastError();

15161
    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15162
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15163
        virDispatchError(NULL);
15164 15165 15166
        return -1;
    }

15167 15168
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
15169

15170
    if (dev->conn->nodeDeviceDriver && dev->conn->nodeDeviceDriver->nodeDeviceListCaps) {
15171
        int ret;
15172
        ret = dev->conn->nodeDeviceDriver->nodeDeviceListCaps(dev, names, maxnames);
15173 15174 15175 15176
        if (ret < 0)
            goto error;
        return ret;
    }
15177

15178
    virReportUnsupportedError();
15179 15180

error:
15181
    virDispatchError(dev->conn);
15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194
    return -1;
}


/**
 * virNodeDeviceFree:
 * @dev: pointer to the node device
 *
 * Drops a reference to the node device, freeing it if
 * this was the last reference.
 *
 * Returns the 0 for success, -1 for error.
 */
15195 15196
int
virNodeDeviceFree(virNodeDevicePtr dev)
15197
{
15198
    VIR_DEBUG("dev=%p, conn=%p", dev, dev ? dev->conn : NULL);
15199

15200 15201
    virResetLastError();

15202
    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15203
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15204
        virDispatchError(NULL);
15205
        return -1;
15206
    }
15207
    virObjectUnref(dev);
15208
    return 0;
15209 15210 15211
}


15212 15213
/**
 * virNodeDeviceRef:
D
Daniel Veillard 已提交
15214
 * @dev: the dev to hold a reference on
15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225
 *
 * Increment the reference count on the dev. For each
 * additional call to this method, there shall be a corresponding
 * call to virNodeDeviceFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
 * it. ie, each new thread using a dev would increment
 * the reference count.
D
Daniel Veillard 已提交
15226 15227
 *
 * Returns 0 in case of success, -1 in case of failure.
15228 15229 15230 15231
 */
int
virNodeDeviceRef(virNodeDevicePtr dev)
{
15232 15233
    VIR_DEBUG("dev=%p refs=%d", dev, dev ? dev->object.u.s.refs : 0);

15234 15235
    virResetLastError();

15236
    if ((!VIR_IS_CONNECTED_NODE_DEVICE(dev))) {
15237
        virLibConnError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15238
        virDispatchError(NULL);
15239
        return -1;
15240
    }
15241
    virObjectRef(dev);
15242 15243 15244
    return 0;
}

15245

15246
/**
D
Daniel Veillard 已提交
15247
 * virNodeDeviceDettach:
15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261
 * @dev: pointer to the node device
 *
 * Dettach the node device from the node itself so that it may be
 * assigned to a guest domain.
 *
 * Depending on the hypervisor, this may involve operations such
 * as unbinding any device drivers from the device, binding the
 * device to a dummy device driver and resetting the device.
 *
 * If the device is currently in use by the node, this method may
 * fail.
 *
 * Once the device is not assigned to any guest, it may be re-attached
 * to the node using the virNodeDeviceReattach() method.
D
Daniel Veillard 已提交
15262
 *
15263 15264 15265 15266 15267
 * If the caller needs control over which backend driver will be used
 * during PCI device assignment (to use something other than the
 * default, for example VFIO), the newer virNodeDeviceDetachFlags()
 * API should be used instead.
 *
D
Daniel Veillard 已提交
15268
 * Returns 0 in case of success, -1 in case of failure.
15269 15270 15271 15272
 */
int
virNodeDeviceDettach(virNodeDevicePtr dev)
{
15273
    VIR_DEBUG("dev=%p, conn=%p", dev, dev ? dev->conn : NULL);
15274 15275 15276 15277

    virResetLastError();

    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15278
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15279
        virDispatchError(NULL);
15280
        return -1;
15281 15282
    }

15283
    virCheckReadOnlyGoto(dev->conn->flags, error);
15284

15285 15286
    if (dev->conn->driver->nodeDeviceDettach) {
        int ret;
15287
        ret = dev->conn->driver->nodeDeviceDettach(dev);
15288 15289 15290 15291 15292
        if (ret < 0)
            goto error;
        return ret;
    }

15293
    virReportUnsupportedError();
15294 15295

error:
15296
    virDispatchError(dev->conn);
15297
    return -1;
15298 15299
}

15300

15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344
/**
 * virNodeDeviceDetachFlags:
 * @dev: pointer to the node device
 * @driverName: name of backend driver that will be used
 *              for later device assignment to a domain. NULL
 *              means "use the hypervisor default driver"
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Detach the node device from the node itself so that it may be
 * assigned to a guest domain.
 *
 * Depending on the hypervisor, this may involve operations such as
 * unbinding any device drivers from the device, binding the device to
 * a dummy device driver and resetting the device. Different backend
 * drivers expect the device to be bound to different dummy
 * devices. For example, QEMU's "kvm" backend driver (the default)
 * expects the device to be bound to "pci-stub", but its "vfio"
 * backend driver expects the device to be bound to "vfio-pci".
 *
 * If the device is currently in use by the node, this method may
 * fail.
 *
 * Once the device is not assigned to any guest, it may be re-attached
 * to the node using the virNodeDeviceReAttach() method.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virNodeDeviceDetachFlags(virNodeDevicePtr dev,
                         const char *driverName,
                         unsigned int flags)
{
    VIR_DEBUG("dev=%p, conn=%p driverName=%s flags=%x",
              dev, dev ? dev->conn : NULL,
              driverName ? driverName : "(default)", flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

15345
    virCheckReadOnlyGoto(dev->conn->flags, error);
15346 15347 15348 15349 15350 15351 15352 15353 15354

    if (dev->conn->driver->nodeDeviceDetachFlags) {
        int ret;
        ret = dev->conn->driver->nodeDeviceDetachFlags(dev, driverName, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

15355
    virReportUnsupportedError();
15356 15357 15358 15359 15360 15361

error:
    virDispatchError(dev->conn);
    return -1;
}

15362

15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374
/**
 * virNodeDeviceReAttach:
 * @dev: pointer to the node device
 *
 * Re-attach a previously dettached node device to the node so that it
 * may be used by the node again.
 *
 * Depending on the hypervisor, this may involve operations such
 * as resetting the device, unbinding it from a dummy device driver
 * and binding it to its appropriate driver.
 *
 * If the device is currently in use by a guest, this method may fail.
D
Daniel Veillard 已提交
15375 15376
 *
 * Returns 0 in case of success, -1 in case of failure.
15377 15378 15379 15380
 */
int
virNodeDeviceReAttach(virNodeDevicePtr dev)
{
15381
    VIR_DEBUG("dev=%p, conn=%p", dev, dev ? dev->conn : NULL);
15382 15383 15384 15385

    virResetLastError();

    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15386
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15387
        virDispatchError(NULL);
15388
        return -1;
15389 15390
    }

15391
    virCheckReadOnlyGoto(dev->conn->flags, error);
15392

15393 15394
    if (dev->conn->driver->nodeDeviceReAttach) {
        int ret;
15395
        ret = dev->conn->driver->nodeDeviceReAttach(dev);
15396 15397 15398 15399 15400
        if (ret < 0)
            goto error;
        return ret;
    }

15401
    virReportUnsupportedError();
15402 15403

error:
15404
    virDispatchError(dev->conn);
15405
    return -1;
15406 15407
}

15408

15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422
/**
 * virNodeDeviceReset:
 * @dev: pointer to the node device
 *
 * Reset a previously dettached node device to the node before or
 * after assigning it to a guest.
 *
 * The exact reset semantics depends on the hypervisor and device
 * type but, for example, KVM will attempt to reset PCI devices with
 * a Function Level Reset, Secondary Bus Reset or a Power Management
 * D-State reset.
 *
 * If the reset will affect other devices which are currently in use,
 * this function may fail.
D
Daniel Veillard 已提交
15423 15424
 *
 * Returns 0 in case of success, -1 in case of failure.
15425 15426 15427 15428
 */
int
virNodeDeviceReset(virNodeDevicePtr dev)
{
15429
    VIR_DEBUG("dev=%p, conn=%p", dev, dev ? dev->conn : NULL);
15430 15431 15432 15433

    virResetLastError();

    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15434
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15435
        virDispatchError(NULL);
15436
        return -1;
15437 15438
    }

15439
    virCheckReadOnlyGoto(dev->conn->flags, error);
15440

15441 15442
    if (dev->conn->driver->nodeDeviceReset) {
        int ret;
15443
        ret = dev->conn->driver->nodeDeviceReset(dev);
15444 15445 15446 15447 15448
        if (ret < 0)
            goto error;
        return ret;
    }

15449
    virReportUnsupportedError();
15450 15451

error:
15452
    virDispatchError(dev->conn);
15453
    return -1;
15454 15455
}

15456

15457 15458 15459 15460
/**
 * virNodeDeviceCreateXML:
 * @conn: pointer to the hypervisor connection
 * @xmlDesc: string containing an XML description of the device to be created
15461
 * @flags: extra flags; not used yet, so callers should always pass 0
15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472
 *
 * Create a new device on the VM host machine, for example, virtual
 * HBAs created using vport_create.
 *
 * Returns a node device object if successful, NULL in case of failure
 */
virNodeDevicePtr
virNodeDeviceCreateXML(virConnectPtr conn,
                       const char *xmlDesc,
                       unsigned int flags)
{
15473
    VIR_DEBUG("conn=%p, xmlDesc=%s, flags=%x", conn, xmlDesc, flags);
15474 15475 15476

    virResetLastError();

15477
    virCheckConnectReturn(conn, NULL);
15478
    virCheckReadOnlyGoto(conn->flags, error);
15479
    virCheckNonNullArgGoto(xmlDesc, error);
15480

15481 15482 15483
    if (conn->nodeDeviceDriver &&
        conn->nodeDeviceDriver->nodeDeviceCreateXML) {
        virNodeDevicePtr dev = conn->nodeDeviceDriver->nodeDeviceCreateXML(conn, xmlDesc, flags);
15484 15485 15486 15487 15488
        if (dev == NULL)
            goto error;
        return dev;
    }

15489
    virReportUnsupportedError();
15490 15491

error:
15492
    virDispatchError(conn);
15493 15494 15495 15496 15497 15498 15499 15500
    return NULL;
}


/**
 * virNodeDeviceDestroy:
 * @dev: a device object
 *
15501 15502 15503
 * Destroy the device object. The virtual device (only works for vHBA
 * currently) is removed from the host operating system.  This function
 * may require privileged access.
15504 15505 15506 15507 15508 15509
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virNodeDeviceDestroy(virNodeDevicePtr dev)
{
15510
    VIR_DEBUG("dev=%p", dev);
15511 15512 15513 15514

    virResetLastError();

    if (!VIR_IS_CONNECTED_NODE_DEVICE(dev)) {
15515
        virLibNodeDeviceError(VIR_ERR_INVALID_NODE_DEVICE, __FUNCTION__);
15516
        virDispatchError(NULL);
15517
        return -1;
15518 15519
    }

15520
    virCheckReadOnlyGoto(dev->conn->flags, error);
15521

15522 15523 15524
    if (dev->conn->nodeDeviceDriver &&
        dev->conn->nodeDeviceDriver->nodeDeviceDestroy) {
        int retval = dev->conn->nodeDeviceDriver->nodeDeviceDestroy(dev);
15525 15526 15527 15528 15529 15530 15531
        if (retval < 0) {
            goto error;
        }

        return 0;
    }

15532
    virReportUnsupportedError();
15533 15534

error:
15535
    virDispatchError(dev->conn);
15536 15537 15538 15539
    return -1;
}


15540 15541 15542 15543 15544 15545 15546 15547 15548
/*
 * Domain Event Notification
 */

/**
 * virConnectDomainEventRegister:
 * @conn: pointer to the connection
 * @cb: callback to the function handling domain events
 * @opaque: opaque data to pass on to the callback
D
Daniel Veillard 已提交
15549
 * @freecb: optional function to deallocate opaque when not used anymore
15550
 *
15551
 * Adds a callback to receive notifications of domain lifecycle events
E
Eric Blake 已提交
15552 15553 15554
 * occurring on a connection.  This function requires that an event loop
 * has been previously registered with virEventRegisterImpl() or
 * virEventRegisterDefaultImpl().
15555 15556
 *
 * Use of this method is no longer recommended. Instead applications
15557
 * should try virConnectDomainEventRegisterAny() which has a more flexible
E
Eric Blake 已提交
15558
 * API contract.
15559
 *
15560 15561
 * The virDomainPtr object handle passed into the callback upon delivery
 * of an event is only valid for the duration of execution of the callback.
15562 15563
 * If the callback wishes to keep the domain object after the callback returns,
 * it shall take a reference to it, by calling virDomainRef.
15564 15565 15566
 * The reference can be released once the object is no longer required
 * by calling virDomainFree.
 *
15567 15568 15569
 * Returns 0 on success, -1 on failure.  Older versions of some hypervisors
 * sometimes returned a positive number on success, but without any reliable
 * semantics on what that number represents.
15570 15571 15572 15573
 */
int
virConnectDomainEventRegister(virConnectPtr conn,
                              virConnectDomainEventCallback cb,
15574 15575
                              void *opaque,
                              virFreeCallback freecb)
15576
{
15577
    VIR_DEBUG("conn=%p, cb=%p, opaque=%p, freecb=%p", conn, cb, opaque, freecb);
15578
    virResetLastError();
15579

15580
    virCheckConnectReturn(conn, -1);
15581
    virCheckNonNullArgGoto(cb, error);
15582

15583
    if (conn->driver && conn->driver->connectDomainEventRegister) {
15584
        int ret;
15585
        ret = conn->driver->connectDomainEventRegister(conn, cb, opaque, freecb);
15586 15587 15588 15589 15590
        if (ret < 0)
            goto error;
        return ret;
    }

15591
    virReportUnsupportedError();
15592
error:
15593
    virDispatchError(conn);
15594 15595 15596
    return -1;
}

15597

15598 15599 15600 15601 15602
/**
 * virConnectDomainEventDeregister:
 * @conn: pointer to the connection
 * @cb: callback to the function handling domain events
 *
15603 15604
 * Removes a callback previously registered with the
 * virConnectDomainEventRegister() function.
15605 15606
 *
 * Use of this method is no longer recommended. Instead applications
15607
 * should try virConnectDomainEventDeregisterAny() which has a more flexible
15608
 * API contract
15609
 *
15610 15611 15612
 * Returns 0 on success, -1 on failure.  Older versions of some hypervisors
 * sometimes returned a positive number on success, but without any reliable
 * semantics on what that number represents.
15613 15614 15615 15616 15617
 */
int
virConnectDomainEventDeregister(virConnectPtr conn,
                                virConnectDomainEventCallback cb)
{
15618
    VIR_DEBUG("conn=%p, cb=%p", conn, cb);
15619 15620

    virResetLastError();
15621

15622
    virCheckConnectReturn(conn, -1);
15623 15624
    virCheckNonNullArgGoto(cb, error);

15625
    if (conn->driver && conn->driver->connectDomainEventDeregister) {
15626
        int ret;
15627
        ret = conn->driver->connectDomainEventDeregister(conn, cb);
15628 15629 15630
        if (ret < 0)
            goto error;
        return ret;
15631 15632
    }

15633
    virReportUnsupportedError();
15634
error:
15635
    virDispatchError(conn);
15636 15637
    return -1;
}
15638

15639

15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652
/**
 * virSecretGetConnect:
 * @secret: A virSecret secret
 *
 * Provides the connection pointer associated with a secret.  The reference
 * counter on the connection is not increased by this call.
 *
 * WARNING: When writing libvirt bindings in other languages, do not use this
 * function.  Instead, store the connection and the secret object together.
 *
 * Returns the virConnectPtr or NULL in case of failure.
 */
virConnectPtr
15653
virSecretGetConnect(virSecretPtr secret)
15654
{
15655
    VIR_DEBUG("secret=%p", secret);
15656 15657 15658

    virResetLastError();

15659
    if (!VIR_IS_CONNECTED_SECRET(secret)) {
15660
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
15661
        virDispatchError(NULL);
15662 15663 15664 15665 15666
        return NULL;
    }
    return secret->conn;
}

15667

15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682
/**
 * virConnectNumOfSecrets:
 * @conn: virConnect connection
 *
 * Fetch number of currently defined secrets.
 *
 * Returns the number currently defined secrets.
 */
int
virConnectNumOfSecrets(virConnectPtr conn)
{
    VIR_DEBUG("conn=%p", conn);

    virResetLastError();

15683
    virCheckConnectReturn(conn, -1);
15684 15685

    if (conn->secretDriver != NULL &&
15686
        conn->secretDriver->connectNumOfSecrets != NULL) {
15687 15688
        int ret;

15689
        ret = conn->secretDriver->connectNumOfSecrets(conn);
15690 15691 15692 15693 15694
        if (ret < 0)
            goto error;
        return ret;
    }

15695
    virReportUnsupportedError();
15696 15697

error:
15698
    virDispatchError(conn);
15699 15700 15701
    return -1;
}

15702

15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747
/**
 * virConnectListAllSecrets:
 * @conn: Pointer to the hypervisor connection.
 * @secrets: Pointer to a variable to store the array containing the secret
 *           objects or NULL if the list is not required (just returns the
 *           number of secrets).
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Collect the list of secrets, and allocate an array to store those
 * objects.
 *
 * Normally, all secrets are returned; however, @flags can be used to
 * filter the results for a smaller list of targeted secrets. The valid
 * flags are divided into groups, where each group contains bits that
 * describe mutually exclusive attributes of a secret, and where all bits
 * within a group describe all possible secrets.
 *
 * The first group of @flags is used to filter secrets by its storage
 * location. Flag VIR_CONNECT_LIST_SECRETS_EPHEMERAL selects secrets that
 * are kept only in memory. Flag VIR_CONNECT_LIST_SECRETS_NO_EPHEMERAL
 * selects secrets that are kept in persistent storage.
 *
 * The second group of @flags is used to filter secrets by privacy. Flag
 * VIR_CONNECT_LIST_SECRETS_PRIVATE seclets secrets that are never revealed
 * to any caller of libvirt nor to any other node. Flag
 * VIR_CONNECT_LIST_SECRETS_NO_PRIVATE selects non-private secrets.
 *
 * Returns the number of secrets found or -1 and sets @secrets to NULL in case
 * of error.  On success, the array stored into @secrets is guaranteed to
 * have an extra allocated element set to NULL but not included in the return count,
 * to make iteration easier.  The caller is responsible for calling
 * virSecretFree() on each array element, then calling free() on @secrets.
 */
int
virConnectListAllSecrets(virConnectPtr conn,
                         virSecretPtr **secrets,
                         unsigned int flags)
{
    VIR_DEBUG("conn=%p, secrets=%p, flags=%x", conn, secrets, flags);

    virResetLastError();

    if (secrets)
        *secrets = NULL;

15748
    virCheckConnectReturn(conn, -1);
15749 15750

    if (conn->secretDriver &&
15751
        conn->secretDriver->connectListAllSecrets) {
15752
        int ret;
15753
        ret = conn->secretDriver->connectListAllSecrets(conn, secrets, flags);
15754 15755 15756 15757 15758
        if (ret < 0)
            goto error;
        return ret;
    }

15759
    virReportUnsupportedError();
15760 15761 15762 15763 15764 15765

error:
    virDispatchError(conn);
    return -1;
}

15766

15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783
/**
 * virConnectListSecrets:
 * @conn: virConnect connection
 * @uuids: Pointer to an array to store the UUIDs
 * @maxuuids: size of the array.
 *
 * List UUIDs of defined secrets, store pointers to names in uuids.
 *
 * Returns the number of UUIDs provided in the array, or -1 on failure.
 */
int
virConnectListSecrets(virConnectPtr conn, char **uuids, int maxuuids)
{
    VIR_DEBUG("conn=%p, uuids=%p, maxuuids=%d", conn, uuids, maxuuids);

    virResetLastError();

15784
    virCheckConnectReturn(conn, -1);
15785 15786
    virCheckNonNullArgGoto(uuids, error);
    virCheckNonNegativeArgGoto(maxuuids, error);
15787

15788
    if (conn->secretDriver != NULL && conn->secretDriver->connectListSecrets != NULL) {
15789 15790
        int ret;

15791
        ret = conn->secretDriver->connectListSecrets(conn, uuids, maxuuids);
15792 15793 15794 15795 15796
        if (ret < 0)
            goto error;
        return ret;
    }

15797
    virReportUnsupportedError();
15798 15799

error:
15800
    virDispatchError(conn);
15801 15802 15803
    return -1;
}

15804

15805
/**
15806 15807 15808
 * virSecretLookupByUUID:
 * @conn: pointer to the hypervisor connection
 * @uuid: the raw UUID for the secret
15809
 *
15810 15811
 * Try to lookup a secret on the given hypervisor based on its UUID.
 * Uses the 16 bytes of raw data to describe the UUID
15812
 *
15813 15814
 * Returns a new secret object or NULL in case of failure.  If the
 * secret cannot be found, then VIR_ERR_NO_SECRET error is raised.
15815 15816
 */
virSecretPtr
15817
virSecretLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
15818
{
15819
    VIR_UUID_DEBUG(conn, uuid);
15820 15821 15822

    virResetLastError();

15823
    virCheckConnectReturn(conn, NULL);
15824
    virCheckNonNullArgGoto(uuid, error);
15825

15826
    if (conn->secretDriver &&
15827
        conn->secretDriver->secretLookupByUUID) {
15828
        virSecretPtr ret;
15829
        ret = conn->secretDriver->secretLookupByUUID(conn, uuid);
15830
        if (!ret)
15831 15832 15833 15834
            goto error;
        return ret;
    }

15835
    virReportUnsupportedError();
15836 15837

error:
15838
    virDispatchError(conn);
15839 15840 15841
    return NULL;
}

15842

15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857
/**
 * virSecretLookupByUUIDString:
 * @conn: pointer to the hypervisor connection
 * @uuidstr: the string UUID for the secret
 *
 * Try to lookup a secret on the given hypervisor based on its UUID.
 * Uses the printable string value to describe the UUID
 *
 * Returns a new secret object or NULL in case of failure.  If the
 * secret cannot be found, then VIR_ERR_NO_SECRET error is raised.
 */
virSecretPtr
virSecretLookupByUUIDString(virConnectPtr conn, const char *uuidstr)
{
    unsigned char uuid[VIR_UUID_BUFLEN];
15858
    VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr));
15859 15860 15861

    virResetLastError();

15862
    virCheckConnectReturn(conn, NULL);
15863
    virCheckNonNullArgGoto(uuidstr, error);
15864 15865

    if (virUUIDParse(uuidstr, uuid) < 0) {
15866 15867 15868
        virReportInvalidArg(uuidstr,
                            _("uuidstr in %s must be a valid UUID"),
                            __FUNCTION__);
15869 15870 15871 15872 15873 15874
        goto error;
    }

    return virSecretLookupByUUID(conn, &uuid[0]);

error:
15875
    virDispatchError(conn);
15876 15877 15878 15879
    return NULL;
}


15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897
/**
 * virSecretLookupByUsage:
 * @conn: pointer to the hypervisor connection
 * @usageType: the type of secret usage
 * @usageID: identifier of the object using the secret
 *
 * Try to lookup a secret on the given hypervisor based on its usage
 * The usageID is unique within the set of secrets sharing the
 * same usageType value.
 *
 * Returns a new secret object or NULL in case of failure.  If the
 * secret cannot be found, then VIR_ERR_NO_SECRET error is raised.
 */
virSecretPtr
virSecretLookupByUsage(virConnectPtr conn,
                       int usageType,
                       const char *usageID)
{
15898
    VIR_DEBUG("conn=%p, usageType=%d usageID=%s", conn, usageType, NULLSTR(usageID));
15899 15900 15901

    virResetLastError();

15902
    virCheckConnectReturn(conn, NULL);
15903
    virCheckNonNullArgGoto(usageID, error);
15904 15905

    if (conn->secretDriver &&
15906
        conn->secretDriver->secretLookupByUsage) {
15907
        virSecretPtr ret;
15908
        ret = conn->secretDriver->secretLookupByUsage(conn, usageType, usageID);
15909 15910 15911 15912 15913
        if (!ret)
            goto error;
        return ret;
    }

15914
    virReportUnsupportedError();
15915 15916

error:
15917
    virDispatchError(conn);
15918 15919 15920 15921
    return NULL;
}


15922 15923 15924 15925
/**
 * virSecretDefineXML:
 * @conn: virConnect connection
 * @xml: XML describing the secret.
15926
 * @flags: extra flags; not used yet, so callers should always pass 0
15927
 *
D
Dan Kenigsberg 已提交
15928
 * If XML specifies a UUID, locates the specified secret and replaces all
15929 15930 15931 15932 15933 15934
 * attributes of the secret specified by UUID by attributes specified in xml
 * (any attributes not specified in xml are discarded).
 *
 * Otherwise, creates a new secret with an automatically chosen UUID, and
 * initializes its attributes from xml.
 *
W
Wang Yufei 已提交
15935
 * Returns a secret on success, NULL on failure.
15936 15937 15938 15939
 */
virSecretPtr
virSecretDefineXML(virConnectPtr conn, const char *xml, unsigned int flags)
{
15940
    VIR_DEBUG("conn=%p, xml=%s, flags=%x", conn, xml, flags);
15941 15942 15943

    virResetLastError();

15944
    virCheckConnectReturn(conn, NULL);
15945
    virCheckReadOnlyGoto(conn->flags, error);
15946
    virCheckNonNullArgGoto(xml, error);
15947

15948
    if (conn->secretDriver != NULL && conn->secretDriver->secretDefineXML != NULL) {
15949 15950
        virSecretPtr ret;

15951
        ret = conn->secretDriver->secretDefineXML(conn, xml, flags);
15952 15953 15954 15955 15956
        if (ret == NULL)
            goto error;
        return ret;
    }

15957
    virReportUnsupportedError();
15958 15959

error:
15960
    virDispatchError(conn);
15961 15962 15963
    return NULL;
}

15964

15965
/**
15966
 * virSecretGetUUID:
15967
 * @secret: A virSecret secret
15968
 * @uuid: buffer of VIR_UUID_BUFLEN bytes in size
15969 15970 15971
 *
 * Fetches the UUID of the secret.
 *
15972 15973
 * Returns 0 on success with the uuid buffer being filled, or
 * -1 upon failure.
15974
 */
15975 15976
int
virSecretGetUUID(virSecretPtr secret, unsigned char *uuid)
15977 15978 15979 15980 15981 15982
{
    VIR_DEBUG("secret=%p", secret);

    virResetLastError();

    if (!VIR_IS_CONNECTED_SECRET(secret)) {
15983
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
15984
        virDispatchError(NULL);
15985 15986
        return -1;
    }
15987
    virCheckNonNullArgGoto(uuid, error);
15988

15989 15990 15991
    memcpy(uuid, &secret->uuid[0], VIR_UUID_BUFLEN);

    return 0;
15992 15993 15994 15995

error:
    virDispatchError(secret->conn);
    return -1;
15996 15997
}

15998

15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011
/**
 * virSecretGetUUIDString:
 * @secret: a secret object
 * @buf: pointer to a VIR_UUID_STRING_BUFLEN bytes array
 *
 * Get the UUID for a secret as string. For more information about
 * UUID see RFC4122.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virSecretGetUUIDString(virSecretPtr secret, char *buf)
{
16012
    VIR_DEBUG("secret=%p, buf=%p", secret, buf);
16013 16014

    virResetLastError();
16015

16016
    if (!VIR_IS_SECRET(secret)) {
16017
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16018
        virDispatchError(NULL);
16019
        return -1;
16020
    }
16021
    virCheckNonNullArgGoto(buf, error);
16022

E
Eric Blake 已提交
16023
    virUUIDFormat(secret->uuid, buf);
16024
    return 0;
16025 16026

error:
16027
    virDispatchError(secret->conn);
16028
    return -1;
16029 16030
}

16031

16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047
/**
 * virSecretGetUsageType:
 * @secret: a secret object
 *
 * Get the type of object which uses this secret. The returned
 * value is one of the constants defined in the virSecretUsageType
 * enumeration. More values may be added to this enumeration in
 * the future, so callers should expect to see usage types they
 * do not explicitly know about.
 *
 * Returns a positive integer identifying the type of object,
 * or -1 upon error.
 */
int
virSecretGetUsageType(virSecretPtr secret)
{
16048
    VIR_DEBUG("secret=%p", secret);
16049 16050 16051 16052

    virResetLastError();

    if (!VIR_IS_SECRET(secret)) {
16053
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16054
        virDispatchError(NULL);
16055
        return -1;
16056
    }
16057
    return secret->usageType;
16058 16059
}

16060

16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079
/**
 * virSecretGetUsageID:
 * @secret: a secret object
 *
 * Get the unique identifier of the object with which this
 * secret is to be used. The format of the identifier is
 * dependant on the usage type of the secret. For a secret
 * with a usage type of VIR_SECRET_USAGE_TYPE_VOLUME the
 * identifier will be a fully qualfied path name. The
 * identifiers are intended to be unique within the set of
 * all secrets sharing the same usage type. ie, there shall
 * only ever be one secret for each volume path.
 *
 * Returns a string identifying the object using the secret,
 * or NULL upon error
 */
const char *
virSecretGetUsageID(virSecretPtr secret)
{
16080
    VIR_DEBUG("secret=%p", secret);
16081 16082 16083 16084

    virResetLastError();

    if (!VIR_IS_SECRET(secret)) {
16085
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16086
        virDispatchError(NULL);
16087
        return NULL;
16088
    }
16089
    return secret->usageID;
16090 16091
}

16092

16093 16094 16095
/**
 * virSecretGetXMLDesc:
 * @secret: A virSecret secret
16096
 * @flags: extra flags; not used yet, so callers should always pass 0
16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107
 *
 * Fetches an XML document describing attributes of the secret.
 *
 * Returns the XML document on success, NULL on failure.  The caller must
 * free() the XML.
 */
char *
virSecretGetXMLDesc(virSecretPtr secret, unsigned int flags)
{
    virConnectPtr conn;

16108
    VIR_DEBUG("secret=%p, flags=%x", secret, flags);
16109 16110 16111 16112

    virResetLastError();

    if (!VIR_IS_CONNECTED_SECRET(secret)) {
16113
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16114
        virDispatchError(NULL);
16115 16116 16117 16118
        return NULL;
    }

    conn = secret->conn;
16119
    if (conn->secretDriver != NULL && conn->secretDriver->secretGetXMLDesc != NULL) {
16120 16121
        char *ret;

16122
        ret = conn->secretDriver->secretGetXMLDesc(secret, flags);
16123 16124 16125 16126 16127
        if (ret == NULL)
            goto error;
        return ret;
    }

16128
    virReportUnsupportedError();
16129 16130

error:
16131
    virDispatchError(conn);
16132 16133 16134
    return NULL;
}

16135

16136 16137 16138 16139 16140
/**
 * virSecretSetValue:
 * @secret: A virSecret secret
 * @value: Value of the secret
 * @value_size: Size of the value
16141
 * @flags: extra flags; not used yet, so callers should always pass 0
16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152
 *
 * Sets the value of a secret.
 *
 * Returns 0 on success, -1 on failure.
 */
int
virSecretSetValue(virSecretPtr secret, const unsigned char *value,
                  size_t value_size, unsigned int flags)
{
    virConnectPtr conn;

16153
    VIR_DEBUG("secret=%p, value=%p, value_size=%zu, flags=%x", secret, value,
16154 16155 16156 16157 16158
              value_size, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_SECRET(secret)) {
16159
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16160
        virDispatchError(NULL);
16161 16162 16163
        return -1;
    }
    conn = secret->conn;
16164
    virCheckReadOnlyGoto(conn->flags, error);
16165
    virCheckNonNullArgGoto(value, error);
16166

16167
    if (conn->secretDriver != NULL && conn->secretDriver->secretSetValue != NULL) {
16168 16169
        int ret;

16170
        ret = conn->secretDriver->secretSetValue(secret, value, value_size, flags);
16171 16172 16173 16174 16175
        if (ret < 0)
            goto error;
        return ret;
    }

16176
    virReportUnsupportedError();
16177 16178

error:
16179
    virDispatchError(conn);
16180 16181 16182
    return -1;
}

16183

16184 16185 16186 16187
/**
 * virSecretGetValue:
 * @secret: A virSecret connection
 * @value_size: Place for storing size of the secret value
16188
 * @flags: extra flags; not used yet, so callers should always pass 0
16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199
 *
 * Fetches the value of a secret.
 *
 * Returns the secret value on success, NULL on failure.  The caller must
 * free() the secret value.
 */
unsigned char *
virSecretGetValue(virSecretPtr secret, size_t *value_size, unsigned int flags)
{
    virConnectPtr conn;

16200
    VIR_DEBUG("secret=%p, value_size=%p, flags=%x", secret, value_size, flags);
16201 16202 16203 16204

    virResetLastError();

    if (!VIR_IS_CONNECTED_SECRET(secret)) {
16205
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16206
        virDispatchError(NULL);
16207 16208 16209
        return NULL;
    }
    conn = secret->conn;
16210
    virCheckReadOnlyGoto(conn->flags, error);
16211
    virCheckNonNullArgGoto(value_size, error);
16212

16213
    if (conn->secretDriver != NULL && conn->secretDriver->secretGetValue != NULL) {
16214 16215
        unsigned char *ret;

16216
        ret = conn->secretDriver->secretGetValue(secret, value_size, flags, 0);
16217 16218 16219 16220 16221
        if (ret == NULL)
            goto error;
        return ret;
    }

16222
    virReportUnsupportedError();
16223 16224

error:
16225
    virDispatchError(conn);
16226 16227 16228
    return NULL;
}

16229

16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248
/**
 * virSecretUndefine:
 * @secret: A virSecret secret
 *
 * Deletes the specified secret.  This does not free the associated
 * virSecretPtr object.
 *
 * Returns 0 on success, -1 on failure.
 */
int
virSecretUndefine(virSecretPtr secret)
{
    virConnectPtr conn;

    VIR_DEBUG("secret=%p", secret);

    virResetLastError();

    if (!VIR_IS_CONNECTED_SECRET(secret)) {
16249
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16250
        virDispatchError(NULL);
16251 16252 16253
        return -1;
    }
    conn = secret->conn;
16254
    virCheckReadOnlyGoto(conn->flags, error);
16255

16256
    if (conn->secretDriver != NULL && conn->secretDriver->secretUndefine != NULL) {
16257 16258
        int ret;

16259
        ret = conn->secretDriver->secretUndefine(secret);
16260 16261 16262 16263 16264
        if (ret < 0)
            goto error;
        return ret;
    }

16265
    virReportUnsupportedError();
16266 16267

error:
16268
    virDispatchError(conn);
16269 16270 16271
    return -1;
}

16272

16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291
/**
 * virSecretRef:
 * @secret: the secret to hold a reference on
 *
 * Increment the reference count on the secret. For each additional call to
 * this method, there shall be a corresponding call to virSecretFree to release
 * the reference count, once the caller no longer needs the reference to this
 * object.
 *
 * This method is typically useful for applications where multiple threads are
 * using a connection, and it is required that the connection remain open until
 * all threads have finished using it. ie, each new thread using a secret would
 * increment the reference count.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virSecretRef(virSecretPtr secret)
{
16292 16293 16294
    VIR_DEBUG("secret=%p refs=%d", secret,
              secret ? secret->object.u.s.refs : 0);

16295 16296
    virResetLastError();

16297
    if (!VIR_IS_CONNECTED_SECRET(secret)) {
16298
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16299
        virDispatchError(NULL);
16300 16301
        return -1;
    }
16302
    virObjectRef(secret);
16303 16304 16305
    return 0;
}

16306

16307 16308 16309 16310 16311 16312
/**
 * virSecretFree:
 * @secret: pointer to a secret
 *
 * Release the secret handle. The underlying secret continues to exist.
 *
16313
 * Returns 0 on success, or -1 on error
16314 16315 16316 16317
 */
int
virSecretFree(virSecretPtr secret)
{
16318
    VIR_DEBUG("secret=%p", secret);
16319 16320 16321 16322

    virResetLastError();

    if (!VIR_IS_CONNECTED_SECRET(secret)) {
16323
        virLibSecretError(VIR_ERR_INVALID_SECRET, __FUNCTION__);
16324
        virDispatchError(NULL);
16325 16326
        return -1;
    }
16327
    virObjectUnref(secret);
16328 16329
    return 0;
}
16330 16331 16332 16333 16334


/**
 * virStreamNew:
 * @conn: pointer to the connection
16335
 * @flags: bitwise-OR of virStreamFlags
16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356
 *
 * Creates a new stream object which can be used to perform
 * streamed I/O with other public API function.
 *
 * When no longer needed, a stream object must be released
 * with virStreamFree. If a data stream has been used,
 * then the application must call virStreamFinish or
 * virStreamAbort before free'ing to, in order to notify
 * the driver of termination.
 *
 * If a non-blocking data stream is required passed
 * VIR_STREAM_NONBLOCK for flags, otherwise pass 0.
 *
 * Returns the new stream, or NULL upon error
 */
virStreamPtr
virStreamNew(virConnectPtr conn,
             unsigned int flags)
{
    virStreamPtr st;

16357
    VIR_DEBUG("conn=%p, flags=%x", conn, flags);
16358 16359 16360

    virResetLastError();

16361
    virCheckConnectReturn(conn, NULL);
16362 16363 16364 16365

    st = virGetStream(conn);
    if (st)
        st->flags = flags;
16366 16367
    else
        virDispatchError(conn);
16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386

    return st;
}


/**
 * virStreamRef:
 * @stream: pointer to the stream
 *
 * Increment the reference count on the stream. For each
 * additional call to this method, there shall be a corresponding
 * call to virStreamFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * Returns 0 in case of success, -1 in case of failure
 */
int
virStreamRef(virStreamPtr stream)
{
16387 16388 16389
    VIR_DEBUG("stream=%p refs=%d", stream,
              stream ? stream->object.u.s.refs : 0);

16390 16391
    virResetLastError();

16392
    if ((!VIR_IS_CONNECTED_STREAM(stream))) {
16393
        virLibConnError(VIR_ERR_INVALID_STREAM, __FUNCTION__);
16394
        virDispatchError(NULL);
16395
        return -1;
16396
    }
16397
    virObjectRef(stream);
16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410
    return 0;
}


/**
 * virStreamSend:
 * @stream: pointer to the stream object
 * @data: buffer to write to stream
 * @nbytes: size of @data buffer
 *
 * Write a series of bytes to the stream. This method may
 * block the calling application for an arbitrary amount
 * of time. Once an application has finished sending data
16411
 * it should call virStreamFinish to wait for successful
16412
 * confirmation from the driver, or detect any error.
16413 16414
 *
 * This method may not be used if a stream source has been
16415
 * registered.
16416 16417 16418 16419 16420
 *
 * Errors are not guaranteed to be reported synchronously
 * with the call, but may instead be delayed until a
 * subsequent call.
 *
D
Dan Kenigsberg 已提交
16421
 * An example using this with a hypothetical file upload
16422 16423
 * API looks like
 *
16424
 *     virStreamPtr st = virStreamNew(conn, 0);
E
Eric Blake 已提交
16425
 *     int fd = open("demo.iso", O_RDONLY);
16426 16427 16428 16429 16430 16431 16432
 *
 *     virConnectUploadFile(conn, "demo.iso", st);
 *
 *     while (1) {
 *          char buf[1024];
 *          int got = read(fd, buf, 1024);
 *          if (got < 0) {
16433
 *             virStreamAbort(st);
16434 16435 16436 16437 16438
 *             break;
 *          }
 *          if (got == 0) {
 *             virStreamFinish(st);
 *             break;
16439
 *          }
16440 16441
 *          int offset = 0;
 *          while (offset < got) {
E
Eric Blake 已提交
16442
 *             int sent = virStreamSend(st, buf+offset, got-offset);
16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454
 *             if (sent < 0) {
 *                virStreamAbort(st);
 *                goto done;
 *             }
 *             offset += sent;
 *          }
 *      }
 *      if (virStreamFinish(st) < 0)
 *         ... report an error ....
 *    done:
 *      virStreamFree(st);
 *      close(fd);
16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465
 *
 * Returns the number of bytes written, which may be less
 * than requested.
 *
 * Returns -1 upon error, at which time the stream will
 * be marked as aborted, and the caller should now release
 * the stream with virStreamFree.
 *
 * Returns -2 if the outgoing transmit buffers are full &
 * the stream is marked as non-blocking.
 */
16466 16467 16468 16469
int
virStreamSend(virStreamPtr stream,
              const char *data,
              size_t nbytes)
16470
{
16471
    VIR_DEBUG("stream=%p, data=%p, nbytes=%zi", stream, data, nbytes);
16472 16473 16474 16475

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16476
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16477
        virDispatchError(NULL);
16478
        return -1;
16479 16480
    }

16481
    virCheckNonNullArgGoto(data, error);
16482

16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493
    if (stream->driver &&
        stream->driver->streamSend) {
        int ret;
        ret = (stream->driver->streamSend)(stream, data, nbytes);
        if (ret == -2)
            return -2;
        if (ret < 0)
            goto error;
        return ret;
    }

16494
    virReportUnsupportedError();
16495 16496

error:
16497
    virDispatchError(stream->conn);
16498 16499 16500 16501 16502 16503 16504
    return -1;
}


/**
 * virStreamRecv:
 * @stream: pointer to the stream object
16505
 * @data: buffer to read into from stream
16506 16507
 * @nbytes: size of @data buffer
 *
16508
 * Reads a series of bytes from the stream. This method may
16509 16510 16511 16512 16513 16514 16515
 * block the calling application for an arbitrary amount
 * of time.
 *
 * Errors are not guaranteed to be reported synchronously
 * with the call, but may instead be delayed until a
 * subsequent call.
 *
D
Dan Kenigsberg 已提交
16516
 * An example using this with a hypothetical file download
16517 16518
 * API looks like
 *
16519
 *     virStreamPtr st = virStreamNew(conn, 0);
E
Eric Blake 已提交
16520
 *     int fd = open("demo.iso", O_WRONLY, 0600);
16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534
 *
 *     virConnectDownloadFile(conn, "demo.iso", st);
 *
 *     while (1) {
 *         char buf[1024];
 *         int got = virStreamRecv(st, buf, 1024);
 *         if (got < 0)
 *            break;
 *         if (got == 0) {
 *            virStreamFinish(st);
 *            break;
 *         }
 *         int offset = 0;
 *         while (offset < got) {
E
Eric Blake 已提交
16535
 *            int sent = write(fd, buf + offset, got - offset);
16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547
 *            if (sent < 0) {
 *               virStreamAbort(st);
 *               goto done;
 *            }
 *            offset += sent;
 *         }
 *     }
 *     if (virStreamFinish(st) < 0)
 *        ... report an error ....
 *   done:
 *     virStreamFree(st);
 *     close(fd);
16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563
 *
 *
 * Returns the number of bytes read, which may be less
 * than requested.
 *
 * Returns 0 when the end of the stream is reached, at
 * which time the caller should invoke virStreamFinish()
 * to get confirmation of stream completion.
 *
 * Returns -1 upon error, at which time the stream will
 * be marked as aborted, and the caller should now release
 * the stream with virStreamFree.
 *
 * Returns -2 if there is no data pending to be read & the
 * stream is marked as non-blocking.
 */
16564 16565 16566 16567
int
virStreamRecv(virStreamPtr stream,
              char *data,
              size_t nbytes)
16568
{
16569
    VIR_DEBUG("stream=%p, data=%p, nbytes=%zi", stream, data, nbytes);
16570 16571 16572 16573

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16574
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16575
        virDispatchError(NULL);
16576
        return -1;
16577 16578
    }

16579
    virCheckNonNullArgGoto(data, error);
16580

16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591
    if (stream->driver &&
        stream->driver->streamRecv) {
        int ret;
        ret = (stream->driver->streamRecv)(stream, data, nbytes);
        if (ret == -2)
            return -2;
        if (ret < 0)
            goto error;
        return ret;
    }

16592
    virReportUnsupportedError();
16593 16594

error:
16595
    virDispatchError(stream->conn);
16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609
    return -1;
}


/**
 * virStreamSendAll:
 * @stream: pointer to the stream object
 * @handler: source callback for reading data from application
 * @opaque: application defined data
 *
 * Send the entire data stream, reading the data from the
 * requested data source. This is simply a convenient alternative
 * to virStreamSend, for apps that do blocking-I/o.
 *
D
Dan Kenigsberg 已提交
16610
 * An example using this with a hypothetical file upload
16611 16612 16613 16614 16615 16616 16617 16618 16619
 * API looks like
 *
 *   int mysource(virStreamPtr st, char *buf, int nbytes, void *opaque) {
 *       int *fd = opaque;
 *
 *       return read(*fd, buf, nbytes);
 *   }
 *
 *   virStreamPtr st = virStreamNew(conn, 0);
E
Eric Blake 已提交
16620
 *   int fd = open("demo.iso", O_RDONLY);
16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631
 *
 *   virConnectUploadFile(conn, st);
 *   if (virStreamSendAll(st, mysource, &fd) < 0) {
 *      ...report an error ...
 *      goto done;
 *   }
 *   if (virStreamFinish(st) < 0)
 *      ...report an error...
 *   virStreamFree(st);
 *   close(fd);
 *
16632
 * Returns 0 if all the data was successfully sent. The caller
16633 16634 16635 16636 16637 16638 16639
 * should invoke virStreamFinish(st) to flush the stream upon
 * success and then virStreamFree
 *
 * Returns -1 upon any error, with virStreamAbort() already
 * having been called,  so the caller need only call
 * virStreamFree()
 */
16640 16641 16642 16643
int
virStreamSendAll(virStreamPtr stream,
                 virStreamSourceFunc handler,
                 void *opaque)
16644 16645 16646 16647
{
    char *bytes = NULL;
    int want = 1024*64;
    int ret = -1;
16648
    VIR_DEBUG("stream=%p, handler=%p, opaque=%p", stream, handler, opaque);
16649 16650 16651 16652

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16653
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16654
        virDispatchError(NULL);
16655
        return -1;
16656 16657
    }

16658
    virCheckNonNullArgGoto(handler, cleanup);
16659

16660
    if (stream->flags & VIR_STREAM_NONBLOCK) {
16661
        virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
16662 16663 16664 16665
                        _("data sources cannot be used for non-blocking streams"));
        goto cleanup;
    }

16666
    if (VIR_ALLOC_N(bytes, want) < 0)
16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691
        goto cleanup;

    for (;;) {
        int got, offset = 0;
        got = (handler)(stream, bytes, want, opaque);
        if (got < 0) {
            virStreamAbort(stream);
            goto cleanup;
        }
        if (got == 0)
            break;
        while (offset < got) {
            int done;
            done = virStreamSend(stream, bytes + offset, got - offset);
            if (done < 0)
                goto cleanup;
            offset += done;
        }
    }
    ret = 0;

cleanup:
    VIR_FREE(bytes);

    if (ret != 0)
16692
        virDispatchError(stream->conn);
16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707

    return ret;
}


/**
 * virStreamRecvAll:
 * @stream: pointer to the stream object
 * @handler: sink callback for writing data to application
 * @opaque: application defined data
 *
 * Receive the entire data stream, sending the data to the
 * requested data sink. This is simply a convenient alternative
 * to virStreamRecv, for apps that do blocking-I/o.
 *
D
Dan Kenigsberg 已提交
16708
 * An example using this with a hypothetical file download
16709 16710 16711 16712 16713 16714 16715 16716 16717
 * API looks like
 *
 *   int mysink(virStreamPtr st, const char *buf, int nbytes, void *opaque) {
 *       int *fd = opaque;
 *
 *       return write(*fd, buf, nbytes);
 *   }
 *
 *   virStreamPtr st = virStreamNew(conn, 0);
E
Eric Blake 已提交
16718
 *   int fd = open("demo.iso", O_WRONLY);
16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729
 *
 *   virConnectUploadFile(conn, st);
 *   if (virStreamRecvAll(st, mysink, &fd) < 0) {
 *      ...report an error ...
 *      goto done;
 *   }
 *   if (virStreamFinish(st) < 0)
 *      ...report an error...
 *   virStreamFree(st);
 *   close(fd);
 *
16730
 * Returns 0 if all the data was successfully received. The caller
16731 16732 16733 16734 16735 16736 16737
 * should invoke virStreamFinish(st) to flush the stream upon
 * success and then virStreamFree
 *
 * Returns -1 upon any error, with virStreamAbort() already
 * having been called,  so the caller need only call
 * virStreamFree()
 */
16738 16739 16740 16741
int
virStreamRecvAll(virStreamPtr stream,
                 virStreamSinkFunc handler,
                 void *opaque)
16742 16743 16744 16745
{
    char *bytes = NULL;
    int want = 1024*64;
    int ret = -1;
16746
    VIR_DEBUG("stream=%p, handler=%p, opaque=%p", stream, handler, opaque);
16747 16748 16749 16750

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16751
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16752
        virDispatchError(NULL);
16753
        return -1;
16754 16755
    }

16756
    virCheckNonNullArgGoto(handler, cleanup);
16757

16758
    if (stream->flags & VIR_STREAM_NONBLOCK) {
16759
        virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
16760 16761 16762 16763 16764
                        _("data sinks cannot be used for non-blocking streams"));
        goto cleanup;
    }


16765
    if (VIR_ALLOC_N(bytes, want) < 0)
16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790
        goto cleanup;

    for (;;) {
        int got, offset = 0;
        got = virStreamRecv(stream, bytes, want);
        if (got < 0)
            goto cleanup;
        if (got == 0)
            break;
        while (offset < got) {
            int done;
            done = (handler)(stream, bytes + offset, got - offset, opaque);
            if (done < 0) {
                virStreamAbort(stream);
                goto cleanup;
            }
            offset += done;
        }
    }
    ret = 0;

cleanup:
    VIR_FREE(bytes);

    if (ret != 0)
16791
        virDispatchError(stream->conn);
16792 16793 16794 16795 16796 16797

    return ret;
}


/**
M
Matthias Bolte 已提交
16798
 * virStreamEventAddCallback:
16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811
 * @stream: pointer to the stream object
 * @events: set of events to monitor
 * @cb: callback to invoke when an event occurs
 * @opaque: application defined data
 * @ff: callback to free @opaque data
 *
 * Register a callback to be notified when a stream
 * becomes writable, or readable. This is most commonly
 * used in conjunction with non-blocking data streams
 * to integrate into an event loop
 *
 * Returns 0 on success, -1 upon error
 */
16812 16813 16814 16815 16816 16817
int
virStreamEventAddCallback(virStreamPtr stream,
                          int events,
                          virStreamEventCallback cb,
                          void *opaque,
                          virFreeCallback ff)
16818
{
16819 16820
    VIR_DEBUG("stream=%p, events=%d, cb=%p, opaque=%p, ff=%p",
              stream, events, cb, opaque, ff);
16821 16822 16823 16824

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16825
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16826
        virDispatchError(NULL);
16827
        return -1;
16828 16829 16830
    }

    if (stream->driver &&
16831
        stream->driver->streamEventAddCallback) {
16832
        int ret;
16833
        ret = (stream->driver->streamEventAddCallback)(stream, events, cb, opaque, ff);
16834 16835 16836 16837 16838
        if (ret < 0)
            goto error;
        return ret;
    }

16839
    virReportUnsupportedError();
16840 16841

error:
16842
    virDispatchError(stream->conn);
16843 16844 16845 16846 16847
    return -1;
}


/**
M
Matthias Bolte 已提交
16848
 * virStreamEventUpdateCallback:
16849 16850 16851 16852 16853 16854
 * @stream: pointer to the stream object
 * @events: set of events to monitor
 *
 * Changes the set of events to monitor for a stream. This allows
 * for event notification to be changed without having to
 * unregister & register the callback completely. This method
E
Eric Blake 已提交
16855
 * is guaranteed to succeed if a callback is already registered
16856 16857 16858
 *
 * Returns 0 on success, -1 if no callback is registered
 */
16859 16860 16861
int
virStreamEventUpdateCallback(virStreamPtr stream,
                             int events)
16862
{
16863
    VIR_DEBUG("stream=%p, events=%d", stream, events);
16864 16865 16866 16867

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16868
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16869
        virDispatchError(NULL);
16870
        return -1;
16871 16872 16873
    }

    if (stream->driver &&
16874
        stream->driver->streamEventUpdateCallback) {
16875
        int ret;
16876
        ret = (stream->driver->streamEventUpdateCallback)(stream, events);
16877 16878 16879 16880 16881
        if (ret < 0)
            goto error;
        return ret;
    }

16882
    virReportUnsupportedError();
16883 16884

error:
16885
    virDispatchError(stream->conn);
16886 16887 16888
    return -1;
}

16889

16890
/**
M
Matthias Bolte 已提交
16891
 * virStreamEventRemoveCallback:
16892 16893
 * @stream: pointer to the stream object
 *
D
Dan Kenigsberg 已提交
16894
 * Remove an event callback from the stream
16895 16896 16897
 *
 * Returns 0 on success, -1 on error
 */
16898 16899
int
virStreamEventRemoveCallback(virStreamPtr stream)
16900
{
16901
    VIR_DEBUG("stream=%p", stream);
16902 16903 16904 16905

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16906
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16907
        virDispatchError(NULL);
16908
        return -1;
16909 16910 16911
    }

    if (stream->driver &&
16912
        stream->driver->streamEventRemoveCallback) {
16913
        int ret;
16914
        ret = (stream->driver->streamEventRemoveCallback)(stream);
16915 16916 16917 16918 16919
        if (ret < 0)
            goto error;
        return ret;
    }

16920
    virReportUnsupportedError();
16921 16922

error:
16923
    virDispatchError(stream->conn);
16924 16925 16926
    return -1;
}

16927

16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942
/**
 * virStreamFinish:
 * @stream: pointer to the stream object
 *
 * Indicate that there is no further data is to be transmitted
 * on the stream. For output streams this should be called once
 * all data has been written. For input streams this should be
 * called once virStreamRecv returns end-of-file.
 *
 * This method is a synchronization point for all asynchronous
 * errors, so if this returns a success code the application can
 * be sure that all data has been successfully processed.
 *
 * Returns 0 on success, -1 upon error
 */
16943 16944
int
virStreamFinish(virStreamPtr stream)
16945
{
16946
    VIR_DEBUG("stream=%p", stream);
16947 16948 16949 16950

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16951
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16952
        virDispatchError(NULL);
16953
        return -1;
16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964
    }

    if (stream->driver &&
        stream->driver->streamFinish) {
        int ret;
        ret = (stream->driver->streamFinish)(stream);
        if (ret < 0)
            goto error;
        return ret;
    }

16965
    virReportUnsupportedError();
16966 16967

error:
16968
    virDispatchError(stream->conn);
16969 16970 16971
    return -1;
}

16972

16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985
/**
 * virStreamAbort:
 * @stream: pointer to the stream object
 *
 * Request that the in progress data transfer be cancelled
 * abnormally before the end of the stream has been reached.
 * For output streams this can be used to inform the driver
 * that the stream is being terminated early. For input
 * streams this can be used to inform the driver that it
 * should stop sending data.
 *
 * Returns 0 on success, -1 upon error
 */
16986 16987
int
virStreamAbort(virStreamPtr stream)
16988
{
16989
    VIR_DEBUG("stream=%p", stream);
16990 16991 16992 16993

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
16994
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
16995
        virDispatchError(NULL);
16996
        return -1;
16997 16998
    }

16999 17000 17001 17002 17003 17004
    if (!stream->driver) {
        VIR_DEBUG("aborting unused stream");
        return 0;
    }

    if (stream->driver->streamAbort) {
17005 17006 17007 17008 17009 17010 17011
        int ret;
        ret = (stream->driver->streamAbort)(stream);
        if (ret < 0)
            goto error;
        return ret;
    }

17012
    virReportUnsupportedError();
17013 17014

error:
17015
    virDispatchError(stream->conn);
17016 17017 17018
    return -1;
}

17019

17020 17021 17022 17023 17024 17025 17026
/**
 * virStreamFree:
 * @stream: pointer to the stream object
 *
 * Decrement the reference count on a stream, releasing
 * the stream object if the reference count has hit zero.
 *
D
Dan Kenigsberg 已提交
17027
 * There must not be an active data transfer in progress
17028 17029 17030 17031 17032 17033
 * when releasing the stream. If a stream needs to be
 * disposed of prior to end of stream being reached, then
 * the virStreamAbort function should be called first.
 *
 * Returns 0 upon success, or -1 on error
 */
17034 17035
int
virStreamFree(virStreamPtr stream)
17036
{
17037
    VIR_DEBUG("stream=%p", stream);
17038 17039 17040 17041

    virResetLastError();

    if (!VIR_IS_CONNECTED_STREAM(stream)) {
17042
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17043
        virDispatchError(NULL);
17044
        return -1;
17045 17046 17047 17048
    }

    /* XXX Enforce shutdown before free'ing resources ? */

17049
    virObjectUnref(stream);
17050
    return 0;
17051
}
17052 17053 17054 17055 17056 17057 17058 17059 17060 17061


/**
 * virDomainIsActive:
 * @dom: pointer to the domain object
 *
 * Determine if the domain is currently running
 *
 * Returns 1 if running, 0 if inactive, -1 on error
 */
17062 17063
int
virDomainIsActive(virDomainPtr dom)
17064
{
17065
    VIR_DEBUG("dom=%p", dom);
17066 17067 17068 17069

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
17070
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17071
        virDispatchError(NULL);
17072
        return -1;
17073 17074 17075 17076 17077 17078 17079 17080 17081
    }
    if (dom->conn->driver->domainIsActive) {
        int ret;
        ret = dom->conn->driver->domainIsActive(dom);
        if (ret < 0)
            goto error;
        return ret;
    }

17082
    virReportUnsupportedError();
17083
error:
17084
    virDispatchError(dom->conn);
17085 17086 17087
    return -1;
}

17088

17089 17090 17091 17092 17093 17094 17095 17096 17097
/**
 * virDomainIsPersistent:
 * @dom: pointer to the domain object
 *
 * Determine if the domain has a persistent configuration
 * which means it will still exist after shutting down
 *
 * Returns 1 if persistent, 0 if transient, -1 on error
 */
17098 17099
int
virDomainIsPersistent(virDomainPtr dom)
17100
{
17101
    VIR_DOMAIN_DEBUG(dom);
17102 17103 17104 17105

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
17106
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17107
        virDispatchError(NULL);
17108
        return -1;
17109 17110 17111 17112 17113 17114 17115 17116 17117
    }
    if (dom->conn->driver->domainIsPersistent) {
        int ret;
        ret = dom->conn->driver->domainIsPersistent(dom);
        if (ret < 0)
            goto error;
        return ret;
    }

17118
    virReportUnsupportedError();
17119
error:
17120
    virDispatchError(dom->conn);
17121 17122 17123
    return -1;
}

17124

17125 17126 17127 17128 17129 17130 17131 17132
/**
 * virDomainIsUpdated:
 * @dom: pointer to the domain object
 *
 * Determine if the domain has been updated.
 *
 * Returns 1 if updated, 0 if not, -1 on error
 */
17133 17134
int
virDomainIsUpdated(virDomainPtr dom)
17135
{
17136
    VIR_DOMAIN_DEBUG(dom);
17137 17138 17139 17140

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
17141
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17142
        virDispatchError(NULL);
17143
        return -1;
17144 17145 17146 17147 17148 17149 17150 17151 17152
    }
    if (dom->conn->driver->domainIsUpdated) {
        int ret;
        ret = dom->conn->driver->domainIsUpdated(dom);
        if (ret < 0)
            goto error;
        return ret;
    }

17153
    virReportUnsupportedError();
17154 17155 17156 17157 17158
error:
    virDispatchError(dom->conn);
    return -1;
}

17159

17160 17161 17162 17163 17164 17165 17166 17167
/**
 * virNetworkIsActive:
 * @net: pointer to the network object
 *
 * Determine if the network is currently running
 *
 * Returns 1 if running, 0 if inactive, -1 on error
 */
17168 17169
int
virNetworkIsActive(virNetworkPtr net)
17170
{
17171
    VIR_DEBUG("net=%p", net);
17172 17173 17174 17175

    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(net)) {
17176
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17177
        virDispatchError(NULL);
17178
        return -1;
17179 17180 17181 17182 17183 17184 17185 17186 17187
    }
    if (net->conn->networkDriver->networkIsActive) {
        int ret;
        ret = net->conn->networkDriver->networkIsActive(net);
        if (ret < 0)
            goto error;
        return ret;
    }

17188
    virReportUnsupportedError();
17189
error:
17190
    virDispatchError(net->conn);
17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203
    return -1;
}


/**
 * virNetworkIsPersistent:
 * @net: pointer to the network object
 *
 * Determine if the network has a persistent configuration
 * which means it will still exist after shutting down
 *
 * Returns 1 if persistent, 0 if transient, -1 on error
 */
17204 17205
int
virNetworkIsPersistent(virNetworkPtr net)
17206
{
17207
    VIR_DEBUG("net=%p", net);
17208 17209 17210 17211

    virResetLastError();

    if (!VIR_IS_CONNECTED_NETWORK(net)) {
17212
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17213
        virDispatchError(NULL);
17214
        return -1;
17215 17216 17217 17218 17219 17220 17221 17222 17223
    }
    if (net->conn->networkDriver->networkIsPersistent) {
        int ret;
        ret = net->conn->networkDriver->networkIsPersistent(net);
        if (ret < 0)
            goto error;
        return ret;
    }

17224
    virReportUnsupportedError();
17225
error:
17226
    virDispatchError(net->conn);
17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238
    return -1;
}


/**
 * virStoragePoolIsActive:
 * @pool: pointer to the storage pool object
 *
 * Determine if the storage pool is currently running
 *
 * Returns 1 if running, 0 if inactive, -1 on error
 */
17239 17240
int
virStoragePoolIsActive(virStoragePoolPtr pool)
17241
{
17242
    VIR_DEBUG("pool=%p", pool);
17243 17244 17245 17246

    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
17247
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17248
        virDispatchError(NULL);
17249
        return -1;
17250
    }
17251
    if (pool->conn->storageDriver->storagePoolIsActive) {
17252
        int ret;
17253
        ret = pool->conn->storageDriver->storagePoolIsActive(pool);
17254 17255 17256 17257 17258
        if (ret < 0)
            goto error;
        return ret;
    }

17259
    virReportUnsupportedError();
17260
error:
17261
    virDispatchError(pool->conn);
17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274
    return -1;
}


/**
 * virStoragePoolIsPersistent:
 * @pool: pointer to the storage pool object
 *
 * Determine if the storage pool has a persistent configuration
 * which means it will still exist after shutting down
 *
 * Returns 1 if persistent, 0 if transient, -1 on error
 */
17275 17276
int
virStoragePoolIsPersistent(virStoragePoolPtr pool)
17277
{
17278
    VIR_DEBUG("pool=%p", pool);
17279 17280 17281 17282

    virResetLastError();

    if (!VIR_IS_CONNECTED_STORAGE_POOL(pool)) {
17283
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17284
        virDispatchError(NULL);
17285
        return -1;
17286
    }
17287
    if (pool->conn->storageDriver->storagePoolIsPersistent) {
17288
        int ret;
17289
        ret = pool->conn->storageDriver->storagePoolIsPersistent(pool);
17290 17291 17292 17293 17294
        if (ret < 0)
            goto error;
        return ret;
    }

17295
    virReportUnsupportedError();
17296
error:
17297
    virDispatchError(pool->conn);
17298 17299 17300 17301
    return -1;
}


S
Stefan Berger 已提交
17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312
/**
 * virConnectNumOfNWFilters:
 * @conn: pointer to the hypervisor connection
 *
 * Provides the number of nwfilters.
 *
 * Returns the number of nwfilters found or -1 in case of error
 */
int
virConnectNumOfNWFilters(virConnectPtr conn)
{
17313
    VIR_DEBUG("conn=%p", conn);
S
Stefan Berger 已提交
17314 17315 17316

    virResetLastError();

17317
    virCheckConnectReturn(conn, -1);
S
Stefan Berger 已提交
17318

17319
    if (conn->nwfilterDriver && conn->nwfilterDriver->connectNumOfNWFilters) {
S
Stefan Berger 已提交
17320
        int ret;
17321
        ret = conn->nwfilterDriver->connectNumOfNWFilters(conn);
S
Stefan Berger 已提交
17322 17323 17324 17325 17326
        if (ret < 0)
            goto error;
        return ret;
    }

17327
    virReportUnsupportedError();
S
Stefan Berger 已提交
17328 17329 17330 17331 17332 17333

error:
    virDispatchError(conn);
    return -1;
}

17334

17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363
/**
 * virConnectListAllNWFilters:
 * @conn: Pointer to the hypervisor connection.
 * @filters: Pointer to a variable to store the array containing the network
 *           filter objects or NULL if the list is not required (just returns
 *           number of network filters).
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Collect the list of network filters, and allocate an array to store those
 * objects.
 *
 * Returns the number of network filters found or -1 and sets @filters to  NULL
 * in case of error.  On success, the array stored into @filters is guaranteed to
 * have an extra allocated element set to NULL but not included in the return count,
 * to make iteration easier.  The caller is responsible for calling
 * virNWFilterFree() on each array element, then calling free() on @filters.
 */
int
virConnectListAllNWFilters(virConnectPtr conn,
                           virNWFilterPtr **filters,
                           unsigned int flags)
{
    VIR_DEBUG("conn=%p, filters=%p, flags=%x", conn, filters, flags);

    virResetLastError();

    if (filters)
        *filters = NULL;

17364
    virCheckConnectReturn(conn, -1);
17365 17366

    if (conn->nwfilterDriver &&
17367
        conn->nwfilterDriver->connectListAllNWFilters) {
17368
        int ret;
17369
        ret = conn->nwfilterDriver->connectListAllNWFilters(conn, filters, flags);
17370 17371 17372 17373 17374
        if (ret < 0)
            goto error;
        return ret;
    }

17375
    virReportUnsupportedError();
17376 17377 17378 17379 17380

error:
    virDispatchError(conn);
    return -1;
}
S
Stefan Berger 已提交
17381

17382

S
Stefan Berger 已提交
17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395
/**
 * virConnectListNWFilters:
 * @conn: pointer to the hypervisor connection
 * @names: array to collect the list of names of network filters
 * @maxnames: size of @names
 *
 * Collect the list of network filters, and store their names in @names
 *
 * Returns the number of network filters found or -1 in case of error
 */
int
virConnectListNWFilters(virConnectPtr conn, char **const names, int maxnames)
{
17396
    VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
S
Stefan Berger 已提交
17397 17398 17399

    virResetLastError();

17400
    virCheckConnectReturn(conn, -1);
17401 17402
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(maxnames, error);
S
Stefan Berger 已提交
17403

17404
    if (conn->nwfilterDriver && conn->nwfilterDriver->connectListNWFilters) {
S
Stefan Berger 已提交
17405
        int ret;
17406
        ret = conn->nwfilterDriver->connectListNWFilters(conn, names, maxnames);
S
Stefan Berger 已提交
17407 17408 17409 17410 17411
        if (ret < 0)
            goto error;
        return ret;
    }

17412
    virReportUnsupportedError();
S
Stefan Berger 已提交
17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432

error:
    virDispatchError(conn);
    return -1;
}


/**
 * virNWFilterLookupByName:
 * @conn: pointer to the hypervisor connection
 * @name: name for the network filter
 *
 * Try to lookup a network filter on the given hypervisor based on its name.
 *
 * Returns a new nwfilter object or NULL in case of failure.  If the
 * network filter cannot be found, then VIR_ERR_NO_NWFILTER error is raised.
 */
virNWFilterPtr
virNWFilterLookupByName(virConnectPtr conn, const char *name)
{
17433
    VIR_DEBUG("conn=%p, name=%s", conn, name);
S
Stefan Berger 已提交
17434 17435 17436

    virResetLastError();

17437
    virCheckConnectReturn(conn, NULL);
17438
    virCheckNonNullArgGoto(name, error);
S
Stefan Berger 已提交
17439 17440 17441

    if (conn->nwfilterDriver && conn->nwfilterDriver->nwfilterLookupByName) {
        virNWFilterPtr ret;
17442
        ret = conn->nwfilterDriver->nwfilterLookupByName(conn, name);
S
Stefan Berger 已提交
17443 17444 17445 17446 17447
        if (!ret)
            goto error;
        return ret;
    }

17448
    virReportUnsupportedError();
S
Stefan Berger 已提交
17449 17450 17451 17452 17453 17454

error:
    virDispatchError(conn);
    return NULL;
}

17455

S
Stefan Berger 已提交
17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468
/**
 * virNWFilterLookupByUUID:
 * @conn: pointer to the hypervisor connection
 * @uuid: the raw UUID for the network filter
 *
 * Try to lookup a network filter on the given hypervisor based on its UUID.
 *
 * Returns a new nwfilter object or NULL in case of failure.  If the
 * nwfdilter cannot be found, then VIR_ERR_NO_NWFILTER error is raised.
 */
virNWFilterPtr
virNWFilterLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
17469
    VIR_UUID_DEBUG(conn, uuid);
S
Stefan Berger 已提交
17470 17471 17472

    virResetLastError();

17473
    virCheckConnectReturn(conn, NULL);
17474
    virCheckNonNullArgGoto(uuid, error);
S
Stefan Berger 已提交
17475 17476 17477

    if (conn->nwfilterDriver && conn->nwfilterDriver->nwfilterLookupByUUID){
        virNWFilterPtr ret;
17478
        ret = conn->nwfilterDriver->nwfilterLookupByUUID(conn, uuid);
S
Stefan Berger 已提交
17479 17480 17481 17482 17483
        if (!ret)
            goto error;
        return ret;
    }

17484
    virReportUnsupportedError();
S
Stefan Berger 已提交
17485 17486 17487 17488 17489 17490

error:
    virDispatchError(conn);
    return NULL;
}

17491

S
Stefan Berger 已提交
17492
/**
17493
 * virNWFilterLookupByUUIDString:
S
Stefan Berger 已提交
17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505
 * @conn: pointer to the hypervisor connection
 * @uuidstr: the string UUID for the nwfilter
 *
 * Try to lookup an nwfilter on the given hypervisor based on its UUID.
 *
 * Returns a new nwfilter object or NULL in case of failure.  If the
 * nwfilter cannot be found, then VIR_ERR_NO_NWFILTER error is raised.
 */
virNWFilterPtr
virNWFilterLookupByUUIDString(virConnectPtr conn, const char *uuidstr)
{
    unsigned char uuid[VIR_UUID_BUFLEN];
17506
    VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr));
S
Stefan Berger 已提交
17507 17508 17509

    virResetLastError();

17510
    virCheckConnectReturn(conn, NULL);
17511
    virCheckNonNullArgGoto(uuidstr, error);
S
Stefan Berger 已提交
17512 17513

    if (virUUIDParse(uuidstr, uuid) < 0) {
17514 17515 17516
        virReportInvalidArg(uuidstr,
                            _("uuidstr in %s must be a valid UUID"),
                            __FUNCTION__);
S
Stefan Berger 已提交
17517 17518 17519 17520 17521 17522 17523 17524 17525 17526
        goto error;
    }

    return virNWFilterLookupByUUID(conn, &uuid[0]);

error:
    virDispatchError(conn);
    return NULL;
}

17527

S
Stefan Berger 已提交
17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539
/**
 * virNWFilterFree:
 * @nwfilter: a nwfilter object
 *
 * Free the nwfilter object. The running instance is kept alive.
 * The data structure is freed and should not be used thereafter.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virNWFilterFree(virNWFilterPtr nwfilter)
{
17540
    VIR_DEBUG("nwfilter=%p", nwfilter);
S
Stefan Berger 已提交
17541 17542 17543 17544

    virResetLastError();

    if (!VIR_IS_CONNECTED_NWFILTER(nwfilter)) {
17545
        virLibNWFilterError(VIR_ERR_INVALID_NWFILTER, __FUNCTION__);
S
Stefan Berger 已提交
17546 17547 17548
        virDispatchError(NULL);
        return -1;
    }
17549 17550

    virObjectUnref(nwfilter);
S
Stefan Berger 已提交
17551 17552 17553
    return 0;
}

17554

S
Stefan Berger 已提交
17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566
/**
 * virNWFilterGetName:
 * @nwfilter: a nwfilter object
 *
 * Get the public name for the network filter
 *
 * Returns a pointer to the name or NULL, the string need not be deallocated
 * its lifetime will be the same as the nwfilter object.
 */
const char *
virNWFilterGetName(virNWFilterPtr nwfilter)
{
17567
    VIR_DEBUG("nwfilter=%p", nwfilter);
S
Stefan Berger 已提交
17568 17569 17570 17571

    virResetLastError();

    if (!VIR_IS_NWFILTER(nwfilter)) {
17572
        virLibNWFilterError(VIR_ERR_INVALID_NWFILTER, __FUNCTION__);
S
Stefan Berger 已提交
17573
        virDispatchError(NULL);
17574
        return NULL;
S
Stefan Berger 已提交
17575
    }
17576
    return nwfilter->name;
S
Stefan Berger 已提交
17577 17578
}

17579

S
Stefan Berger 已提交
17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591
/**
 * virNWFilterGetUUID:
 * @nwfilter: a nwfilter object
 * @uuid: pointer to a VIR_UUID_BUFLEN bytes array
 *
 * Get the UUID for a network filter
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virNWFilterGetUUID(virNWFilterPtr nwfilter, unsigned char *uuid)
{
17592
    VIR_DEBUG("nwfilter=%p, uuid=%p", nwfilter, uuid);
S
Stefan Berger 已提交
17593 17594 17595 17596

    virResetLastError();

    if (!VIR_IS_NWFILTER(nwfilter)) {
17597
        virLibNWFilterError(VIR_ERR_INVALID_NWFILTER, __FUNCTION__);
S
Stefan Berger 已提交
17598 17599 17600
        virDispatchError(NULL);
        return -1;
    }
17601
    virCheckNonNullArgGoto(uuid, error);
S
Stefan Berger 已提交
17602 17603 17604 17605 17606 17607 17608 17609 17610 17611

    memcpy(uuid, &nwfilter->uuid[0], VIR_UUID_BUFLEN);

    return 0;

error:
    virDispatchError(nwfilter->conn);
    return -1;
}

17612

S
Stefan Berger 已提交
17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625
/**
 * virNWFilterGetUUIDString:
 * @nwfilter: a nwfilter object
 * @buf: pointer to a VIR_UUID_STRING_BUFLEN bytes array
 *
 * Get the UUID for a network filter as string. For more information about
 * UUID see RFC4122.
 *
 * Returns -1 in case of error, 0 in case of success
 */
int
virNWFilterGetUUIDString(virNWFilterPtr nwfilter, char *buf)
{
17626
    VIR_DEBUG("nwfilter=%p, buf=%p", nwfilter, buf);
S
Stefan Berger 已提交
17627 17628 17629 17630

    virResetLastError();

    if (!VIR_IS_NWFILTER(nwfilter)) {
17631
        virLibNWFilterError(VIR_ERR_INVALID_NWFILTER, __FUNCTION__);
S
Stefan Berger 已提交
17632 17633 17634
        virDispatchError(NULL);
        return -1;
    }
17635
    virCheckNonNullArgGoto(buf, error);
S
Stefan Berger 已提交
17636

E
Eric Blake 已提交
17637
    virUUIDFormat(nwfilter->uuid, buf);
S
Stefan Berger 已提交
17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658
    return 0;

error:
    virDispatchError(nwfilter->conn);
    return -1;
}


/**
 * virNWFilterDefineXML:
 * @conn: pointer to the hypervisor connection
 * @xmlDesc: an XML description of the nwfilter
 *
 * Define a new network filter, based on an XML description
 * similar to the one returned by virNWFilterGetXMLDesc()
 *
 * Returns a new nwfilter object or NULL in case of failure
 */
virNWFilterPtr
virNWFilterDefineXML(virConnectPtr conn, const char *xmlDesc)
{
17659
    VIR_DEBUG("conn=%p, xmlDesc=%s", conn, xmlDesc);
S
Stefan Berger 已提交
17660 17661 17662

    virResetLastError();

17663
    virCheckConnectReturn(conn, NULL);
17664
    virCheckNonNullArgGoto(xmlDesc, error);
17665
    virCheckReadOnlyGoto(conn->flags, error);
S
Stefan Berger 已提交
17666

17667
    if (conn->nwfilterDriver && conn->nwfilterDriver->nwfilterDefineXML) {
S
Stefan Berger 已提交
17668
        virNWFilterPtr ret;
17669
        ret = conn->nwfilterDriver->nwfilterDefineXML(conn, xmlDesc);
S
Stefan Berger 已提交
17670 17671 17672 17673 17674
        if (!ret)
            goto error;
        return ret;
    }

17675
    virReportUnsupportedError();
S
Stefan Berger 已提交
17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696

error:
    virDispatchError(conn);
    return NULL;
}


/**
 * virNWFilterUndefine:
 * @nwfilter: a nwfilter object
 *
 * Undefine the nwfilter object. This call will not succeed if
 * a running VM is referencing the filter. This does not free the
 * associated virNWFilterPtr object.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virNWFilterUndefine(virNWFilterPtr nwfilter)
{
    virConnectPtr conn;
17697
    VIR_DEBUG("nwfilter=%p", nwfilter);
S
Stefan Berger 已提交
17698 17699 17700 17701

    virResetLastError();

    if (!VIR_IS_CONNECTED_NWFILTER(nwfilter)) {
17702
        virLibNWFilterError(VIR_ERR_INVALID_NWFILTER, __FUNCTION__);
S
Stefan Berger 已提交
17703 17704 17705 17706 17707
        virDispatchError(NULL);
        return -1;
    }

    conn = nwfilter->conn;
17708
    virCheckReadOnlyGoto(conn->flags, error);
S
Stefan Berger 已提交
17709

17710
    if (conn->nwfilterDriver && conn->nwfilterDriver->nwfilterUndefine) {
S
Stefan Berger 已提交
17711
        int ret;
17712
        ret = conn->nwfilterDriver->nwfilterUndefine(nwfilter);
S
Stefan Berger 已提交
17713 17714 17715 17716 17717
        if (ret < 0)
            goto error;
        return ret;
    }

17718
    virReportUnsupportedError();
S
Stefan Berger 已提交
17719 17720 17721 17722 17723 17724 17725 17726 17727 17728

error:
    virDispatchError(nwfilter->conn);
    return -1;
}


/**
 * virNWFilterGetXMLDesc:
 * @nwfilter: a nwfilter object
17729
 * @flags: extra flags; not used yet, so callers should always pass 0
S
Stefan Berger 已提交
17730 17731 17732 17733 17734 17735 17736 17737
 *
 * Provide an XML description of the network filter. The description may be
 * reused later to redefine the network filter with virNWFilterCreateXML().
 *
 * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
17738
virNWFilterGetXMLDesc(virNWFilterPtr nwfilter, unsigned int flags)
S
Stefan Berger 已提交
17739 17740
{
    virConnectPtr conn;
17741
    VIR_DEBUG("nwfilter=%p, flags=%x", nwfilter, flags);
S
Stefan Berger 已提交
17742 17743 17744 17745

    virResetLastError();

    if (!VIR_IS_CONNECTED_NWFILTER(nwfilter)) {
17746
        virLibNWFilterError(VIR_ERR_INVALID_NWFILTER, __FUNCTION__);
S
Stefan Berger 已提交
17747
        virDispatchError(NULL);
17748
        return NULL;
S
Stefan Berger 已提交
17749 17750 17751 17752
    }

    conn = nwfilter->conn;

17753
    if (conn->nwfilterDriver && conn->nwfilterDriver->nwfilterGetXMLDesc) {
S
Stefan Berger 已提交
17754
        char *ret;
17755
        ret = conn->nwfilterDriver->nwfilterGetXMLDesc(nwfilter, flags);
S
Stefan Berger 已提交
17756 17757 17758 17759 17760
        if (!ret)
            goto error;
        return ret;
    }

17761
    virReportUnsupportedError();
S
Stefan Berger 已提交
17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788

error:
    virDispatchError(nwfilter->conn);
    return NULL;
}


/**
 * virNWFilterRef:
 * @nwfilter: the nwfilter to hold a reference on
 *
 * Increment the reference count on the nwfilter. For each
 * additional call to this method, there shall be a corresponding
 * call to virNWFilterFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection remain open until all threads have finished using
 * it. ie, each new thread using an nwfilter would increment
 * the reference count.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
virNWFilterRef(virNWFilterPtr nwfilter)
{
17789 17790 17791
    VIR_DEBUG("nwfilter=%p refs=%d", nwfilter,
              nwfilter ? nwfilter->object.u.s.refs : 0);

17792 17793
    virResetLastError();

S
Stefan Berger 已提交
17794
    if ((!VIR_IS_CONNECTED_NWFILTER(nwfilter))) {
17795
        virLibConnError(VIR_ERR_INVALID_NWFILTER, __FUNCTION__);
S
Stefan Berger 已提交
17796 17797 17798
        virDispatchError(NULL);
        return -1;
    }
17799
    virObjectRef(nwfilter);
S
Stefan Berger 已提交
17800 17801 17802 17803
    return 0;
}


17804 17805 17806 17807 17808 17809 17810 17811
/**
 * virInterfaceIsActive:
 * @iface: pointer to the interface object
 *
 * Determine if the interface is currently running
 *
 * Returns 1 if running, 0 if inactive, -1 on error
 */
17812 17813
int
virInterfaceIsActive(virInterfacePtr iface)
17814
{
17815
    VIR_DEBUG("iface=%p", iface);
17816 17817 17818 17819

    virResetLastError();

    if (!VIR_IS_CONNECTED_INTERFACE(iface)) {
17820
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
17821
        virDispatchError(NULL);
17822
        return -1;
17823 17824 17825 17826 17827 17828 17829 17830 17831
    }
    if (iface->conn->interfaceDriver->interfaceIsActive) {
        int ret;
        ret = iface->conn->interfaceDriver->interfaceIsActive(iface);
        if (ret < 0)
            goto error;
        return ret;
    }

17832
    virReportUnsupportedError();
17833
error:
17834
    virDispatchError(iface->conn);
17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846
    return -1;
}


/**
 * virConnectIsEncrypted:
 * @conn: pointer to the connection object
 *
 * Determine if the connection to the hypervisor is encrypted
 *
 * Returns 1 if encrypted, 0 if not encrypted, -1 on error
 */
17847 17848
int
virConnectIsEncrypted(virConnectPtr conn)
17849
{
17850
    VIR_DEBUG("conn=%p", conn);
17851 17852 17853

    virResetLastError();

17854
    virCheckConnectReturn(conn, -1);
17855
    if (conn->driver->connectIsEncrypted) {
17856
        int ret;
17857
        ret = conn->driver->connectIsEncrypted(conn);
17858 17859 17860 17861 17862
        if (ret < 0)
            goto error;
        return ret;
    }

17863
    virReportUnsupportedError();
17864
error:
17865
    virDispatchError(conn);
17866 17867 17868
    return -1;
}

17869

17870 17871 17872 17873 17874 17875 17876 17877 17878 17879
/**
 * virConnectIsSecure:
 * @conn: pointer to the connection object
 *
 * Determine if the connection to the hypervisor is secure
 *
 * A connection will be classed as secure if it is either
 * encrypted, or running over a channel which is not exposed
 * to eavesdropping (eg a UNIX domain socket, or pipe)
 *
C
Claudio Bley 已提交
17880
 * Returns 1 if secure, 0 if not secure, -1 on error
17881
 */
17882 17883
int
virConnectIsSecure(virConnectPtr conn)
17884
{
17885
    VIR_DEBUG("conn=%p", conn);
17886 17887 17888

    virResetLastError();

17889
    virCheckConnectReturn(conn, -1);
17890
    if (conn->driver->connectIsSecure) {
17891
        int ret;
17892
        ret = conn->driver->connectIsSecure(conn);
17893 17894 17895 17896 17897
        if (ret < 0)
            goto error;
        return ret;
    }

17898
    virReportUnsupportedError();
17899
error:
17900
    virDispatchError(conn);
17901 17902
    return -1;
}
J
Jiri Denemark 已提交
17903 17904 17905 17906 17907


/**
 * virConnectCompareCPU:
 * @conn: virConnect connection
17908
 * @xmlDesc: XML describing the CPU to compare with host CPU
17909
 * @flags: extra flags; not used yet, so callers should always pass 0
17910 17911
 *
 * Compares the given CPU description with the host CPU
J
Jiri Denemark 已提交
17912 17913 17914 17915 17916 17917 17918 17919
 *
 * Returns comparison result according to enum virCPUCompareResult
 */
int
virConnectCompareCPU(virConnectPtr conn,
                     const char *xmlDesc,
                     unsigned int flags)
{
17920
    VIR_DEBUG("conn=%p, xmlDesc=%s, flags=%x", conn, xmlDesc, flags);
J
Jiri Denemark 已提交
17921 17922 17923

    virResetLastError();

17924
    virCheckConnectReturn(conn, VIR_CPU_COMPARE_ERROR);
17925
    virCheckNonNullArgGoto(xmlDesc, error);
J
Jiri Denemark 已提交
17926

17927
    if (conn->driver->connectCompareCPU) {
J
Jiri Denemark 已提交
17928 17929
        int ret;

17930
        ret = conn->driver->connectCompareCPU(conn, xmlDesc, flags);
J
Jiri Denemark 已提交
17931 17932 17933 17934 17935
        if (ret == VIR_CPU_COMPARE_ERROR)
            goto error;
        return ret;
    }

17936
    virReportUnsupportedError();
J
Jiri Denemark 已提交
17937 17938

error:
17939
    virDispatchError(conn);
J
Jiri Denemark 已提交
17940 17941
    return VIR_CPU_COMPARE_ERROR;
}
17942 17943


17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969
/**
 * virConnectGetCPUModelNames:
 *
 * @conn: virConnect connection
 * @arch: Architecture
 * @models: Pointer to a variable to store the NULL-terminated array of the
 *          CPU models supported for the specified architecture.  Each element
 *          and the array itself must be freed by the caller with free.  Pass
 *          NULL if only the list length is needed.
 * @flags: extra flags; not used yet, so callers should always pass 0.
 *
 * Get the list of supported CPU models for a specific architecture.
 *
 * Returns -1 on error, number of elements in @models on success.
 */
int
virConnectGetCPUModelNames(virConnectPtr conn, const char *arch, char ***models,
                           unsigned int flags)
{
    VIR_DEBUG("conn=%p, arch=%s, models=%p, flags=%x",
              conn, arch, models, flags);
    virResetLastError();

    if (models)
        *models = NULL;

17970
    virCheckConnectReturn(conn, -1);
17971
    virCheckNonNullArgGoto(arch, error);
17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982

    if (conn->driver->connectGetCPUModelNames) {
        int ret;

        ret = conn->driver->connectGetCPUModelNames(conn, arch, models, flags);
        if (ret < 0)
            goto error;

        return ret;
    }

17983
    virReportUnsupportedError();
17984 17985 17986 17987 17988 17989 17990

error:
    virDispatchError(conn);
    return -1;
}


17991 17992 17993 17994 17995 17996
/**
 * virConnectBaselineCPU:
 *
 * @conn: virConnect connection
 * @xmlCPUs: array of XML descriptions of host CPUs
 * @ncpus: number of CPUs in xmlCPUs
17997
 * @flags: bitwise-OR of virConnectBaselineCPUFlags
17998 17999 18000 18001
 *
 * Computes the most feature-rich CPU which is compatible with all given
 * host CPUs.
 *
18002 18003 18004 18005 18006
 * If @flags includes VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES then libvirt
 * will explicitly list all CPU features that are part of the host CPU,
 * without this flag features that are part of the CPU model will not be
 * listed.
 *
18007 18008 18009 18010 18011 18012 18013 18014
 * Returns XML description of the computed CPU or NULL on error.
 */
char *
virConnectBaselineCPU(virConnectPtr conn,
                      const char **xmlCPUs,
                      unsigned int ncpus,
                      unsigned int flags)
{
18015
    size_t i;
18016

18017
    VIR_DEBUG("conn=%p, xmlCPUs=%p, ncpus=%u, flags=%x",
18018 18019 18020
              conn, xmlCPUs, ncpus, flags);
    if (xmlCPUs) {
        for (i = 0; i < ncpus; i++)
18021
            VIR_DEBUG("xmlCPUs[%zu]=%s", i, NULLSTR(xmlCPUs[i]));
18022 18023 18024 18025
    }

    virResetLastError();

18026
    virCheckConnectReturn(conn, NULL);
18027
    virCheckNonNullArgGoto(xmlCPUs, error);
18028

18029
    if (conn->driver->connectBaselineCPU) {
18030 18031
        char *cpu;

18032
        cpu = conn->driver->connectBaselineCPU(conn, xmlCPUs, ncpus, flags);
18033 18034 18035 18036 18037
        if (!cpu)
            goto error;
        return cpu;
    }

18038
    virReportUnsupportedError();
18039 18040 18041 18042 18043

error:
    virDispatchError(conn);
    return NULL;
}
18044 18045 18046 18047 18048 18049 18050 18051 18052 18053


/**
 * virDomainGetJobInfo:
 * @domain: a domain object
 * @info: pointer to a virDomainJobInfo structure allocated by the user
 *
 * Extract information about progress of a background job on a domain.
 * Will return an error if the domain is not active.
 *
E
Eric Blake 已提交
18054 18055 18056
 * This function returns a limited amount of information in comparison
 * to virDomainGetJobStats().
 *
18057 18058 18059 18060 18061 18062
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainGetJobInfo(virDomainPtr domain, virDomainJobInfoPtr info)
{
    virConnectPtr conn;
18063 18064

    VIR_DOMAIN_DEBUG(domain, "info=%p", info);
18065 18066 18067 18068

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
18069
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
18070
        virDispatchError(NULL);
18071
        return -1;
18072
    }
18073
    virCheckNonNullArgGoto(info, error);
18074 18075 18076 18077 18078 18079 18080

    memset(info, 0, sizeof(virDomainJobInfo));

    conn = domain->conn;

    if (conn->driver->domainGetJobInfo) {
        int ret;
18081
        ret = conn->driver->domainGetJobInfo(domain, info);
18082 18083 18084 18085 18086
        if (ret < 0)
            goto error;
        return ret;
    }

18087
    virReportUnsupportedError();
18088 18089 18090 18091

error:
    virDispatchError(domain->conn);
    return -1;
18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146
}


/**
 * virDomainGetJobStats:
 * @domain: a domain object
 * @type: where to store the job type (one of virDomainJobType)
 * @params: where to store job statistics
 * @nparams: number of items in @params
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Extract information about progress of a background job on a domain.
 * Will return an error if the domain is not active. The function returns
 * a superset of progress information provided by virDomainGetJobInfo.
 * Possible fields returned in @params are defined by VIR_DOMAIN_JOB_*
 * macros and new fields will likely be introduced in the future so callers
 * may receive fields that they do not understand in case they talk to a
 * newer server.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainGetJobStats(virDomainPtr domain,
                     int *type,
                     virTypedParameterPtr *params,
                     int *nparams,
                     unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "type=%p, params=%p, nparams=%p, flags=%x",
                     type, params, nparams, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    virCheckNonNullArgGoto(type, error);
    virCheckNonNullArgGoto(params, error);
    virCheckNonNullArgGoto(nparams, error);

    conn = domain->conn;

    if (conn->driver->domainGetJobStats) {
        int ret;
        ret = conn->driver->domainGetJobStats(domain, type, params,
                                              nparams, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

18147
    virReportUnsupportedError();
18148 18149 18150 18151

error:
    virDispatchError(domain->conn);
    return -1;
18152
}
18153 18154 18155 18156 18157 18158 18159


/**
 * virDomainAbortJob:
 * @domain: a domain object
 *
 * Requests that the current background job be aborted at the
M
Michal Privoznik 已提交
18160
 * soonest opportunity.
18161 18162 18163 18164 18165 18166 18167 18168
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainAbortJob(virDomainPtr domain)
{
    virConnectPtr conn;

18169
    VIR_DOMAIN_DEBUG(domain);
18170 18171 18172 18173

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
18174
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
18175
        virDispatchError(NULL);
18176
        return -1;
18177 18178 18179
    }

    conn = domain->conn;
18180
    virCheckReadOnlyGoto(conn->flags, error);
18181 18182 18183 18184 18185 18186 18187 18188 18189

    if (conn->driver->domainAbortJob) {
        int ret;
        ret = conn->driver->domainAbortJob(domain);
        if (ret < 0)
            goto error;
        return ret;
    }

18190
    virReportUnsupportedError();
18191 18192 18193 18194 18195

error:
    virDispatchError(conn);
    return -1;
}
18196 18197 18198 18199 18200 18201


/**
 * virDomainMigrateSetMaxDowntime:
 * @domain: a domain object
 * @downtime: maximum tolerable downtime for live migration, in milliseconds
18202
 * @flags: extra flags; not used yet, so callers should always pass 0
18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216
 *
 * Sets maximum tolerable time for which the domain is allowed to be paused
 * at the end of live migration. It's supposed to be called while the domain is
 * being live-migrated as a reaction to migration progress.
 *
 * Returns 0 in case of success, -1 otherwise.
 */
int
virDomainMigrateSetMaxDowntime(virDomainPtr domain,
                               unsigned long long downtime,
                               unsigned int flags)
{
    virConnectPtr conn;

18217
    VIR_DOMAIN_DEBUG(domain, "downtime=%llu, flags=%x", downtime, flags);
18218 18219 18220 18221

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
18222
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
18223 18224 18225 18226 18227
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;
18228
    virCheckReadOnlyGoto(conn->flags, error);
18229 18230 18231 18232 18233 18234 18235

    if (conn->driver->domainMigrateSetMaxDowntime) {
        if (conn->driver->domainMigrateSetMaxDowntime(domain, downtime, flags) < 0)
            goto error;
        return 0;
    }

18236
    virReportUnsupportedError();
18237 18238 18239 18240 18241
error:
    virDispatchError(conn);
    return -1;
}

18242

18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281
/**
 * virDomainMigrateGetCompressionCache:
 * @domain: a domain object
 * @cacheSize: return value of current size of the cache (in bytes)
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Gets current size of the cache (in bytes) used for compressing repeatedly
 * transferred memory pages during live migration.
 *
 * Returns 0 in case of success, -1 otherwise.
 */
int
virDomainMigrateGetCompressionCache(virDomainPtr domain,
                                    unsigned long long *cacheSize,
                                    unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "cacheSize=%p, flags=%x", cacheSize, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;

    virCheckNonNullArgGoto(cacheSize, error);

    if (conn->driver->domainMigrateGetCompressionCache) {
        if (conn->driver->domainMigrateGetCompressionCache(domain, cacheSize,
                                                           flags) < 0)
            goto error;
        return 0;
    }

18282
    virReportUnsupportedError();
18283 18284 18285 18286 18287
error:
    virDispatchError(conn);
    return -1;
}

18288

18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320
/**
 * virDomainMigrateSetCompressionCache:
 * @domain: a domain object
 * @cacheSize: size of the cache (in bytes) used for compression
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Sets size of the cache (in bytes) used for compressing repeatedly
 * transferred memory pages during live migration. It's supposed to be called
 * while the domain is being live-migrated as a reaction to migration progress
 * and increasing number of compression cache misses obtained from
 * virDomainGetJobStats.
 *
 * Returns 0 in case of success, -1 otherwise.
 */
int
virDomainMigrateSetCompressionCache(virDomainPtr domain,
                                    unsigned long long cacheSize,
                                    unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "cacheSize=%llu, flags=%x", cacheSize, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;
18321
    virCheckReadOnlyGoto(conn->flags, error);
18322 18323 18324 18325 18326 18327 18328 18329

    if (conn->driver->domainMigrateSetCompressionCache) {
        if (conn->driver->domainMigrateSetCompressionCache(domain, cacheSize,
                                                           flags) < 0)
            goto error;
        return 0;
    }

18330
    virReportUnsupportedError();
18331 18332 18333 18334 18335
error:
    virDispatchError(conn);
    return -1;
}

18336

18337 18338 18339
/**
 * virDomainMigrateSetMaxSpeed:
 * @domain: a domain object
18340
 * @bandwidth: migration bandwidth limit in MiB/s
18341
 * @flags: extra flags; not used yet, so callers should always pass 0
18342
 *
18343
 * The maximum bandwidth (in MiB/s) that will be used to do migration
18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355
 * can be specified with the bandwidth parameter. Not all hypervisors
 * will support a bandwidth cap
 *
 * Returns 0 in case of success, -1 otherwise.
 */
int
virDomainMigrateSetMaxSpeed(virDomainPtr domain,
                            unsigned long bandwidth,
                            unsigned int flags)
{
    virConnectPtr conn;

18356
    VIR_DOMAIN_DEBUG(domain, "bandwidth=%lu, flags=%x", bandwidth, flags);
18357 18358 18359 18360 18361 18362 18363 18364 18365 18366

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;
18367
    virCheckReadOnlyGoto(conn->flags, error);
18368 18369 18370 18371 18372 18373 18374

    if (conn->driver->domainMigrateSetMaxSpeed) {
        if (conn->driver->domainMigrateSetMaxSpeed(domain, bandwidth, flags) < 0)
            goto error;
        return 0;
    }

18375
    virReportUnsupportedError();
18376 18377 18378 18379 18380
error:
    virDispatchError(conn);
    return -1;
}

18381

18382 18383 18384
/**
 * virDomainMigrateGetMaxSpeed:
 * @domain: a domain object
18385
 * @bandwidth: return value of current migration bandwidth limit in MiB/s
18386
 * @flags: extra flags; not used yet, so callers should always pass 0
18387
 *
18388
 * Get the current maximum bandwidth (in MiB/s) that will be used if the
18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409
 * domain is migrated.  Not all hypervisors will support a bandwidth limit.
 *
 * Returns 0 in case of success, -1 otherwise.
 */
int
virDomainMigrateGetMaxSpeed(virDomainPtr domain,
                            unsigned long *bandwidth,
                            unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "bandwidth = %p, flags=%x", bandwidth, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

18410 18411
    conn = domain->conn;

18412
    virCheckNonNullArgGoto(bandwidth, error);
18413

18414
    virCheckReadOnlyGoto(conn->flags, error);
18415 18416 18417 18418 18419 18420 18421

    if (conn->driver->domainMigrateGetMaxSpeed) {
        if (conn->driver->domainMigrateGetMaxSpeed(domain, bandwidth, flags) < 0)
            goto error;
        return 0;
    }

18422
    virReportUnsupportedError();
18423 18424 18425 18426 18427
error:
    virDispatchError(conn);
    return -1;
}

18428

18429 18430 18431 18432 18433 18434 18435 18436 18437 18438
/**
 * virConnectDomainEventRegisterAny:
 * @conn: pointer to the connection
 * @dom: pointer to the domain
 * @eventID: the event type to receive
 * @cb: callback to the function handling domain events
 * @opaque: opaque data to pass on to the callback
 * @freecb: optional function to deallocate opaque when not used anymore
 *
 * Adds a callback to receive notifications of arbitrary domain events
E
Eric Blake 已提交
18439 18440 18441
 * occurring on a domain.  This function requires that an event loop
 * has been previously registered with virEventRegisterImpl() or
 * virEventRegisterDefaultImpl().
18442
 *
18443
 * If @dom is NULL, then events will be monitored for any domain. If @dom
E
Eric Blake 已提交
18444
 * is non-NULL, then only the specific domain will be monitored.
18445 18446
 *
 * Most types of event have a callback providing a custom set of parameters
18447
 * for the event. When registering an event, it is thus necessary to use
18448 18449 18450 18451 18452
 * the VIR_DOMAIN_EVENT_CALLBACK() macro to cast the supplied function pointer
 * to match the signature of this method.
 *
 * The virDomainPtr object handle passed into the callback upon delivery
 * of an event is only valid for the duration of execution of the callback.
18453
 * If the callback wishes to keep the domain object after the callback returns,
18454
 * it shall take a reference to it, by calling virDomainRef().
18455
 * The reference can be released once the object is no longer required
18456
 * by calling virDomainFree().
18457 18458 18459
 *
 * The return value from this method is a positive integer identifier
 * for the callback. To unregister a callback, this callback ID should
18460
 * be passed to the virConnectDomainEventDeregisterAny() method.
18461
 *
E
Eric Blake 已提交
18462
 * Returns a callback identifier on success, -1 on failure.
18463 18464 18465 18466 18467 18468 18469 18470 18471
 */
int
virConnectDomainEventRegisterAny(virConnectPtr conn,
                                 virDomainPtr dom,
                                 int eventID,
                                 virConnectDomainEventGenericCallback cb,
                                 void *opaque,
                                 virFreeCallback freecb)
{
18472 18473 18474
    VIR_DOMAIN_DEBUG(dom, "conn=%p, eventID=%d, cb=%p, opaque=%p, freecb=%p",
                     conn, eventID, cb, opaque, freecb);

18475 18476
    virResetLastError();

18477
    virCheckConnectReturn(conn, -1);
18478 18479
    if (dom != NULL &&
        !(VIR_IS_CONNECTED_DOMAIN(dom) && dom->conn == conn)) {
18480
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
18481
        virDispatchError(conn);
18482
        return -1;
18483
    }
18484 18485 18486 18487 18488 18489
    virCheckNonNullArgGoto(cb, error);
    virCheckNonNegativeArgGoto(eventID, error);
    if (eventID >= VIR_DOMAIN_EVENT_ID_LAST) {
        virReportInvalidArg(eventID,
                            _("eventID in %s must be less than %d"),
                            __FUNCTION__, VIR_DOMAIN_EVENT_ID_LAST);
18490 18491 18492
        goto error;
    }

18493
    if (conn->driver && conn->driver->connectDomainEventRegisterAny) {
18494
        int ret;
18495
        ret = conn->driver->connectDomainEventRegisterAny(conn, dom, eventID, cb, opaque, freecb);
18496 18497 18498 18499 18500
        if (ret < 0)
            goto error;
        return ret;
    }

18501
    virReportUnsupportedError();
18502 18503 18504 18505
error:
    virDispatchError(conn);
    return -1;
}
18506

18507

18508 18509 18510 18511 18512 18513
/**
 * virConnectDomainEventDeregisterAny:
 * @conn: pointer to the connection
 * @callbackID: the callback identifier
 *
 * Removes an event callback. The callbackID parameter should be the
18514
 * value obtained from a previous virConnectDomainEventRegisterAny() method.
18515
 *
18516 18517 18518
 * Returns 0 on success, -1 on failure.  Older versions of some hypervisors
 * sometimes returned a positive number on success, but without any reliable
 * semantics on what that number represents. */
18519 18520 18521 18522
int
virConnectDomainEventDeregisterAny(virConnectPtr conn,
                                   int callbackID)
{
18523
    VIR_DEBUG("conn=%p, callbackID=%d", conn, callbackID);
18524 18525 18526

    virResetLastError();

18527
    virCheckConnectReturn(conn, -1);
18528 18529
    virCheckNonNegativeArgGoto(callbackID, error);

18530
    if (conn->driver && conn->driver->connectDomainEventDeregisterAny) {
18531
        int ret;
18532
        ret = conn->driver->connectDomainEventDeregisterAny(conn, callbackID);
18533 18534 18535 18536 18537
        if (ret < 0)
            goto error;
        return ret;
    }

18538
    virReportUnsupportedError();
18539 18540 18541 18542
error:
    virDispatchError(conn);
    return -1;
}
18543

18544

18545 18546 18547 18548 18549 18550 18551 18552 18553 18554
/**
 * virConnectNetworkEventRegisterAny:
 * @conn: pointer to the connection
 * @net: pointer to the network
 * @eventID: the event type to receive
 * @cb: callback to the function handling network events
 * @opaque: opaque data to pass on to the callback
 * @freecb: optional function to deallocate opaque when not used anymore
 *
 * Adds a callback to receive notifications of arbitrary network events
E
Eric Blake 已提交
18555 18556 18557
 * occurring on a network.  This function requires that an event loop
 * has been previously registered with virEventRegisterImpl() or
 * virEventRegisterDefaultImpl().
18558
 *
18559
 * If @net is NULL, then events will be monitored for any network. If @net
E
Eric Blake 已提交
18560
 * is non-NULL, then only the specific network will be monitored.
18561 18562 18563 18564 18565 18566 18567 18568 18569
 *
 * Most types of event have a callback providing a custom set of parameters
 * for the event. When registering an event, it is thus necessary to use
 * the VIR_NETWORK_EVENT_CALLBACK() macro to cast the supplied function pointer
 * to match the signature of this method.
 *
 * The virNetworkPtr object handle passed into the callback upon delivery
 * of an event is only valid for the duration of execution of the callback.
 * If the callback wishes to keep the network object after the callback
18570
 * returns, it shall take a reference to it, by calling virNetworkRef().
18571
 * The reference can be released once the object is no longer required
18572
 * by calling virNetworkFree().
18573 18574 18575
 *
 * The return value from this method is a positive integer identifier
 * for the callback. To unregister a callback, this callback ID should
18576
 * be passed to the virConnectNetworkEventDeregisterAny() method.
18577
 *
E
Eric Blake 已提交
18578
 * Returns a callback identifier on success, -1 on failure.
18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592
 */
int
virConnectNetworkEventRegisterAny(virConnectPtr conn,
                                  virNetworkPtr net,
                                  int eventID,
                                  virConnectNetworkEventGenericCallback cb,
                                  void *opaque,
                                  virFreeCallback freecb)
{
    VIR_DEBUG("conn=%p, eventID=%d, cb=%p, opaque=%p, freecb=%p",
              conn, eventID, cb, opaque, freecb);

    virResetLastError();

18593
    virCheckConnectReturn(conn, -1);
18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609
    if (net != NULL &&
        !(VIR_IS_CONNECTED_NETWORK(net) && net->conn == conn)) {
        virLibConnError(VIR_ERR_INVALID_CONN, __FUNCTION__);
        virDispatchError(conn);
        return -1;
    }
    virCheckNonNullArgGoto(cb, error);
    virCheckNonNegativeArgGoto(eventID, error);

    if (eventID >= VIR_NETWORK_EVENT_ID_LAST) {
        virReportInvalidArg(eventID,
                            _("eventID in %s must be less than %d"),
                            __FUNCTION__, VIR_NETWORK_EVENT_ID_LAST);
        goto error;
    }

18610
    if (conn->networkDriver && conn->networkDriver->connectNetworkEventRegisterAny) {
18611 18612 18613 18614 18615 18616 18617 18618 18619 18620
        int ret;
        ret = conn->networkDriver->connectNetworkEventRegisterAny(conn, net,
                                                                  eventID,
                                                                  cb, opaque,
                                                                  freecb);
        if (ret < 0)
            goto error;
        return ret;
    }

18621
    virReportUnsupportedError();
18622 18623 18624 18625 18626
error:
    virDispatchError(conn);
    return -1;
}

18627

18628 18629 18630 18631 18632 18633
/**
 * virConnectNetworkEventDeregisterAny:
 * @conn: pointer to the connection
 * @callbackID: the callback identifier
 *
 * Removes an event callback. The callbackID parameter should be the
18634
 * value obtained from a previous virConnectNetworkEventRegisterAny() method.
18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645
 *
 * Returns 0 on success, -1 on failure
 */
int
virConnectNetworkEventDeregisterAny(virConnectPtr conn,
                                    int callbackID)
{
    VIR_DEBUG("conn=%p, callbackID=%d", conn, callbackID);

    virResetLastError();

18646
    virCheckConnectReturn(conn, -1);
18647 18648
    virCheckNonNegativeArgGoto(callbackID, error);

18649 18650
    if (conn->networkDriver &&
        conn->networkDriver->connectNetworkEventDeregisterAny) {
18651 18652 18653 18654 18655 18656 18657 18658
        int ret;
        ret = conn->networkDriver->connectNetworkEventDeregisterAny(conn,
                                                                    callbackID);
        if (ret < 0)
            goto error;
        return ret;
    }

18659
    virReportUnsupportedError();
18660 18661 18662 18663 18664
error:
    virDispatchError(conn);
    return -1;
}

18665

18666 18667 18668
/**
 * virDomainManagedSave:
 * @dom: pointer to the domain
18669
 * @flags: bitwise-OR of virDomainSaveRestoreFlags
18670 18671 18672 18673 18674 18675 18676 18677
 *
 * This method will suspend a domain and save its memory contents to
 * a file on disk. After the call, if successful, the domain is not
 * listed as running anymore.
 * The difference from virDomainSave() is that libvirt is keeping track of
 * the saved state itself, and will reuse it once the domain is being
 * restarted (automatically or via an explicit libvirt call).
 * As a result any running domain is sure to not have a managed saved image.
18678 18679 18680
 * This also implies that managed save only works on persistent domains,
 * since the domain must still exist in order to use virDomainCreate() to
 * restart it.
18681
 *
18682 18683 18684 18685 18686
 * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will
 * attempt to bypass the file system cache while creating the file, or
 * fail if it cannot do so for the given system; this can allow less
 * pressure on file system cache, but also risks slowing saves to NFS.
 *
18687 18688 18689 18690 18691 18692
 * Normally, the managed saved state will remember whether the domain
 * was running or paused, and start will resume to the same state.
 * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
 * @flags will override the default saved into the file.  These two
 * flags are mutually exclusive.
 *
18693 18694
 * Returns 0 in case of success or -1 in case of failure
 */
18695 18696
int
virDomainManagedSave(virDomainPtr dom, unsigned int flags)
18697 18698 18699
{
    virConnectPtr conn;

18700
    VIR_DOMAIN_DEBUG(dom, "flags=%x", flags);
18701 18702 18703 18704

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
18705
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
18706 18707 18708 18709 18710
        virDispatchError(NULL);
        return -1;
    }

    conn = dom->conn;
18711
    virCheckReadOnlyGoto(conn->flags, error);
18712

18713
    if ((flags & VIR_DOMAIN_SAVE_RUNNING) && (flags & VIR_DOMAIN_SAVE_PAUSED)) {
18714
        virReportInvalidArg(flags,
18715 18716
                            _("running and paused flags in %s are mutually "
                              "exclusive"),
18717
                            __FUNCTION__);
18718 18719 18720
        goto error;
    }

18721 18722 18723 18724 18725 18726 18727 18728 18729
    if (conn->driver->domainManagedSave) {
        int ret;

        ret = conn->driver->domainManagedSave(dom, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

18730
    virReportUnsupportedError();
18731 18732 18733 18734 18735 18736

error:
    virDispatchError(conn);
    return -1;
}

18737

18738 18739 18740
/**
 * virDomainHasManagedSaveImage:
 * @dom: pointer to the domain
18741
 * @flags: extra flags; not used yet, so callers should always pass 0
18742 18743 18744 18745 18746 18747 18748 18749
 *
 * Check if a domain has a managed save image as created by
 * virDomainManagedSave(). Note that any running domain should not have
 * such an image, as it should have been removed on restart.
 *
 * Returns 0 if no image is present, 1 if an image is present, and
 *         -1 in case of error
 */
18750 18751
int
virDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
18752 18753 18754
{
    virConnectPtr conn;

18755
    VIR_DOMAIN_DEBUG(dom, "flags=%x", flags);
18756 18757 18758 18759

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
18760
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775
        virDispatchError(NULL);
        return -1;
    }

    conn = dom->conn;

    if (conn->driver->domainHasManagedSaveImage) {
        int ret;

        ret = conn->driver->domainHasManagedSaveImage(dom, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

18776
    virReportUnsupportedError();
18777 18778 18779 18780 18781 18782

error:
    virDispatchError(conn);
    return -1;
}

18783

18784 18785 18786
/**
 * virDomainManagedSaveRemove:
 * @dom: pointer to the domain
18787
 * @flags: extra flags; not used yet, so callers should always pass 0
18788
 *
D
Daniel Veillard 已提交
18789
 * Remove any managed save image for this domain.
18790 18791 18792
 *
 * Returns 0 in case of success, and -1 in case of error
 */
18793 18794
int
virDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
18795 18796 18797
{
    virConnectPtr conn;

18798
    VIR_DOMAIN_DEBUG(dom, "flags=%x", flags);
18799 18800 18801 18802

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
18803
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
18804 18805 18806 18807 18808
        virDispatchError(NULL);
        return -1;
    }

    conn = dom->conn;
18809
    virCheckReadOnlyGoto(conn->flags, error);
18810 18811 18812 18813 18814 18815 18816 18817 18818 18819

    if (conn->driver->domainManagedSaveRemove) {
        int ret;

        ret = conn->driver->domainManagedSaveRemove(dom, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

18820
    virReportUnsupportedError();
18821 18822 18823 18824 18825

error:
    virDispatchError(conn);
    return -1;
}
C
Chris Lalancette 已提交
18826

18827

18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852
/**
 * virDomainSnapshotGetName:
 * @snapshot: a snapshot object
 *
 * Get the public name for that snapshot
 *
 * Returns a pointer to the name or NULL, the string need not be deallocated
 * as its lifetime will be the same as the snapshot object.
 */
const char *
virDomainSnapshotGetName(virDomainSnapshotPtr snapshot)
{
    VIR_DEBUG("snapshot=%p", snapshot);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
    return snapshot->name;
}

18853

18854 18855 18856 18857
/**
 * virDomainSnapshotGetDomain:
 * @snapshot: a snapshot object
 *
18858 18859 18860 18861 18862 18863
 * Provides the domain pointer associated with a snapshot.  The
 * reference counter on the domain is not increased by this
 * call.
 *
 * WARNING: When writing libvirt bindings in other languages, do not use this
 * function.  Instead, store the domain and the snapshot object together.
18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882
 *
 * Returns the domain or NULL.
 */
virDomainPtr
virDomainSnapshotGetDomain(virDomainSnapshotPtr snapshot)
{
    VIR_DEBUG("snapshot=%p", snapshot);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
    return snapshot->domain;
}

18883

18884 18885 18886 18887
/**
 * virDomainSnapshotGetConnect:
 * @snapshot: a snapshot object
 *
18888 18889 18890 18891 18892 18893
 * Provides the connection pointer associated with a snapshot.  The
 * reference counter on the connection is not increased by this
 * call.
 *
 * WARNING: When writing libvirt bindings in other languages, do not use this
 * function.  Instead, store the connection and the snapshot object together.
18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912
 *
 * Returns the connection or NULL.
 */
virConnectPtr
virDomainSnapshotGetConnect(virDomainSnapshotPtr snapshot)
{
    VIR_DEBUG("snapshot=%p", snapshot);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }
    return snapshot->domain->conn;
}

18913

C
Chris Lalancette 已提交
18914 18915 18916 18917
/**
 * virDomainSnapshotCreateXML:
 * @domain: a domain object
 * @xmlDesc: string containing an XML description of the domain
18918
 * @flags: bitwise-OR of virDomainSnapshotCreateFlags
C
Chris Lalancette 已提交
18919 18920 18921 18922
 *
 * Creates a new snapshot of a domain based on the snapshot xml
 * contained in xmlDesc.
 *
18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957
 * If @flags is 0, the domain can be active, in which case the
 * snapshot will be a system checkpoint (both disk state and runtime
 * VM state such as RAM contents), where reverting to the snapshot is
 * the same as resuming from hibernation (TCP connections may have
 * timed out, but everything else picks up where it left off); or
 * the domain can be inactive, in which case the snapshot includes
 * just the disk state prior to booting.  The newly created snapshot
 * becomes current (see virDomainSnapshotCurrent()), and is a child
 * of any previous current snapshot.
 *
 * If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE, then this
 * is a request to reinstate snapshot metadata that was previously
 * discarded, rather than creating a new snapshot.  This can be used
 * to recreate a snapshot hierarchy on a destination, then remove it
 * on the source, in order to allow migration (since migration
 * normally fails if snapshot metadata still remains on the source
 * machine).  When redefining snapshot metadata, the current snapshot
 * will not be altered unless the VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT
 * flag is also present.  It is an error to request the
 * VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT flag without
 * VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE.  On some hypervisors,
 * redefining an existing snapshot can be used to alter host-specific
 * portions of the domain XML to be used during revert (such as
 * backing filenames associated with disk devices), but must not alter
 * guest-visible layout.  When redefining a snapshot name that does
 * not exist, the hypervisor may validate that reverting to the
 * snapshot appears to be possible (for example, disk images have
 * snapshot contents by the requested name).  Not all hypervisors
 * support these flags.
 *
 * If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA, then the
 * domain's disk images are modified according to @xmlDesc, but then
 * the just-created snapshot has its metadata deleted.  This flag is
 * incompatible with VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE.
 *
18958 18959 18960 18961 18962 18963
 * If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_HALT, then the domain
 * will be inactive after the snapshot completes, regardless of whether
 * it was active before; otherwise, a running domain will still be
 * running after the snapshot.  This flag is invalid on transient domains,
 * and is incompatible with VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE.
 *
18964 18965 18966 18967 18968 18969
 * If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_LIVE, then the domain
 * is not paused while creating the snapshot. This increases the size
 * of the memory dump file, but reduces downtime of the guest while
 * taking the snapshot. Some hypervisors only support this flag during
 * external checkpoints.
 *
18970 18971 18972 18973 18974 18975
 * If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY, then the
 * snapshot will be limited to the disks described in @xmlDesc, and no
 * VM state will be saved.  For an active guest, the disk image may be
 * inconsistent (as if power had been pulled), and specifying this
 * with the VIR_DOMAIN_SNAPSHOT_CREATE_HALT flag risks data loss.
 *
18976 18977 18978 18979 18980 18981
 * If @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE, then the
 * libvirt will attempt to use guest agent to freeze and thaw all
 * file systems in use within domain OS. However, if the guest agent
 * is not present, an error is thrown. Moreover, this flag requires
 * VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY to be passed as well.
 *
18982
 * By default, if the snapshot involves external files, and any of the
18983 18984 18985 18986 18987 18988 18989
 * destination files already exist as a non-empty regular file, the
 * snapshot is rejected to avoid losing contents of those files.
 * However, if @flags includes VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT,
 * then the destination files must already exist and contain content
 * identical to the source files (this allows a management app to
 * pre-create files with relative backing file names, rather than the
 * default of creating with absolute backing file names).
18990 18991
 *
 * Be aware that although libvirt prefers to report errors up front with
E
Eric Blake 已提交
18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004
 * no other effect, some hypervisors have certain types of failures where
 * the overall command can easily fail even though the guest configuration
 * was partially altered (for example, if a disk snapshot request for two
 * disks fails on the second disk, but the first disk alteration cannot be
 * rolled back).  If this API call fails, it is therefore normally
 * necessary to follow up with virDomainGetXMLDesc() and check each disk
 * to determine if any partial changes occurred.  However, if @flags
 * contains VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC, then libvirt guarantees
 * that this command will not alter any disks unless the entire set of
 * changes can be done atomically, making failure recovery simpler (note
 * that it is still possible to fail after disks have changed, but only
 * in the much rarer cases of running out of memory or disk space).
 *
E
Eric Blake 已提交
19005 19006 19007 19008
 * Some hypervisors may prevent this operation if there is a current
 * block copy operation; in that case, use virDomainBlockJobAbort()
 * to stop the block copy first.
 *
E
Eric Blake 已提交
19009
 * Returns an (opaque) virDomainSnapshotPtr on success, NULL on failure.
C
Chris Lalancette 已提交
19010 19011 19012 19013 19014 19015 19016 19017
 */
virDomainSnapshotPtr
virDomainSnapshotCreateXML(virDomainPtr domain,
                           const char *xmlDesc,
                           unsigned int flags)
{
    virConnectPtr conn;

19018
    VIR_DOMAIN_DEBUG(domain, "xmlDesc=%s, flags=%x", xmlDesc, flags);
C
Chris Lalancette 已提交
19019 19020 19021 19022

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
19023
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
C
Chris Lalancette 已提交
19024 19025 19026 19027 19028
        virDispatchError(NULL);
        return NULL;
    }

    conn = domain->conn;
19029

19030
    virCheckNonNullArgGoto(xmlDesc, error);
19031

19032
    virCheckReadOnlyGoto(conn->flags, error);
C
Chris Lalancette 已提交
19033

19034 19035
    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT) &&
        !(flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)) {
19036
        virReportInvalidArg(flags,
19037 19038
                            _("use of 'current' flag in %s requires "
                              "'redefine' flag"),
19039
                            __FUNCTION__);
19040 19041 19042 19043
        goto error;
    }
    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) &&
        (flags & VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA)) {
19044
        virReportInvalidArg(flags,
19045 19046
                            _("'redefine' and 'no metadata' flags in %s are "
                              "mutually exclusive"),
19047
                            __FUNCTION__);
19048 19049
        goto error;
    }
19050 19051
    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) &&
        (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
19052
        virReportInvalidArg(flags,
19053 19054
                            _("'redefine' and 'halt' flags in %s are mutually "
                              "exclusive"),
19055
                            __FUNCTION__);
19056 19057
        goto error;
    }
19058

C
Chris Lalancette 已提交
19059 19060 19061 19062 19063 19064 19065 19066
    if (conn->driver->domainSnapshotCreateXML) {
        virDomainSnapshotPtr ret;
        ret = conn->driver->domainSnapshotCreateXML(domain, xmlDesc, flags);
        if (!ret)
            goto error;
        return ret;
    }

19067
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19068 19069 19070 19071 19072
error:
    virDispatchError(conn);
    return NULL;
}

19073

C
Chris Lalancette 已提交
19074 19075 19076
/**
 * virDomainSnapshotGetXMLDesc:
 * @snapshot: a domain snapshot object
19077
 * @flags: bitwise-OR of subset of virDomainXMLFlags
C
Chris Lalancette 已提交
19078 19079 19080
 *
 * Provide an XML description of the domain snapshot.
 *
19081 19082 19083 19084 19085
 * No security-sensitive data will be included unless @flags contains
 * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only
 * connections.  For this API, @flags should not contain either
 * VIR_DOMAIN_XML_INACTIVE or VIR_DOMAIN_XML_UPDATE_CPU.
 *
C
Chris Lalancette 已提交
19086 19087 19088 19089 19090 19091 19092 19093
 * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
virDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virConnectPtr conn;
19094
    VIR_DEBUG("snapshot=%p, flags=%x", snapshot, flags);
C
Chris Lalancette 已提交
19095 19096 19097 19098

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
19099
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
C
Chris Lalancette 已提交
19100 19101
                                  __FUNCTION__);
        virDispatchError(NULL);
19102
        return NULL;
C
Chris Lalancette 已提交
19103 19104 19105 19106 19107
    }

    conn = snapshot->domain->conn;

    if ((conn->flags & VIR_CONNECT_RO) && (flags & VIR_DOMAIN_XML_SECURE)) {
19108
        virLibConnError(VIR_ERR_OPERATION_DENIED, "%s",
C
Chris Lalancette 已提交
19109 19110 19111 19112
                        _("virDomainSnapshotGetXMLDesc with secure flag"));
        goto error;
    }

19113
    if (conn->driver->domainSnapshotGetXMLDesc) {
C
Chris Lalancette 已提交
19114
        char *ret;
19115
        ret = conn->driver->domainSnapshotGetXMLDesc(snapshot, flags);
C
Chris Lalancette 已提交
19116 19117 19118 19119 19120
        if (!ret)
            goto error;
        return ret;
    }

19121
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19122 19123 19124 19125 19126
error:
    virDispatchError(conn);
    return NULL;
}

19127

C
Chris Lalancette 已提交
19128 19129 19130
/**
 * virDomainSnapshotNum:
 * @domain: a domain object
19131
 * @flags: bitwise-OR of supported virDomainSnapshotListFlags
19132 19133
 *
 * Provides the number of domain snapshots for this domain.
C
Chris Lalancette 已提交
19134
 *
19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150
 * By default, this command covers all snapshots; it is also possible to
 * limit things to just snapshots with no parents, when @flags includes
 * VIR_DOMAIN_SNAPSHOT_LIST_ROOTS.  Additional filters are provided in
 * groups, where each group contains bits that describe mutually exclusive
 * attributes of a snapshot, and where all bits within a group describe
 * all possible snapshots.  Some hypervisors might reject explicit bits
 * from a group where the hypervisor cannot make a distinction.  For a
 * group supported by a given hypervisor, the behavior when no bits of a
 * group are set is identical to the behavior when all bits in that group
 * are set.  When setting bits from more than one group, it is possible to
 * select an impossible combination, in that case a hypervisor may return
 * either 0 or an error.
 *
 * The first group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_LEAVES and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES, to filter based on snapshots that
 * have no further children (a leaf snapshot).
C
Chris Lalancette 已提交
19151
 *
19152 19153 19154 19155
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_METADATA and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA, for filtering snapshots based on
 * whether they have metadata that would prevent the removal of the last
 * reference to a domain.
19156
 *
19157 19158 19159 19160 19161 19162 19163 19164 19165 19166
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE,
 * VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE, and VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY,
 * for filtering snapshots based on what domain state is tracked by the
 * snapshot.
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL and
 * VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL, for filtering snapshots based on
 * whether the snapshot is stored inside the disk images or as
 * additional files.
 *
19167
 * Returns the number of domain snapshots found or -1 in case of error.
C
Chris Lalancette 已提交
19168 19169 19170 19171 19172
 */
int
virDomainSnapshotNum(virDomainPtr domain, unsigned int flags)
{
    virConnectPtr conn;
19173

E
Eric Blake 已提交
19174
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
C
Chris Lalancette 已提交
19175 19176 19177 19178

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
19179
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
C
Chris Lalancette 已提交
19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;
    if (conn->driver->domainSnapshotNum) {
        int ret = conn->driver->domainSnapshotNum(domain, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19192
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19193 19194 19195 19196 19197
error:
    virDispatchError(conn);
    return -1;
}

19198

C
Chris Lalancette 已提交
19199 19200 19201 19202 19203
/**
 * virDomainSnapshotListNames:
 * @domain: a domain object
 * @names: array to collect the list of names of snapshots
 * @nameslen: size of @names
19204
 * @flags: bitwise-OR of supported virDomainSnapshotListFlags
C
Chris Lalancette 已提交
19205 19206
 *
 * Collect the list of domain snapshots for the given domain, and store
19207 19208
 * their names in @names.  The value to use for @nameslen can be determined
 * by virDomainSnapshotNum() with the same @flags.
19209
 *
19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225
 * By default, this command covers all snapshots; it is also possible to
 * limit things to just snapshots with no parents, when @flags includes
 * VIR_DOMAIN_SNAPSHOT_LIST_ROOTS.  Additional filters are provided in
 * groups, where each group contains bits that describe mutually exclusive
 * attributes of a snapshot, and where all bits within a group describe
 * all possible snapshots.  Some hypervisors might reject explicit bits
 * from a group where the hypervisor cannot make a distinction.  For a
 * group supported by a given hypervisor, the behavior when no bits of a
 * group are set is identical to the behavior when all bits in that group
 * are set.  When setting bits from more than one group, it is possible to
 * select an impossible combination, in that case a hypervisor may return
 * either 0 or an error.
 *
 * The first group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_LEAVES and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES, to filter based on snapshots that
 * have no further children (a leaf snapshot).
19226
 *
19227 19228 19229 19230
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_METADATA and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA, for filtering snapshots based on
 * whether they have metadata that would prevent the removal of the last
 * reference to a domain.
C
Chris Lalancette 已提交
19231
 *
19232 19233 19234 19235 19236 19237 19238 19239 19240 19241
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE,
 * VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE, and VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY,
 * for filtering snapshots based on what domain state is tracked by the
 * snapshot.
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL and
 * VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL, for filtering snapshots based on
 * whether the snapshot is stored inside the disk images or as
 * additional files.
 *
19242 19243 19244 19245 19246 19247
 * Note that this command is inherently racy: another connection can
 * define a new snapshot between a call to virDomainSnapshotNum() and
 * this call.  You are only guaranteed that all currently defined
 * snapshots were listed if the return is less than @nameslen.  Likewise,
 * you should be prepared for virDomainSnapshotLookupByName() to fail when
 * converting a name from this call into a snapshot object, if another
19248 19249 19250 19251
 * connection deletes the snapshot in the meantime.  For more control over
 * the results, see virDomainListAllSnapshots().
 *
 * Returns the number of domain snapshots found or -1 in case of error.
J
John Ferlan 已提交
19252
 * The caller is responsible to call free() for each member of the array.
C
Chris Lalancette 已提交
19253 19254 19255 19256 19257 19258 19259
 */
int
virDomainSnapshotListNames(virDomainPtr domain, char **names, int nameslen,
                           unsigned int flags)
{
    virConnectPtr conn;

19260
    VIR_DOMAIN_DEBUG(domain, "names=%p, nameslen=%d, flags=%x",
19261
                     names, nameslen, flags);
C
Chris Lalancette 已提交
19262 19263 19264 19265

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
19266
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
C
Chris Lalancette 已提交
19267 19268 19269 19270 19271 19272
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;

19273 19274
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(nameslen, error);
C
Chris Lalancette 已提交
19275 19276 19277 19278 19279 19280 19281 19282 19283

    if (conn->driver->domainSnapshotListNames) {
        int ret = conn->driver->domainSnapshotListNames(domain, names,
                                                        nameslen, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19284
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19285 19286 19287 19288 19289
error:
    virDispatchError(conn);
    return -1;
}

19290

19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324
/**
 * virDomainListAllSnapshots:
 * @domain: a domain object
 * @snaps: pointer to variable to store the array containing snapshot objects,
 *         or NULL if the list is not required (just returns number of
 *         snapshots)
 * @flags: bitwise-OR of supported virDomainSnapshotListFlags
 *
 * Collect the list of domain snapshots for the given domain, and allocate
 * an array to store those objects.  This API solves the race inherent in
 * virDomainSnapshotListNames().
 *
 * By default, this command covers all snapshots; it is also possible to
 * limit things to just snapshots with no parents, when @flags includes
 * VIR_DOMAIN_SNAPSHOT_LIST_ROOTS.  Additional filters are provided in
 * groups, where each group contains bits that describe mutually exclusive
 * attributes of a snapshot, and where all bits within a group describe
 * all possible snapshots.  Some hypervisors might reject explicit bits
 * from a group where the hypervisor cannot make a distinction.  For a
 * group supported by a given hypervisor, the behavior when no bits of a
 * group are set is identical to the behavior when all bits in that group
 * are set.  When setting bits from more than one group, it is possible to
 * select an impossible combination, in that case a hypervisor may return
 * either 0 or an error.
 *
 * The first group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_LEAVES and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES, to filter based on snapshots that
 * have no further children (a leaf snapshot).
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_METADATA and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA, for filtering snapshots based on
 * whether they have metadata that would prevent the removal of the last
 * reference to a domain.
 *
19325 19326 19327 19328 19329 19330 19331 19332 19333 19334
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE,
 * VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE, and VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY,
 * for filtering snapshots based on what domain state is tracked by the
 * snapshot.
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL and
 * VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL, for filtering snapshots based on
 * whether the snapshot is stored inside the disk images or as
 * additional files.
 *
19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369
 * Returns the number of domain snapshots found or -1 and sets @snaps to
 * NULL in case of error.  On success, the array stored into @snaps is
 * guaranteed to have an extra allocated element set to NULL but not included
 * in the return count, to make iteration easier.  The caller is responsible
 * for calling virDomainSnapshotFree() on each array element, then calling
 * free() on @snaps.
 */
int
virDomainListAllSnapshots(virDomainPtr domain, virDomainSnapshotPtr **snaps,
                          unsigned int flags)
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain, "snaps=%p, flags=%x", snaps, flags);

    virResetLastError();

    if (snaps)
        *snaps = NULL;

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;

    if (conn->driver->domainListAllSnapshots) {
        int ret = conn->driver->domainListAllSnapshots(domain, snaps, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19370
    virReportUnsupportedError();
19371 19372 19373 19374 19375
error:
    virDispatchError(conn);
    return -1;
}

19376

19377 19378 19379
/**
 * virDomainSnapshotNumChildren:
 * @snapshot: a domain snapshot object
19380
 * @flags: bitwise-OR of supported virDomainSnapshotListFlags
19381 19382 19383
 *
 * Provides the number of child snapshots for this domain snapshot.
 *
19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395
 * By default, this command covers only direct children; it is also possible
 * to expand things to cover all descendants, when @flags includes
 * VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS.  Also, some filters are provided in
 * groups, where each group contains bits that describe mutually exclusive
 * attributes of a snapshot, and where all bits within a group describe
 * all possible snapshots.  Some hypervisors might reject explicit bits
 * from a group where the hypervisor cannot make a distinction.  For a
 * group supported by a given hypervisor, the behavior when no bits of a
 * group are set is identical to the behavior when all bits in that group
 * are set.  When setting bits from more than one group, it is possible to
 * select an impossible combination, in that case a hypervisor may return
 * either 0 or an error.
19396
 *
19397 19398 19399
 * The first group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_LEAVES and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES, to filter based on snapshots that
 * have no further children (a leaf snapshot).
19400
 *
19401 19402 19403 19404
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_METADATA and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA, for filtering snapshots based on
 * whether they have metadata that would prevent the removal of the last
 * reference to a domain.
19405
 *
19406 19407 19408 19409 19410 19411 19412 19413 19414 19415
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE,
 * VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE, and VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY,
 * for filtering snapshots based on what domain state is tracked by the
 * snapshot.
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL and
 * VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL, for filtering snapshots based on
 * whether the snapshot is stored inside the disk images or as
 * additional files.
 *
19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441
 * Returns the number of domain snapshots found or -1 in case of error.
 */
int
virDomainSnapshotNumChildren(virDomainSnapshotPtr snapshot, unsigned int flags)
{
    virConnectPtr conn;

    VIR_DEBUG("snapshot=%p, flags=%x", snapshot, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = snapshot->domain->conn;
    if (conn->driver->domainSnapshotNumChildren) {
        int ret = conn->driver->domainSnapshotNumChildren(snapshot, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19442
    virReportUnsupportedError();
19443 19444 19445 19446 19447
error:
    virDispatchError(conn);
    return -1;
}

19448

19449 19450 19451 19452 19453
/**
 * virDomainSnapshotListChildrenNames:
 * @snapshot: a domain snapshot object
 * @names: array to collect the list of names of snapshots
 * @nameslen: size of @names
19454
 * @flags: bitwise-OR of supported virDomainSnapshotListFlags
19455 19456
 *
 * Collect the list of domain snapshots that are children of the given
19457 19458 19459
 * snapshot, and store their names in @names.  The value to use for
 * @nameslen can be determined by virDomainSnapshotNumChildren() with
 * the same @flags.
19460
 *
19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472
 * By default, this command covers only direct children; it is also possible
 * to expand things to cover all descendants, when @flags includes
 * VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS.  Also, some filters are provided in
 * groups, where each group contains bits that describe mutually exclusive
 * attributes of a snapshot, and where all bits within a group describe
 * all possible snapshots.  Some hypervisors might reject explicit bits
 * from a group where the hypervisor cannot make a distinction.  For a
 * group supported by a given hypervisor, the behavior when no bits of a
 * group are set is identical to the behavior when all bits in that group
 * are set.  When setting bits from more than one group, it is possible to
 * select an impossible combination, in that case a hypervisor may return
 * either 0 or an error.
19473
 *
19474 19475 19476
 * The first group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_LEAVES and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES, to filter based on snapshots that
 * have no further children (a leaf snapshot).
19477
 *
19478 19479 19480 19481
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_METADATA and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA, for filtering snapshots based on
 * whether they have metadata that would prevent the removal of the last
 * reference to a domain.
19482
 *
19483 19484 19485 19486 19487 19488 19489 19490 19491 19492
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE,
 * VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE, and VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY,
 * for filtering snapshots based on what domain state is tracked by the
 * snapshot.
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL and
 * VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL, for filtering snapshots based on
 * whether the snapshot is stored inside the disk images or as
 * additional files.
 *
19493
 * Returns the number of domain snapshots found or -1 in case of error.
19494 19495 19496 19497 19498 19499
 * Note that this command is inherently racy: another connection can
 * define a new snapshot between a call to virDomainSnapshotNumChildren()
 * and this call.  You are only guaranteed that all currently defined
 * snapshots were listed if the return is less than @nameslen.  Likewise,
 * you should be prepared for virDomainSnapshotLookupByName() to fail when
 * converting a name from this call into a snapshot object, if another
19500 19501 19502 19503
 * connection deletes the snapshot in the meantime.  For more control over
 * the results, see virDomainSnapshotListAllChildren().
 *
 * Returns the number of domain snapshots found or -1 in case of error.
J
John Ferlan 已提交
19504
 * The caller is responsible to call free() for each member of the array.
19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526
 */
int
virDomainSnapshotListChildrenNames(virDomainSnapshotPtr snapshot,
                                   char **names, int nameslen,
                                   unsigned int flags)
{
    virConnectPtr conn;

    VIR_DEBUG("snapshot=%p, names=%p, nameslen=%d, flags=%x",
              snapshot, names, nameslen, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = snapshot->domain->conn;

19527 19528
    virCheckNonNullArgGoto(names, error);
    virCheckNonNegativeArgGoto(nameslen, error);
19529 19530 19531 19532 19533 19534

    if (conn->driver->domainSnapshotListChildrenNames) {
        int ret = conn->driver->domainSnapshotListChildrenNames(snapshot,
                                                                names,
                                                                nameslen,
                                                                flags);
19535 19536 19537 19538 19539
        if (ret < 0)
            goto error;
        return ret;
    }

19540
    virReportUnsupportedError();
19541 19542 19543 19544 19545
error:
    virDispatchError(conn);
    return -1;
}

19546

19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580
/**
 * virDomainSnapshotListAllChildren:
 * @snapshot: a domain snapshot object
 * @snaps: pointer to variable to store the array containing snapshot objects,
 *         or NULL if the list is not required (just returns number of
 *         snapshots)
 * @flags: bitwise-OR of supported virDomainSnapshotListFlags
 *
 * Collect the list of domain snapshots that are children of the given
 * snapshot, and allocate an array to store those objects.  This API solves
 * the race inherent in virDomainSnapshotListChildrenNames().
 *
 * By default, this command covers only direct children; it is also possible
 * to expand things to cover all descendants, when @flags includes
 * VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS.  Also, some filters are provided in
 * groups, where each group contains bits that describe mutually exclusive
 * attributes of a snapshot, and where all bits within a group describe
 * all possible snapshots.  Some hypervisors might reject explicit bits
 * from a group where the hypervisor cannot make a distinction.  For a
 * group supported by a given hypervisor, the behavior when no bits of a
 * group are set is identical to the behavior when all bits in that group
 * are set.  When setting bits from more than one group, it is possible to
 * select an impossible combination, in that case a hypervisor may return
 * either 0 or an error.
 *
 * The first group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_LEAVES and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES, to filter based on snapshots that
 * have no further children (a leaf snapshot).
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_METADATA and
 * VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA, for filtering snapshots based on
 * whether they have metadata that would prevent the removal of the last
 * reference to a domain.
 *
19581 19582 19583 19584 19585 19586 19587 19588 19589 19590
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE,
 * VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE, and VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY,
 * for filtering snapshots based on what domain state is tracked by the
 * snapshot.
 *
 * The next group of @flags is VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL and
 * VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL, for filtering snapshots based on
 * whether the snapshot is stored inside the disk images or as
 * additional files.
 *
19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623
 * Returns the number of domain snapshots found or -1 and sets @snaps to
 * NULL in case of error.  On success, the array stored into @snaps is
 * guaranteed to have an extra allocated element set to NULL but not included
 * in the return count, to make iteration easier.  The caller is responsible
 * for calling virDomainSnapshotFree() on each array element, then calling
 * free() on @snaps.
 */
int
virDomainSnapshotListAllChildren(virDomainSnapshotPtr snapshot,
                                 virDomainSnapshotPtr **snaps,
                                 unsigned int flags)
{
    virConnectPtr conn;

    VIR_DEBUG("snapshot=%p, snaps=%p, flags=%x", snapshot, snaps, flags);

    virResetLastError();

    if (snaps)
        *snaps = NULL;

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = snapshot->domain->conn;

    if (conn->driver->domainSnapshotListAllChildren) {
        int ret = conn->driver->domainSnapshotListAllChildren(snapshot, snaps,
                                                              flags);
19624 19625 19626 19627 19628
        if (ret < 0)
            goto error;
        return ret;
    }

19629
    virReportUnsupportedError();
19630 19631 19632 19633 19634
error:
    virDispatchError(conn);
    return -1;
}

19635

C
Chris Lalancette 已提交
19636 19637 19638 19639
/**
 * virDomainSnapshotLookupByName:
 * @domain: a domain object
 * @name: name for the domain snapshot
19640
 * @flags: extra flags; not used yet, so callers should always pass 0
C
Chris Lalancette 已提交
19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653
 *
 * Try to lookup a domain snapshot based on its name.
 *
 * Returns a domain snapshot object or NULL in case of failure.  If the
 * domain snapshot cannot be found, then the VIR_ERR_NO_DOMAIN_SNAPSHOT
 * error is raised.
 */
virDomainSnapshotPtr
virDomainSnapshotLookupByName(virDomainPtr domain,
                              const char *name,
                              unsigned int flags)
{
    virConnectPtr conn;
19654

19655
    VIR_DOMAIN_DEBUG(domain, "name=%s, flags=%x", name, flags);
C
Chris Lalancette 已提交
19656 19657 19658 19659

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
19660
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
C
Chris Lalancette 已提交
19661
        virDispatchError(NULL);
19662
        return NULL;
C
Chris Lalancette 已提交
19663 19664 19665 19666
    }

    conn = domain->conn;

19667
    virCheckNonNullArgGoto(name, error);
C
Chris Lalancette 已提交
19668 19669 19670 19671 19672 19673 19674 19675 19676

    if (conn->driver->domainSnapshotLookupByName) {
        virDomainSnapshotPtr dom;
        dom = conn->driver->domainSnapshotLookupByName(domain, name, flags);
        if (!dom)
            goto error;
        return dom;
    }

19677
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19678 19679 19680 19681 19682
error:
    virDispatchError(conn);
    return NULL;
}

19683

C
Chris Lalancette 已提交
19684 19685 19686
/**
 * virDomainHasCurrentSnapshot:
 * @domain: pointer to the domain object
19687
 * @flags: extra flags; not used yet, so callers should always pass 0
C
Chris Lalancette 已提交
19688 19689 19690 19691 19692 19693 19694 19695 19696
 *
 * Determine if the domain has a current snapshot.
 *
 * Returns 1 if such snapshot exists, 0 if it doesn't, -1 on error.
 */
int
virDomainHasCurrentSnapshot(virDomainPtr domain, unsigned int flags)
{
    virConnectPtr conn;
19697

19698
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
C
Chris Lalancette 已提交
19699 19700 19701 19702

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
19703
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
C
Chris Lalancette 已提交
19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;

    if (conn->driver->domainHasCurrentSnapshot) {
        int ret = conn->driver->domainHasCurrentSnapshot(domain, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19717
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19718 19719 19720 19721 19722
error:
    virDispatchError(conn);
    return -1;
}

19723

C
Chris Lalancette 已提交
19724 19725 19726
/**
 * virDomainSnapshotCurrent:
 * @domain: a domain object
19727
 * @flags: extra flags; not used yet, so callers should always pass 0
C
Chris Lalancette 已提交
19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739
 *
 * Get the current snapshot for a domain, if any.
 *
 * Returns a domain snapshot object or NULL in case of failure.  If the
 * current domain snapshot cannot be found, then the VIR_ERR_NO_DOMAIN_SNAPSHOT
 * error is raised.
 */
virDomainSnapshotPtr
virDomainSnapshotCurrent(virDomainPtr domain,
                         unsigned int flags)
{
    virConnectPtr conn;
19740

19741
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
C
Chris Lalancette 已提交
19742 19743 19744 19745

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
19746
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
C
Chris Lalancette 已提交
19747
        virDispatchError(NULL);
19748
        return NULL;
C
Chris Lalancette 已提交
19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760
    }

    conn = domain->conn;

    if (conn->driver->domainSnapshotCurrent) {
        virDomainSnapshotPtr snap;
        snap = conn->driver->domainSnapshotCurrent(domain, flags);
        if (!snap)
            goto error;
        return snap;
    }

19761
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19762 19763 19764 19765 19766
error:
    virDispatchError(conn);
    return NULL;
}

19767

19768 19769 19770
/**
 * virDomainSnapshotGetParent:
 * @snapshot: a snapshot object
19771
 * @flags: extra flags; not used yet, so callers should always pass 0
19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805
 *
 * Get the parent snapshot for @snapshot, if any.
 *
 * Returns a domain snapshot object or NULL in case of failure.  If the
 * given snapshot is a root (no parent), then the VIR_ERR_NO_DOMAIN_SNAPSHOT
 * error is raised.
 */
virDomainSnapshotPtr
virDomainSnapshotGetParent(virDomainSnapshotPtr snapshot,
                           unsigned int flags)
{
    virConnectPtr conn;

    VIR_DEBUG("snapshot=%p, flags=%x", snapshot, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }

    conn = snapshot->domain->conn;

    if (conn->driver->domainSnapshotGetParent) {
        virDomainSnapshotPtr snap;
        snap = conn->driver->domainSnapshotGetParent(snapshot, flags);
        if (!snap)
            goto error;
        return snap;
    }

19806
    virReportUnsupportedError();
19807 19808 19809 19810 19811
error:
    virDispatchError(conn);
    return NULL;
}

19812

E
Eric Blake 已提交
19813 19814 19815 19816 19817 19818 19819 19820 19821 19822
/**
 * virDomainSnapshotIsCurrent:
 * @snapshot: a snapshot object
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Determine if the given snapshot is the domain's current snapshot.  See
 * also virDomainHasCurrentSnapshot().
 *
 * Returns 1 if current, 0 if not current, or -1 on error.
 */
19823 19824 19825
int
virDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot,
                           unsigned int flags)
E
Eric Blake 已提交
19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849
{
    virConnectPtr conn;

    VIR_DEBUG("snapshot=%p, flags=%x", snapshot, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = snapshot->domain->conn;

    if (conn->driver->domainSnapshotIsCurrent) {
        int ret;
        ret = conn->driver->domainSnapshotIsCurrent(snapshot, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19850
    virReportUnsupportedError();
E
Eric Blake 已提交
19851 19852 19853 19854 19855
error:
    virDispatchError(conn);
    return -1;
}

19856

E
Eric Blake 已提交
19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867
/**
 * virDomainSnapshotHasMetadata:
 * @snapshot: a snapshot object
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Determine if the given snapshot is associated with libvirt metadata
 * that would prevent the deletion of the domain.
 *
 * Returns 1 if the snapshot has metadata, 0 if the snapshot exists without
 * help from libvirt, or -1 on error.
 */
19868 19869 19870
int
virDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot,
                             unsigned int flags)
E
Eric Blake 已提交
19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891 19892 19893 19894
{
    virConnectPtr conn;

    VIR_DEBUG("snapshot=%p, flags=%x", snapshot, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = snapshot->domain->conn;

    if (conn->driver->domainSnapshotHasMetadata) {
        int ret;
        ret = conn->driver->domainSnapshotHasMetadata(snapshot, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19895
    virReportUnsupportedError();
E
Eric Blake 已提交
19896 19897 19898 19899 19900
error:
    virDispatchError(conn);
    return -1;
}

19901

C
Chris Lalancette 已提交
19902
/**
19903
 * virDomainRevertToSnapshot:
C
Chris Lalancette 已提交
19904
 * @snapshot: a domain snapshot object
19905
 * @flags: bitwise-OR of virDomainSnapshotRevertFlags
C
Chris Lalancette 已提交
19906 19907 19908
 *
 * Revert the domain to a given snapshot.
 *
19909 19910 19911 19912 19913 19914 19915 19916 19917 19918 19919 19920
 * Normally, the domain will revert to the same state the domain was
 * in while the snapshot was taken (whether inactive, running, or
 * paused), except that disk snapshots default to reverting to
 * inactive state.  Including VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING in
 * @flags overrides the snapshot state to guarantee a running domain
 * after the revert; or including VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED in
 * @flags guarantees a paused domain after the revert.  These two
 * flags are mutually exclusive.  While a persistent domain does not
 * need either flag, it is not possible to revert a transient domain
 * into an inactive state, so transient domains require the use of one
 * of these two flags.
 *
E
Eric Blake 已提交
19921 19922 19923 19924 19925 19926 19927 19928 19929 19930 19931 19932 19933 19934 19935 19936 19937 19938 19939 19940 19941 19942
 * Reverting to any snapshot discards all configuration changes made since
 * the last snapshot.  Additionally, reverting to a snapshot from a running
 * domain is a form of data loss, since it discards whatever is in the
 * guest's RAM at the time.  Since the very nature of keeping snapshots
 * implies the intent to roll back state, no additional confirmation is
 * normally required for these lossy effects.
 *
 * However, there are two particular situations where reverting will
 * be refused by default, and where @flags must include
 * VIR_DOMAIN_SNAPSHOT_REVERT_FORCE to acknowledge the risks.  1) Any
 * attempt to revert to a snapshot that lacks the metadata to perform
 * ABI compatibility checks (generally the case for snapshots that
 * lack a full <domain> when listed by virDomainSnapshotGetXMLDesc(),
 * such as those created prior to libvirt 0.9.5).  2) Any attempt to
 * revert a running domain to an active state that requires starting a
 * new hypervisor instance rather than reusing the existing hypervisor
 * (since this would terminate all connections to the domain, such as
 * such as VNC or Spice graphics) - this condition arises from active
 * snapshots that are provably ABI incomaptible, as well as from
 * inactive snapshots with a @flags request to start the domain after
 * the revert.
 *
C
Chris Lalancette 已提交
19943 19944 19945 19946 19947 19948 19949 19950
 * Returns 0 if the creation is successful, -1 on error.
 */
int
virDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
                          unsigned int flags)
{
    virConnectPtr conn;

19951
    VIR_DEBUG("snapshot=%p, flags=%x", snapshot, flags);
C
Chris Lalancette 已提交
19952 19953 19954 19955

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
19956
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
C
Chris Lalancette 已提交
19957 19958 19959 19960 19961 19962
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = snapshot->domain->conn;
19963
    virCheckReadOnlyGoto(conn->flags, error);
C
Chris Lalancette 已提交
19964

19965 19966
    if ((flags & VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING) &&
        (flags & VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED)) {
19967
        virReportInvalidArg(flags,
19968 19969
                            _("running and paused flags in %s are mutually "
                              "exclusive"),
19970
                            __FUNCTION__);
19971 19972 19973
        goto error;
    }

C
Chris Lalancette 已提交
19974 19975 19976 19977 19978 19979 19980
    if (conn->driver->domainRevertToSnapshot) {
        int ret = conn->driver->domainRevertToSnapshot(snapshot, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

19981
    virReportUnsupportedError();
C
Chris Lalancette 已提交
19982 19983 19984 19985 19986
error:
    virDispatchError(conn);
    return -1;
}

19987

C
Chris Lalancette 已提交
19988
/**
19989
 * virDomainSnapshotDelete:
C
Chris Lalancette 已提交
19990
 * @snapshot: a domain snapshot object
19991
 * @flags: bitwise-OR of supported virDomainSnapshotDeleteFlags
C
Chris Lalancette 已提交
19992 19993 19994
 *
 * Delete the snapshot.
 *
19995 19996 19997 19998 19999 20000 20001 20002 20003 20004 20005 20006 20007
 * If @flags is 0, then just this snapshot is deleted, and changes
 * from this snapshot are automatically merged into children
 * snapshots.  If @flags includes VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN,
 * then this snapshot and any descendant snapshots are deleted.  If
 * @flags includes VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY, then any
 * descendant snapshots are deleted, but this snapshot remains.  These
 * two flags are mutually exclusive.
 *
 * If @flags includes VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, then
 * any snapshot metadata tracked by libvirt is removed while keeping
 * the snapshot contents intact; if a hypervisor does not require any
 * libvirt metadata to track snapshots, then this flag is silently
 * ignored.
C
Chris Lalancette 已提交
20008
 *
20009 20010
 * Returns 0 if the selected snapshot(s) were successfully deleted,
 * -1 on error.
C
Chris Lalancette 已提交
20011 20012 20013 20014 20015 20016 20017
 */
int
virDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                        unsigned int flags)
{
    virConnectPtr conn;

20018
    VIR_DEBUG("snapshot=%p, flags=%x", snapshot, flags);
C
Chris Lalancette 已提交
20019 20020 20021 20022

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
20023
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
C
Chris Lalancette 已提交
20024 20025 20026 20027 20028 20029
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = snapshot->domain->conn;
20030
    virCheckReadOnlyGoto(conn->flags, error);
C
Chris Lalancette 已提交
20031

20032 20033
    if ((flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN) &&
        (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)) {
20034 20035 20036 20037
        virReportInvalidArg(flags,
                            _("children and children_only flags in %s are "
                              "mutually exclusive"),
                            __FUNCTION__);
20038 20039 20040
        goto error;
    }

C
Chris Lalancette 已提交
20041 20042 20043 20044 20045 20046 20047
    if (conn->driver->domainSnapshotDelete) {
        int ret = conn->driver->domainSnapshotDelete(snapshot, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

20048
    virReportUnsupportedError();
C
Chris Lalancette 已提交
20049 20050 20051 20052 20053
error:
    virDispatchError(conn);
    return -1;
}

20054

20055 20056 20057 20058 20059 20060 20061 20062 20063 20064 20065 20066 20067 20068 20069 20070 20071 20072 20073 20074
/**
 * virDomainSnapshotRef:
 * @snapshot: the snapshot to hold a reference on
 *
 * Increment the reference count on the snapshot. For each
 * additional call to this method, there shall be a corresponding
 * call to virDomainSnapshotFree to release the reference count, once
 * the caller no longer needs the reference to this object.
 *
 * This method is typically useful for applications where multiple
 * threads are using a connection, and it is required that the
 * connection and domain remain open until all threads have finished
 * using the snapshot. ie, each new thread using a snapshot would
 * increment the reference count.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainSnapshotRef(virDomainSnapshotPtr snapshot)
{
20075 20076 20077
    VIR_DEBUG("snapshot=%p, refs=%d", snapshot,
              snapshot ? snapshot->object.u.s.refs : 0);

20078 20079
    virResetLastError();

20080 20081 20082 20083 20084 20085
    if ((!VIR_IS_DOMAIN_SNAPSHOT(snapshot))) {
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
20086
    virObjectRef(snapshot);
20087 20088 20089
    return 0;
}

20090

C
Chris Lalancette 已提交
20091 20092 20093 20094 20095 20096 20097 20098 20099 20100 20101 20102
/**
 * virDomainSnapshotFree:
 * @snapshot: a domain snapshot object
 *
 * Free the domain snapshot object.  The snapshot itself is not modified.
 * The data structure is freed and should not be used thereafter.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainSnapshotFree(virDomainSnapshotPtr snapshot)
{
20103
    VIR_DEBUG("snapshot=%p", snapshot);
C
Chris Lalancette 已提交
20104 20105 20106 20107

    virResetLastError();

    if (!VIR_IS_DOMAIN_SNAPSHOT(snapshot)) {
20108
        virLibDomainSnapshotError(VIR_ERR_INVALID_DOMAIN_SNAPSHOT,
C
Chris Lalancette 已提交
20109 20110 20111 20112
                                  __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
20113
    virObjectUnref(snapshot);
C
Chris Lalancette 已提交
20114 20115
    return 0;
}
20116

20117

20118 20119 20120
/**
 * virDomainOpenConsole:
 * @dom: a domain object
20121
 * @dev_name: the console, serial or parallel port device alias, or NULL
20122
 * @st: a stream to associate with the console
20123
 * @flags: bitwise-OR of virDomainConsoleFlags
20124 20125 20126
 *
 * This opens the backend associated with a console, serial or
 * parallel port device on a guest, if the backend is supported.
20127
 * If the @dev_name is omitted, then the first console or serial
20128 20129 20130 20131
 * device is opened. The console is associated with the passed
 * in @st stream, which should have been opened in non-blocking
 * mode for bi-directional I/O.
 *
20132 20133 20134 20135 20136 20137 20138 20139 20140 20141 20142 20143 20144 20145 20146
 * By default, when @flags is 0, the open will fail if libvirt
 * detects that the console is already in use by another client;
 * passing VIR_DOMAIN_CONSOLE_FORCE will cause libvirt to forcefully
 * remove the other client prior to opening this console.
 *
 * If flag VIR_DOMAIN_CONSOLE_SAFE the console is opened only in the
 * case where the hypervisor driver supports safe (mutually exclusive)
 * console handling.
 *
 * Older servers did not support either flag, and also did not forbid
 * simultaneous clients on a console, with potentially confusing results.
 * When passing @flags of 0 in order to support a wider range of server
 * versions, it is up to the client to ensure mutual exclusion.
 *
 * Returns 0 if the console was opened, -1 on error
20147
 */
20148 20149 20150 20151 20152
int
virDomainOpenConsole(virDomainPtr dom,
                     const char *dev_name,
                     virStreamPtr st,
                     unsigned int flags)
20153 20154
{
    virConnectPtr conn;
20155

20156 20157
    VIR_DOMAIN_DEBUG(dom, "dev_name=%s, st=%p, flags=%x",
                     NULLSTR(dev_name), st, flags);
20158 20159 20160 20161

    virResetLastError();

    if (!VIR_IS_DOMAIN(dom)) {
20162
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
20163 20164 20165 20166 20167
        virDispatchError(NULL);
        return -1;
    }

    conn = dom->conn;
20168
    virCheckReadOnlyGoto(conn->flags, error);
20169 20170 20171

    if (conn->driver->domainOpenConsole) {
        int ret;
20172
        ret = conn->driver->domainOpenConsole(dom, dev_name, st, flags);
20173 20174 20175 20176 20177
        if (ret < 0)
            goto error;
        return ret;
    }

20178
    virReportUnsupportedError();
20179 20180 20181 20182 20183

error:
    virDispatchError(conn);
    return -1;
}
20184

20185

20186 20187 20188 20189 20190 20191 20192 20193 20194 20195 20196 20197 20198 20199 20200 20201 20202 20203 20204 20205 20206 20207
/**
 * virDomainOpenChannel:
 * @dom: a domain object
 * @name: the channel name, or NULL
 * @st: a stream to associate with the channel
 * @flags: bitwise-OR of virDomainChannelFlags
 *
 * This opens the host interface associated with a channel device on a
 * guest, if the host interface is supported.  If @name is given, it
 * can match either the device alias (e.g. "channel0"), or the virtio
 * target name (e.g. "org.qemu.guest_agent.0").  If @name is omitted,
 * then the first channel is opened. The channel is associated with
 * the passed in @st stream, which should have been opened in
 * non-blocking mode for bi-directional I/O.
 *
 * By default, when @flags is 0, the open will fail if libvirt detects
 * that the channel is already in use by another client; passing
 * VIR_DOMAIN_CHANNEL_FORCE will cause libvirt to forcefully remove the
 * other client prior to opening this channel.
 *
 * Returns 0 if the channel was opened, -1 on error
 */
20208 20209 20210 20211 20212
int
virDomainOpenChannel(virDomainPtr dom,
                     const char *name,
                     virStreamPtr st,
                     unsigned int flags)
20213 20214 20215 20216 20217 20218 20219 20220 20221 20222 20223 20224 20225 20226 20227
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(dom, "name=%s, st=%p, flags=%x",
                     NULLSTR(name), st, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = dom->conn;
20228
    virCheckReadOnlyGoto(conn->flags, error);
20229 20230 20231 20232 20233 20234 20235 20236 20237

    if (conn->driver->domainOpenChannel) {
        int ret;
        ret = conn->driver->domainOpenChannel(dom, name, st, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

20238
    virReportUnsupportedError();
20239 20240 20241 20242 20243 20244

error:
    virDispatchError(conn);
    return -1;
}

20245

20246 20247 20248
/**
 * virDomainBlockJobAbort:
 * @dom: pointer to domain object
20249
 * @disk: path to the block device, or device shorthand
20250
 * @flags: bitwise-OR of virDomainBlockJobAbortFlags
20251 20252 20253
 *
 * Cancel the active block job on the given disk.
 *
20254
 * The @disk parameter is either an unambiguous source name of the
20255 20256 20257 20258 20259 20260
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or (since 0.9.5) the device target shorthand
 * (the <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
E
Eric Blake 已提交
20261 20262
 * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, then
 * by default, this function performs a synchronous operation and the caller
20263 20264 20265 20266 20267 20268 20269 20270
 * may assume that the operation has completed when 0 is returned.  However,
 * BlockJob operations may take a long time to cancel, and during this time
 * further domain interactions may be unresponsive.  To avoid this problem,
 * pass VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC in the @flags argument to enable
 * asynchronous behavior, returning as soon as possible.  When the job has
 * been canceled, a BlockJob event will be emitted, with status
 * VIR_DOMAIN_BLOCK_JOB_CANCELED (even if the ABORT_ASYNC flag was not
 * used); it is also possible to poll virDomainBlockJobInfo() to see if
E
Eric Blake 已提交
20271 20272 20273 20274 20275 20276 20277 20278 20279 20280 20281 20282
 * the job cancellation is still pending.  This type of job can be restarted
 * to pick up from where it left off.
 *
 * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_COPY, then
 * the default is to abort the mirroring and revert to the source disk;
 * adding @flags of VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT causes this call to
 * fail with VIR_ERR_BLOCK_COPY_ACTIVE if the copy is not fully populated,
 * otherwise it will swap the disk over to the copy to end the mirroring.  An
 * event will be issued when the job is ended, and it is possible to use
 * VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC to control whether this command waits
 * for the completion of the job.  Restarting this job requires starting
 * over from the beginning of the first phase.
20283
 *
20284 20285
 * Returns -1 in case of failure, 0 when successful.
 */
20286 20287 20288
int
virDomainBlockJobAbort(virDomainPtr dom, const char *disk,
                       unsigned int flags)
20289 20290 20291
{
    virConnectPtr conn;

20292
    VIR_DOMAIN_DEBUG(dom, "disk=%s, flags=%x", disk, flags);
20293 20294 20295

    virResetLastError();

20296
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
20297 20298 20299 20300 20301 20302
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = dom->conn;

20303
    virCheckReadOnlyGoto(dom->conn->flags, error);
20304

20305
    virCheckNonNullArgGoto(disk, error);
20306 20307 20308

    if (conn->driver->domainBlockJobAbort) {
        int ret;
20309
        ret = conn->driver->domainBlockJobAbort(dom, disk, flags);
20310 20311 20312 20313 20314
        if (ret < 0)
            goto error;
        return ret;
    }

20315
    virReportUnsupportedError();
20316 20317 20318 20319 20320 20321

error:
    virDispatchError(dom->conn);
    return -1;
}

20322

20323 20324 20325
/**
 * virDomainGetBlockJobInfo:
 * @dom: pointer to domain object
20326
 * @disk: path to the block device, or device shorthand
20327
 * @info: pointer to a virDomainBlockJobInfo structure
20328
 * @flags: extra flags; not used yet, so callers should always pass 0
20329 20330 20331 20332
 *
 * Request block job information for the given disk.  If an operation is active
 * @info will be updated with the current progress.
 *
20333
 * The @disk parameter is either an unambiguous source name of the
20334 20335 20336 20337 20338 20339
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or (since 0.9.5) the device target shorthand
 * (the <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
20340 20341
 * Returns -1 in case of failure, 0 when nothing found, 1 when info was found.
 */
20342 20343 20344
int
virDomainGetBlockJobInfo(virDomainPtr dom, const char *disk,
                         virDomainBlockJobInfoPtr info, unsigned int flags)
20345 20346 20347
{
    virConnectPtr conn;

20348
    VIR_DOMAIN_DEBUG(dom, "disk=%s, info=%p, flags=%x", disk, info, flags);
20349 20350 20351

    virResetLastError();

20352
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
20353 20354 20355 20356 20357 20358
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = dom->conn;

20359 20360
    virCheckNonNullArgGoto(disk, error);
    virCheckNonNullArgGoto(info, error);
20361

20362 20363
    memset(info, 0, sizeof(*info));

20364 20365
    if (conn->driver->domainGetBlockJobInfo) {
        int ret;
20366
        ret = conn->driver->domainGetBlockJobInfo(dom, disk, info, flags);
20367 20368 20369 20370 20371
        if (ret < 0)
            goto error;
        return ret;
    }

20372
    virReportUnsupportedError();
20373 20374 20375 20376 20377 20378

error:
    virDispatchError(dom->conn);
    return -1;
}

20379

20380 20381 20382
/**
 * virDomainBlockJobSetSpeed:
 * @dom: pointer to domain object
20383
 * @disk: path to the block device, or device shorthand
20384
 * @bandwidth: specify bandwidth limit in MiB/s
20385
 * @flags: extra flags; not used yet, so callers should always pass 0
20386 20387 20388 20389
 *
 * Set the maximimum allowable bandwidth that a block job may consume.  If
 * bandwidth is 0, the limit will revert to the hypervisor default.
 *
20390
 * The @disk parameter is either an unambiguous source name of the
20391 20392 20393 20394 20395 20396
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or (since 0.9.5) the device target shorthand
 * (the <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
20397 20398
 * Returns -1 in case of failure, 0 when successful.
 */
20399 20400 20401
int
virDomainBlockJobSetSpeed(virDomainPtr dom, const char *disk,
                          unsigned long bandwidth, unsigned int flags)
20402 20403 20404
{
    virConnectPtr conn;

20405
    VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=%x",
20406
                     disk, bandwidth, flags);
20407 20408 20409

    virResetLastError();

20410
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
20411 20412 20413 20414 20415 20416
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = dom->conn;

20417
    virCheckReadOnlyGoto(dom->conn->flags, error);
20418

20419
    virCheckNonNullArgGoto(disk, error);
20420 20421 20422

    if (conn->driver->domainBlockJobSetSpeed) {
        int ret;
20423
        ret = conn->driver->domainBlockJobSetSpeed(dom, disk, bandwidth, flags);
20424 20425 20426 20427 20428
        if (ret < 0)
            goto error;
        return ret;
    }

20429
    virReportUnsupportedError();
20430 20431 20432 20433 20434 20435

error:
    virDispatchError(dom->conn);
    return -1;
}

20436

20437 20438 20439
/**
 * virDomainBlockPull:
 * @dom: pointer to domain object
20440
 * @disk: path to the block device, or device shorthand
20441
 * @bandwidth: (optional) specify copy bandwidth limit in MiB/s
20442
 * @flags: extra flags; not used yet, so callers should always pass 0
20443 20444 20445 20446 20447 20448
 *
 * Populate a disk image with data from its backing image.  Once all data from
 * its backing image has been pulled, the disk no longer depends on a backing
 * image.  This function pulls data for the entire device in the background.
 * Progress of the operation can be checked with virDomainGetBlockJobInfo() and
 * the operation can be aborted with virDomainBlockJobAbort().  When finished,
E
Eric Blake 已提交
20449 20450
 * an asynchronous event is raised to indicate the final status.  To move
 * data in the opposite direction, see virDomainBlockCommit().
20451
 *
20452
 * The @disk parameter is either an unambiguous source name of the
20453 20454 20455 20456 20457 20458
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or (since 0.9.5) the device target shorthand
 * (the <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
20459
 * The maximum bandwidth (in MiB/s) that will be used to do the copy can be
20460 20461
 * specified with the bandwidth parameter.  If set to 0, libvirt will choose a
 * suitable default.  Some hypervisors do not support this feature and will
20462 20463 20464
 * return an error if bandwidth is not 0; in this case, it might still be
 * possible for a later call to virDomainBlockJobSetSpeed() to succeed.
 * The actual speed can be determined with virDomainGetBlockJobInfo().
20465
 *
20466 20467
 * This is shorthand for virDomainBlockRebase() with a NULL base.
 *
20468 20469
 * Returns 0 if the operation has started, -1 on failure.
 */
20470 20471 20472
int
virDomainBlockPull(virDomainPtr dom, const char *disk,
                   unsigned long bandwidth, unsigned int flags)
20473 20474 20475
{
    virConnectPtr conn;

20476
    VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=%x",
20477
                     disk, bandwidth, flags);
20478 20479 20480

    virResetLastError();

20481
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
20482 20483 20484 20485 20486 20487
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = dom->conn;

20488
    virCheckReadOnlyGoto(dom->conn->flags, error);
20489

20490
    virCheckNonNullArgGoto(disk, error);
20491 20492 20493

    if (conn->driver->domainBlockPull) {
        int ret;
20494
        ret = conn->driver->domainBlockPull(dom, disk, bandwidth, flags);
20495 20496 20497 20498 20499
        if (ret < 0)
            goto error;
        return ret;
    }

20500
    virReportUnsupportedError();
20501 20502 20503 20504 20505

error:
    virDispatchError(dom->conn);
    return -1;
}
20506 20507


20508 20509 20510 20511 20512
/**
 * virDomainBlockRebase:
 * @dom: pointer to domain object
 * @disk: path to the block device, or device shorthand
 * @base: path to backing file to keep, or NULL for no backing file
20513
 * @bandwidth: (optional) specify copy bandwidth limit in MiB/s
E
Eric Blake 已提交
20514
 * @flags: bitwise-OR of virDomainBlockRebaseFlags
20515 20516
 *
 * Populate a disk image with data from its backing image chain, and
E
Eric Blake 已提交
20517 20518 20519 20520
 * setting the backing image to @base, or alternatively copy an entire
 * backing chain to a new file @base.
 *
 * When @flags is 0, this starts a pull, where @base must be the absolute
20521 20522 20523 20524 20525
 * path of one of the backing images further up the chain, or NULL to
 * convert the disk image so that it has no backing image.  Once all
 * data from its backing image chain has been pulled, the disk no
 * longer depends on those intermediate backing images.  This function
 * pulls data for the entire device in the background.  Progress of
E
Eric Blake 已提交
20526 20527 20528 20529 20530 20531 20532 20533 20534 20535 20536 20537 20538 20539 20540 20541 20542 20543 20544 20545 20546 20547 20548 20549 20550 20551 20552 20553 20554 20555 20556 20557
 * the operation can be checked with virDomainGetBlockJobInfo() with a
 * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, and the operation can be
 * aborted with virDomainBlockJobAbort().  When finished, an asynchronous
 * event is raised to indicate the final status, and the job no longer
 * exists.  If the job is aborted, a new one can be started later to
 * resume from the same point.
 *
 * When @flags includes VIR_DOMAIN_BLOCK_REBASE_COPY, this starts a copy,
 * where @base must be the name of a new file to copy the chain to.  By
 * default, the copy will pull the entire source chain into the destination
 * file, but if @flags also contains VIR_DOMAIN_BLOCK_REBASE_SHALLOW, then
 * only the top of the source chain will be copied (the source and
 * destination have a common backing file).  By default, @base will be
 * created with the same file format as the source, but this can be altered
 * by adding VIR_DOMAIN_BLOCK_REBASE_COPY_RAW to force the copy to be raw
 * (does not make sense with the shallow flag unless the source is also raw),
 * or by using VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT to reuse an existing file
 * with initial contents identical to the backing file of the source (this
 * allows a management app to pre-create files with relative backing file
 * names, rather than the default of absolute backing file names; as a
 * security precaution, you should generally only use reuse_ext with the
 * shallow flag and a non-raw destination file).
 *
 * A copy job has two parts; in the first phase, the @bandwidth parameter
 * affects how fast the source is pulled into the destination, and the job
 * can only be canceled by reverting to the source file; progress in this
 * phase can be tracked via the virDomainBlockJobInfo() command, with a
 * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_COPY.  The job transitions to the
 * second phase when the job info states cur == end, and remains alive to
 * mirror all further changes to both source and destination.  The user
 * must call virDomainBlockJobAbort() to end the mirroring while choosing
 * whether to revert to source or pivot to the destination.  An event is
20558 20559 20560 20561
 * issued when the job ends, and depending on the hypervisor, an event may
 * also be issued when the job transitions from pulling to mirroring.  If
 * the job is aborted, a new job will have to start over from the beginning
 * of the first phase.
E
Eric Blake 已提交
20562 20563 20564 20565
 *
 * Some hypervisors will restrict certain actions, such as virDomainSave()
 * or virDomainDetachDevice(), while a copy job is active; they may
 * also restrict a copy job to transient domains.
20566 20567 20568 20569 20570 20571 20572 20573
 *
 * The @disk parameter is either an unambiguous source name of the
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or the device target shorthand (the
 * <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
20574
 * The maximum bandwidth (in MiB/s) that will be used to do the copy can be
20575 20576
 * specified with the bandwidth parameter.  If set to 0, libvirt will choose a
 * suitable default.  Some hypervisors do not support this feature and will
20577 20578 20579
 * return an error if bandwidth is not 0; in this case, it might still be
 * possible for a later call to virDomainBlockJobSetSpeed() to succeed.
 * The actual speed can be determined with virDomainGetBlockJobInfo().
20580
 *
E
Eric Blake 已提交
20581 20582
 * When @base is NULL and @flags is 0, this is identical to
 * virDomainBlockPull().
20583 20584 20585
 *
 * Returns 0 if the operation has started, -1 on failure.
 */
20586 20587 20588 20589
int
virDomainBlockRebase(virDomainPtr dom, const char *disk,
                     const char *base, unsigned long bandwidth,
                     unsigned int flags)
20590 20591 20592
{
    virConnectPtr conn;

E
Eric Blake 已提交
20593
    VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, bandwidth=%lu, flags=%x",
20594 20595 20596 20597
                     disk, NULLSTR(base), bandwidth, flags);

    virResetLastError();

20598
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
20599 20600 20601 20602 20603 20604
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = dom->conn;

20605
    virCheckReadOnlyGoto(dom->conn->flags, error);
20606

20607
    virCheckNonNullArgGoto(disk, error);
20608

E
Eric Blake 已提交
20609
    if (flags & VIR_DOMAIN_BLOCK_REBASE_COPY) {
20610
        virCheckNonNullArgGoto(base, error);
E
Eric Blake 已提交
20611 20612 20613
    } else if (flags & (VIR_DOMAIN_BLOCK_REBASE_SHALLOW |
                        VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT |
                        VIR_DOMAIN_BLOCK_REBASE_COPY_RAW)) {
20614 20615 20616
        virReportInvalidArg(flags,
                            _("use of flags in %s requires a copy job"),
                            __FUNCTION__);
E
Eric Blake 已提交
20617 20618 20619
        goto error;
    }

20620 20621 20622 20623 20624 20625 20626 20627 20628
    if (conn->driver->domainBlockRebase) {
        int ret;
        ret = conn->driver->domainBlockRebase(dom, disk, base, bandwidth,
                                              flags);
        if (ret < 0)
            goto error;
        return ret;
    }

20629
    virReportUnsupportedError();
20630 20631 20632 20633 20634 20635 20636

error:
    virDispatchError(dom->conn);
    return -1;
}


E
Eric Blake 已提交
20637 20638 20639 20640 20641 20642 20643 20644 20645 20646 20647 20648 20649 20650 20651 20652 20653 20654 20655 20656 20657 20658 20659 20660 20661 20662 20663 20664 20665 20666 20667 20668 20669 20670 20671 20672 20673 20674 20675 20676 20677 20678 20679 20680 20681 20682 20683 20684 20685 20686 20687 20688 20689 20690 20691 20692 20693 20694 20695 20696 20697 20698 20699 20700 20701
/**
 * virDomainBlockCommit:
 * @dom: pointer to domain object
 * @disk: path to the block device, or device shorthand
 * @base: path to backing file to merge into, or NULL for default
 * @top: path to file within backing chain that contains data to be merged,
 *       or NULL to merge all possible data
 * @bandwidth: (optional) specify commit bandwidth limit in MiB/s
 * @flags: bitwise-OR of virDomainBlockCommitFlags
 *
 * Commit changes that were made to temporary top-level files within a disk
 * image backing file chain into a lower-level base file.  In other words,
 * take all the difference between @base and @top, and update @base to contain
 * that difference; after the commit, any portion of the chain that previously
 * depended on @top will now depend on @base, and all files after @base up
 * to and including @top will now be invalidated.  A typical use of this
 * command is to reduce the length of a backing file chain after taking an
 * external disk snapshot.  To move data in the opposite direction, see
 * virDomainBlockPull().
 *
 * This command starts a long-running commit block job, whose status may
 * be tracked by virDomainBlockJobInfo() with a job type of
 * VIR_DOMAIN_BLOCK_JOB_TYPE_COMMIT, and the operation can be aborted with
 * virDomainBlockJobAbort().  When finished, an asynchronous event is
 * raised to indicate the final status, and the job no longer exists.  If
 * the job is aborted, it is up to the hypervisor whether starting a new
 * job will resume from the same point, or start over.
 *
 * Be aware that this command may invalidate files even if it is aborted;
 * the user is cautioned against relying on the contents of invalidated
 * intermediate files such as @top without manually rebasing those files
 * to use a backing file of a read-only copy of @base prior to the point
 * where the commit operation was started (although such a rebase cannot
 * be safely done until the commit has successfully completed).  However,
 * the domain itself will not have any issues; the active layer remains
 * valid throughout the entire commit operation.  As a convenience,
 * if @flags contains VIR_DOMAIN_BLOCK_COMMIT_DELETE, this command will
 * unlink all files that were invalidated, after the commit successfully
 * completes.
 *
 * By default, if @base is NULL, the commit target will be the bottom of
 * the backing chain; if @flags contains VIR_DOMAIN_BLOCK_COMMIT_SHALLOW,
 * then the immediate backing file of @top will be used instead.  If @top
 * is NULL, the active image at the top of the chain will be used.  Some
 * hypervisors place restrictions on how much can be committed, and might
 * fail if @base is not the immediate backing file of @top, or if @top is
 * the active layer in use by a running domain, or if @top is not the
 * top-most file; restrictions may differ for online vs. offline domains.
 *
 * The @disk parameter is either an unambiguous source name of the
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or the device target shorthand (the
 * <target dev='...'/> sub-element, such as "xvda").  Valid names
 * can be found by calling virDomainGetXMLDesc() and inspecting
 * elements within //domain/devices/disk.
 *
 * The maximum bandwidth (in MiB/s) that will be used to do the commit can be
 * specified with the bandwidth parameter.  If set to 0, libvirt will choose a
 * suitable default.  Some hypervisors do not support this feature and will
 * return an error if bandwidth is not 0; in this case, it might still be
 * possible for a later call to virDomainBlockJobSetSpeed() to succeed.
 * The actual speed can be determined with virDomainGetBlockJobInfo().
 *
 * Returns 0 if the operation has started, -1 on failure.
 */
20702 20703 20704 20705
int
virDomainBlockCommit(virDomainPtr dom, const char *disk,
                     const char *base, const char *top,
                     unsigned long bandwidth, unsigned int flags)
E
Eric Blake 已提交
20706 20707 20708 20709 20710 20711 20712 20713 20714 20715 20716 20717 20718 20719 20720
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, top=%s, bandwidth=%lu, flags=%x",
                     disk, NULLSTR(base), NULLSTR(top), bandwidth, flags);

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }
    conn = dom->conn;

20721
    virCheckReadOnlyGoto(dom->conn->flags, error);
E
Eric Blake 已提交
20722 20723 20724 20725 20726 20727 20728 20729 20730 20731 20732 20733

    virCheckNonNullArgGoto(disk, error);

    if (conn->driver->domainBlockCommit) {
        int ret;
        ret = conn->driver->domainBlockCommit(dom, disk, base, top, bandwidth,
                                              flags);
        if (ret < 0)
            goto error;
        return ret;
    }

20734
    virReportUnsupportedError();
E
Eric Blake 已提交
20735 20736 20737 20738 20739 20740 20741

error:
    virDispatchError(dom->conn);
    return -1;
}


20742 20743 20744 20745 20746
/**
 * virDomainOpenGraphics:
 * @dom: pointer to domain object
 * @idx: index of graphics config to open
 * @fd: file descriptor to attach graphics to
20747
 * @flags: bitwise-OR of virDomainOpenGraphicsFlags
20748 20749 20750 20751 20752 20753 20754 20755 20756 20757 20758 20759 20760 20761 20762 20763 20764 20765
 *
 * This will attempt to connect the file descriptor @fd, to
 * the graphics backend of @dom. If @dom has multiple graphics
 * backends configured, then @idx will determine which one is
 * opened, starting from @idx 0.
 *
 * To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH
 * constant for @flags.
 *
 * The caller should use an anonymous socketpair to open
 * @fd before invocation.
 *
 * This method can only be used when connected to a local
 * libvirt hypervisor, over a UNIX domain socket. Attempts
 * to use this method over a TCP connection will always fail
 *
 * Returns 0 on success, -1 on failure
 */
20766 20767 20768 20769 20770
int
virDomainOpenGraphics(virDomainPtr dom,
                      unsigned int idx,
                      int fd,
                      unsigned int flags)
20771 20772 20773 20774 20775 20776 20777 20778 20779 20780 20781 20782 20783
{
    struct stat sb;
    VIR_DOMAIN_DEBUG(dom, "idx=%u, fd=%d, flags=%x",
                     idx, fd, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

20784
    virCheckNonNegativeArgGoto(fd, error);
20785 20786 20787 20788 20789 20790 20791 20792

    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
                             _("Unable to access file descriptor %d"), fd);
        goto error;
    }

    if (!S_ISSOCK(sb.st_mode)) {
20793 20794 20795
        virReportInvalidArg(fd,
                          _("fd %d in %s must be a socket"),
                            fd, __FUNCTION__);
20796 20797 20798
        goto error;
    }

20799
    virCheckReadOnlyGoto(dom->conn->flags, error);
20800 20801 20802

    if (!VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn,
                                  VIR_DRV_FEATURE_FD_PASSING)) {
20803 20804
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("fd passing is not supported by this connection"));
20805 20806 20807 20808 20809 20810 20811 20812 20813 20814 20815
        goto error;
    }

    if (dom->conn->driver->domainOpenGraphics) {
        int ret;
        ret = dom->conn->driver->domainOpenGraphics(dom, idx, fd, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

20816
    virReportUnsupportedError();
20817 20818 20819 20820 20821

error:
    virDispatchError(dom->conn);
    return -1;
}
J
Jiri Denemark 已提交
20822 20823 20824 20825 20826 20827 20828 20829


/**
 * virConnectSetKeepAlive:
 * @conn: pointer to a hypervisor connection
 * @interval: number of seconds of inactivity before a keepalive message is sent
 * @count: number of messages that can be sent in a row
 *
E
Eric Blake 已提交
20830
 * Start sending keepalive messages after @interval seconds of inactivity and
J
Jiri Denemark 已提交
20831
 * consider the connection to be broken when no response is received after
E
Eric Blake 已提交
20832 20833 20834 20835 20836 20837 20838 20839 20840 20841
 * @count keepalive messages sent in a row.  In other words, sending count + 1
 * keepalive message results in closing the connection.  When @interval is
 * <= 0, no keepalive messages will be sent.  When @count is 0, the connection
 * will be automatically closed after @interval seconds of inactivity without
 * sending any keepalive messages.
 *
 * Note: The client has to implement and run an event loop with
 * virEventRegisterImpl() or virEventRegisterDefaultImpl() to be able to
 * use keepalive messages.  Failure to do so may result in connections
 * being closed unexpectedly.
J
Jiri Denemark 已提交
20842
 *
20843 20844 20845 20846
 * Note: This API function controls only keepalive messages sent by the client.
 * If the server is configured to use keepalive you still need to run the event
 * loop to respond to them, even if you disable keepalives by this function.
 *
J
Jiri Denemark 已提交
20847 20848 20849
 * Returns -1 on error, 0 on success, 1 when remote party doesn't support
 * keepalive messages.
 */
20850 20851 20852 20853
int
virConnectSetKeepAlive(virConnectPtr conn,
                       int interval,
                       unsigned int count)
J
Jiri Denemark 已提交
20854 20855 20856 20857 20858 20859 20860
{
    int ret = -1;

    VIR_DEBUG("conn=%p, interval=%d, count=%u", conn, interval, count);

    virResetLastError();

20861
    virCheckConnectReturn(conn, -1);
J
Jiri Denemark 已提交
20862

20863 20864
    if (conn->driver->connectSetKeepAlive) {
        ret = conn->driver->connectSetKeepAlive(conn, interval, count);
J
Jiri Denemark 已提交
20865 20866 20867 20868 20869
        if (ret < 0)
            goto error;
        return ret;
    }

20870
    virReportUnsupportedError();
J
Jiri Denemark 已提交
20871 20872 20873 20874 20875

error:
    virDispatchError(conn);
    return -1;
}
J
Jiri Denemark 已提交
20876

20877

J
Jiri Denemark 已提交
20878 20879 20880 20881 20882 20883 20884 20885 20886 20887 20888
/**
 * virConnectIsAlive:
 * @conn: pointer to the connection object
 *
 * Determine if the connection to the hypervisor is still alive
 *
 * A connection will be classed as alive if it is either local, or running
 * over a channel (TCP or UNIX socket) which is not closed.
 *
 * Returns 1 if alive, 0 if dead, -1 on error
 */
20889 20890
int
virConnectIsAlive(virConnectPtr conn)
J
Jiri Denemark 已提交
20891 20892 20893 20894 20895
{
    VIR_DEBUG("conn=%p", conn);

    virResetLastError();

20896
    virCheckConnectReturn(conn, -1);
20897
    if (conn->driver->connectIsAlive) {
J
Jiri Denemark 已提交
20898
        int ret;
20899
        ret = conn->driver->connectIsAlive(conn);
J
Jiri Denemark 已提交
20900 20901 20902 20903 20904
        if (ret < 0)
            goto error;
        return ret;
    }

20905
    virReportUnsupportedError();
J
Jiri Denemark 已提交
20906 20907 20908 20909
error:
    virDispatchError(conn);
    return -1;
}
20910 20911


20912 20913 20914 20915 20916 20917 20918 20919 20920 20921 20922 20923 20924 20925 20926 20927 20928 20929 20930 20931 20932 20933 20934
/**
 * virConnectRegisterCloseCallback:
 * @conn: pointer to connection object
 * @cb: callback to invoke upon close
 * @opaque: user data to pass to @cb
 * @freecb: callback to free @opaque
 *
 * Registers a callback to be invoked when the connection
 * is closed. This callback is invoked when there is any
 * condition that causes the socket connection to the
 * hypervisor to be closed.
 *
 * This function is only applicable to hypervisor drivers
 * which maintain a persistent open connection. Drivers
 * which open a new connection for every operation will
 * not invoke this.
 *
 * The @freecb must not invoke any other libvirt public
 * APIs, since it is not called from a re-entrant safe
 * context.
 *
 * Returns 0 on success, -1 on error
 */
20935 20936 20937 20938 20939
int
virConnectRegisterCloseCallback(virConnectPtr conn,
                                virConnectCloseFunc cb,
                                void *opaque,
                                virFreeCallback freecb)
20940 20941 20942 20943 20944
{
    VIR_DEBUG("conn=%p", conn);

    virResetLastError();

20945
    virCheckConnectReturn(conn, -1);
20946

20947 20948
    virObjectRef(conn);

20949
    virMutexLock(&conn->lock);
20950
    virObjectLock(conn->closeCallback);
20951 20952 20953

    virCheckNonNullArgGoto(cb, error);

20954
    if (conn->closeCallback->callback) {
20955 20956 20957 20958 20959
        virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("A close callback is already registered"));
        goto error;
    }

20960
    conn->closeCallback->conn = conn;
20961 20962 20963
    conn->closeCallback->callback = cb;
    conn->closeCallback->opaque = opaque;
    conn->closeCallback->freeCallback = freecb;
20964

20965
    virObjectUnlock(conn->closeCallback);
20966 20967 20968 20969 20970
    virMutexUnlock(&conn->lock);

    return 0;

error:
20971
    virDispatchError(conn);
20972
    virObjectUnlock(conn->closeCallback);
20973
    virMutexUnlock(&conn->lock);
20974
    virObjectUnref(conn);
20975 20976 20977
    return -1;
}

20978

20979 20980 20981 20982 20983 20984 20985 20986 20987 20988 20989 20990 20991
/**
 * virConnectUnregisterCloseCallback:
 * @conn: pointer to connection object
 * @cb: pointer to the current registered callback
 *
 * Unregisters the callback previously set with the
 * virConnectRegisterCloseCallback method. The callback
 * will no longer receive notifications when the connection
 * closes. If a virFreeCallback was provided at time of
 * registration, it will be invoked
 *
 * Returns 0 on success, -1 on error
 */
20992 20993 20994
int
virConnectUnregisterCloseCallback(virConnectPtr conn,
                                  virConnectCloseFunc cb)
20995 20996 20997 20998 20999
{
    VIR_DEBUG("conn=%p", conn);

    virResetLastError();

21000
    virCheckConnectReturn(conn, -1);
21001 21002

    virMutexLock(&conn->lock);
21003
    virObjectLock(conn->closeCallback);
21004 21005 21006

    virCheckNonNullArgGoto(cb, error);

21007
    if (conn->closeCallback->callback != cb) {
21008 21009 21010 21011 21012
        virLibConnError(VIR_ERR_OPERATION_INVALID, "%s",
                        _("A different callback was requested"));
        goto error;
    }

21013 21014 21015 21016
    conn->closeCallback->callback = NULL;
    if (conn->closeCallback->freeCallback)
        conn->closeCallback->freeCallback(conn->closeCallback->opaque);
    conn->closeCallback->freeCallback = NULL;
21017

21018
    virObjectUnref(conn);
21019 21020
    virObjectUnlock(conn->closeCallback);
    virMutexUnlock(&conn->lock);
21021

21022 21023 21024
    return 0;

error:
21025
    virDispatchError(conn);
21026
    virObjectUnlock(conn->closeCallback);
21027 21028 21029 21030
    virMutexUnlock(&conn->lock);
    return -1;
}

21031

21032 21033 21034 21035 21036 21037 21038
/**
 * virDomainSetBlockIoTune:
 * @dom: pointer to domain object
 * @disk: path to the block device, or device shorthand
 * @params: Pointer to blkio parameter objects
 * @nparams: Number of blkio parameters (this value can be the same or
 *           less than the number of parameters supported)
21039
 * @flags: bitwise-OR of virDomainModificationImpact
21040 21041 21042 21043 21044 21045 21046 21047 21048 21049 21050 21051
 *
 * Change all or a subset of the per-device block IO tunables.
 *
 * The @disk parameter is either an unambiguous source name of the
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or the device target shorthand (the <target
 * dev='...'/> sub-element, such as "xvda").  Valid names can be found
 * by calling virDomainGetXMLDesc() and inspecting elements
 * within //domain/devices/disk.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
21052 21053 21054 21055 21056 21057
int
virDomainSetBlockIoTune(virDomainPtr dom,
                        const char *disk,
                        virTypedParameterPtr params,
                        int nparams,
                        unsigned int flags)
21058 21059 21060
{
    virConnectPtr conn;

21061
    VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x",
21062
                     disk, params, nparams, flags);
21063
    VIR_TYPED_PARAMS_DEBUG(params, nparams);
21064 21065 21066 21067 21068 21069 21070 21071 21072

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

21073
    virCheckReadOnlyGoto(dom->conn->flags, error);
21074

21075 21076 21077
    virCheckNonNullArgGoto(disk, error);
    virCheckPositiveArgGoto(nparams, error);
    virCheckNonNullArgGoto(params, error);
21078

21079
    if (virTypedParameterValidateSet(dom->conn, params, nparams) < 0)
21080
        goto error;
21081 21082 21083 21084 21085 21086 21087 21088 21089 21090 21091

    conn = dom->conn;

    if (conn->driver->domainSetBlockIoTune) {
        int ret;
        ret = conn->driver->domainSetBlockIoTune(dom, disk, params, nparams, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

21092
    virReportUnsupportedError();
21093 21094 21095 21096 21097 21098

error:
    virDispatchError(dom->conn);
    return -1;
}

21099

21100 21101 21102 21103 21104 21105 21106
/**
 * virDomainGetBlockIoTune:
 * @dom: pointer to domain object
 * @disk: path to the block device, or device shorthand
 * @params: Pointer to blkio parameter object
 *          (return value, allocated by the caller)
 * @nparams: Pointer to number of blkio parameters
21107
 * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
21108 21109 21110 21111 21112 21113 21114 21115 21116 21117 21118 21119 21120 21121 21122 21123 21124 21125 21126 21127 21128 21129 21130 21131 21132
 *
 * Get all block IO tunable parameters for a given device.  On input,
 * @nparams gives the size of the @params array; on output, @nparams
 * gives how many slots were filled with parameter information, which
 * might be less but will not exceed the input value.
 *
 * As a special case, calling with @params as NULL and @nparams as 0
 * on input will cause @nparams on output to contain the number of
 * parameters supported by the hypervisor, either for the given @disk
 * (note that block devices of different types might support different
 * parameters), or if @disk is NULL, for all possible disks. The
 * caller should then allocate @params array,
 * i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
 * again.  See virDomainGetMemoryParameters() for more details.
 *
 * The @disk parameter is either an unambiguous source name of the
 * block device (the <source file='...'/> sub-element, such as
 * "/path/to/image"), or the device target shorthand (the <target
 * dev='...'/> sub-element, such as "xvda").  Valid names can be found
 * by calling virDomainGetXMLDesc() and inspecting elements
 * within //domain/devices/disk.  This parameter cannot be NULL
 * unless @nparams is 0 on input.
 *
 * Returns -1 in case of error, 0 in case of success.
 */
21133 21134 21135 21136 21137 21138
int
virDomainGetBlockIoTune(virDomainPtr dom,
                        const char *disk,
                        virTypedParameterPtr params,
                        int *nparams,
                        unsigned int flags)
21139 21140 21141
{
    virConnectPtr conn;

21142
    VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x",
21143 21144 21145 21146
                     NULLSTR(disk), params, (nparams) ? *nparams : -1, flags);

    virResetLastError();

21147
    if (!VIR_IS_CONNECTED_DOMAIN(dom)) {
21148 21149 21150 21151 21152
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

21153 21154 21155 21156 21157
    virCheckNonNullArgGoto(nparams, error);
    virCheckNonNegativeArgGoto(*nparams, error);
    if (*nparams != 0) {
        virCheckNonNullArgGoto(params, error);
        virCheckNonNullArgGoto(disk, error);
21158 21159 21160 21161 21162 21163 21164 21165 21166
    }

    if (VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;

    /* At most one of these two flags should be set.  */
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) &&
        (flags & VIR_DOMAIN_AFFECT_CONFIG)) {
21167
        virReportInvalidArg(flags,
21168 21169
                            _("flags 'affect live' and 'affect config' in %s "
                              "are mutually exclusive"),
21170
                            __FUNCTION__);
21171 21172 21173 21174 21175 21176 21177 21178 21179 21180 21181 21182
        goto error;
    }
    conn = dom->conn;

    if (conn->driver->domainGetBlockIoTune) {
        int ret;
        ret = conn->driver->domainGetBlockIoTune(dom, disk, params, nparams, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

21183
    virReportUnsupportedError();
21184 21185 21186 21187 21188

error:
    virDispatchError(dom->conn);
    return -1;
}
21189

21190

21191 21192 21193 21194 21195 21196 21197
/**
 * virDomainGetCPUStats:
 * @domain: domain to query
 * @params: array to populate on output
 * @nparams: number of parameters per cpu
 * @start_cpu: which cpu to start with, or -1 for summary
 * @ncpus: how many cpus to query
21198
 * @flags: bitwise-OR of virTypedParameterFlags
21199 21200 21201 21202 21203 21204 21205 21206 21207 21208 21209 21210 21211 21212
 *
 * Get statistics relating to CPU usage attributable to a single
 * domain (in contrast to the statistics returned by
 * virNodeGetCPUStats() for all processes on the host).  @dom
 * must be running (an inactive domain has no attributable cpu
 * usage).  On input, @params must contain at least @nparams * @ncpus
 * entries, allocated by the caller.
 *
 * If @start_cpu is -1, then @ncpus must be 1, and the returned
 * results reflect the statistics attributable to the entire
 * domain (such as user and system time for the process as a
 * whole).  Otherwise, @start_cpu represents which cpu to start
 * with, and @ncpus represents how many consecutive processors to
 * query, with statistics attributable per processor (such as
21213 21214 21215
 * per-cpu usage).  If @ncpus is larger than the number of cpus
 * available to query, then the trailing part of the array will
 * be unpopulated.
21216 21217 21218 21219 21220 21221 21222 21223 21224 21225 21226 21227 21228 21229 21230 21231 21232 21233 21234 21235 21236 21237 21238 21239 21240 21241 21242 21243 21244 21245
 *
 * The remote driver imposes a limit of 128 @ncpus and 16 @nparams;
 * the number of parameters per cpu should not exceed 16, but if you
 * have a host with more than 128 CPUs, your program should split
 * the request into multiple calls.
 *
 * As special cases, if @params is NULL and @nparams is 0 and
 * @ncpus is 1, and the return value will be how many
 * statistics are available for the given @start_cpu.  This number
 * may be different for @start_cpu of -1 than for any non-negative
 * value, but will be the same for all non-negative @start_cpu.
 * Likewise, if @params is NULL and @nparams is 0 and @ncpus is 0,
 * the number of cpus available to query is returned.  From the
 * host perspective, this would typically match the cpus member
 * of virNodeGetInfo(), but might be less due to host cpu hotplug.
 *
 * For now, @flags is unused, and the statistics all relate to the
 * usage from the host perspective.  It is possible that a future
 * version will support a flag that queries the cpu usage from the
 * guest's perspective, where the maximum cpu to query would be
 * related to virDomainGetVcpusFlags() rather than virNodeGetInfo().
 * An individual guest vcpu cannot be reliably mapped back to a
 * specific host cpu unless a single-processor vcpu pinning was used,
 * but when @start_cpu is -1, any difference in usage between a host
 * and guest perspective would serve as a measure of hypervisor overhead.
 *
 * Typical use sequence is below.
 *
 * getting total stats: set start_cpu as -1, ncpus 1
 * virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0) => nparams
21246
 * params = calloc(nparams, sizeof(virTypedParameter))
21247 21248 21249 21250 21251
 * virDomainGetCPUStats(dom, params, nparams, -1, 1, 0) => total stats.
 *
 * getting per-cpu stats:
 * virDomainGetCPUStats(dom, NULL, 0, 0, 0, 0) => ncpus
 * virDomainGetCPUStats(dom, NULL, 0, 0, 1, 0) => nparams
21252
 * params = calloc(ncpus * nparams, sizeof(virTypedParameter))
21253 21254 21255 21256 21257 21258 21259
 * virDomainGetCPUStats(dom, params, nparams, 0, ncpus, 0) => per-cpu stats
 *
 * Returns -1 on failure, or the number of statistics that were
 * populated per cpu on success (this will be less than the total
 * number of populated @params, unless @ncpus was 1; and may be
 * less than @nparams).  The populated parameters start at each
 * stride of @nparams, which means the results may be discontiguous;
21260 21261 21262 21263
 * any unpopulated parameters will be zeroed on success (this includes
 * skipped elements if @nparams is too large, and tail elements if
 * @ncpus is too large).  The caller is responsible for freeing any
 * returned string parameters.
21264
 */
21265 21266 21267 21268 21269 21270 21271
int
virDomainGetCPUStats(virDomainPtr domain,
                     virTypedParameterPtr params,
                     unsigned int nparams,
                     int start_cpu,
                     unsigned int ncpus,
                     unsigned int flags)
21272 21273 21274 21275 21276 21277 21278 21279 21280 21281 21282 21283 21284 21285 21286 21287 21288 21289 21290 21291
{
    virConnectPtr conn;

    VIR_DOMAIN_DEBUG(domain,
                     "params=%p, nparams=%d, start_cpu=%d, ncpus=%u, flags=%x",
                     params, nparams, start_cpu, ncpus, flags);
    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

    conn = domain->conn;
    /* Special cases:
     * start_cpu must be non-negative, or else -1
     * if start_cpu is -1, ncpus must be 1
     * params == NULL must match nparams == 0
     * ncpus must be non-zero unless params == NULL
21292
     * nparams * ncpus must not overflow (RPC may restrict it even more)
21293
     */
21294 21295 21296 21297 21298 21299 21300 21301 21302
    if (start_cpu == -1) {
        if (ncpus != 1) {
            virReportInvalidArg(start_cpu,
                                _("ncpus in %s must be 1 when start_cpu is -1"),
                                __FUNCTION__);
            goto error;
        }
    } else {
        virCheckNonNegativeArgGoto(start_cpu, error);
21303
    }
21304 21305 21306 21307 21308 21309 21310
    if (nparams)
        virCheckNonNullArgGoto(params, error);
    else
        virCheckNullArgGoto(params, error);
    if (ncpus == 0)
        virCheckNullArgGoto(params, error);

E
Eric Blake 已提交
21311 21312 21313 21314 21315
    if (nparams && ncpus > UINT_MAX / nparams) {
        virLibDomainError(VIR_ERR_OVERFLOW, _("input too large: %u * %u"),
                          nparams, ncpus);
        goto error;
    }
21316 21317 21318
    if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
                                 VIR_DRV_FEATURE_TYPED_PARAM_STRING))
        flags |= VIR_TYPED_PARAM_STRING_OKAY;
21319 21320 21321 21322 21323 21324 21325 21326 21327 21328 21329

    if (conn->driver->domainGetCPUStats) {
        int ret;

        ret = conn->driver->domainGetCPUStats(domain, params, nparams,
                                              start_cpu, ncpus, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

21330
    virReportUnsupportedError();
21331 21332 21333 21334 21335

error:
    virDispatchError(domain->conn);
    return -1;
}
21336

21337

21338 21339 21340 21341 21342 21343 21344 21345 21346 21347 21348 21349 21350 21351 21352 21353 21354 21355 21356 21357 21358 21359 21360 21361 21362 21363 21364 21365 21366 21367 21368 21369 21370 21371 21372 21373 21374 21375 21376 21377 21378 21379 21380 21381 21382
/**
 * virDomainGetDiskErrors:
 * @dom: a domain object
 * @errors: array to populate on output
 * @maxerrors: size of @errors array
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * The function populates @errors array with all disks that encountered an
 * I/O error.  Disks with no error will not be returned in the @errors array.
 * Each disk is identified by its target (the dev attribute of target
 * subelement in domain XML), such as "vda", and accompanied with the error
 * that was seen on it.  The caller is also responsible for calling free()
 * on each disk name returned.
 *
 * In a special case when @errors is NULL and @maxerrors is 0, the function
 * returns preferred size of @errors that the caller should use to get all
 * disk errors.
 *
 * Since calling virDomainGetDiskErrors(dom, NULL, 0, 0) to get preferred size
 * of @errors array and getting the errors are two separate operations, new
 * disks may be hotplugged to the domain and new errors may be encountered
 * between the two calls.  Thus, this function may not return all disk errors
 * because the supplied array is not large enough.  Such errors may, however,
 * be detected by listening to domain events.
 *
 * Returns number of disks with errors filled in the @errors array or -1 on
 * error.
 */
int
virDomainGetDiskErrors(virDomainPtr dom,
                       virDomainDiskErrorPtr errors,
                       unsigned int maxerrors,
                       unsigned int flags)
{
    VIR_DOMAIN_DEBUG(dom, "errors=%p, maxerrors=%u, flags=%x",
                     errors, maxerrors, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

21383 21384 21385 21386
    if (maxerrors)
        virCheckNonNullArgGoto(errors, error);
    else
        virCheckNullArgGoto(errors, error);
21387 21388 21389 21390 21391 21392 21393 21394 21395

    if (dom->conn->driver->domainGetDiskErrors) {
        int ret = dom->conn->driver->domainGetDiskErrors(dom, errors,
                                                         maxerrors, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

21396
    virReportUnsupportedError();
21397 21398 21399 21400 21401

error:
    virDispatchError(dom->conn);
    return -1;
}
G
Guido Günther 已提交
21402

21403

G
Guido Günther 已提交
21404 21405 21406 21407 21408 21409 21410 21411 21412 21413 21414 21415 21416 21417 21418 21419 21420 21421
/**
 * virDomainGetHostname:
 * @domain: a domain object
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Get the hostname for that domain.
 *
 * Dependent on hypervisor used, this may require a guest agent to be
 * available.
 *
 * Returns the hostname which must be freed by the caller, or
 * NULL if there was an error.
 */
char *
virDomainGetHostname(virDomainPtr domain, unsigned int flags)
{
    virConnectPtr conn;

21422
    VIR_DOMAIN_DEBUG(domain, "flags=%x", flags);
G
Guido Günther 已提交
21423 21424 21425 21426 21427 21428 21429 21430 21431 21432 21433 21434 21435

    virResetLastError();

    if (!VIR_IS_CONNECTED_DOMAIN(domain)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return NULL;
    }

    conn = domain->conn;

    if (conn->driver->domainGetHostname) {
        char *ret;
21436
        ret = conn->driver->domainGetHostname(domain, flags);
G
Guido Günther 已提交
21437 21438 21439 21440 21441
        if (!ret)
            goto error;
        return ret;
    }

21442
    virReportUnsupportedError();
G
Guido Günther 已提交
21443 21444 21445 21446 21447

error:
    virDispatchError(domain->conn);
    return NULL;
}
21448

21449

21450 21451 21452 21453 21454 21455 21456 21457 21458 21459 21460 21461 21462 21463 21464 21465 21466 21467 21468 21469 21470 21471 21472 21473 21474 21475 21476 21477 21478 21479 21480
/**
 * virNodeGetCPUMap:
 * @conn: pointer to the hypervisor connection
 * @cpumap: optional pointer to a bit map of real CPUs on the host node
 *      (in 8-bit bytes) (OUT)
 *      In case of success each bit set to 1 means that corresponding
 *      CPU is online.
 *      Bytes are stored in little-endian order: CPU0-7, 8-15...
 *      In each byte, lowest CPU number is least significant bit.
 *      The bit map is allocated by virNodeGetCPUMap and needs
 *      to be released using free() by the caller.
 * @online: optional number of online CPUs in cpumap (OUT)
 *      Contains the number of online CPUs if the call was successful.
 * @flags: extra flags; not used yet, so callers should always pass 0
 *
 * Get CPU map of host node CPUs.
 *
 * Returns number of CPUs present on the host node,
 * or -1 if there was an error.
 */
int
virNodeGetCPUMap(virConnectPtr conn,
                 unsigned char **cpumap,
                 unsigned int *online,
                 unsigned int flags)
{
    VIR_DEBUG("conn=%p, cpumap=%p, online=%p, flags=%x",
              conn, cpumap, online, flags);

    virResetLastError();

21481
    virCheckConnectReturn(conn, -1);
21482 21483 21484 21485 21486 21487 21488 21489

    if (conn->driver->nodeGetCPUMap) {
        int ret = conn->driver->nodeGetCPUMap(conn, cpumap, online, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

21490
    virReportUnsupportedError();
21491 21492 21493 21494 21495

error:
    virDispatchError(conn);
    return -1;
}
21496

21497

21498 21499 21500
/**
 * virDomainFSTrim:
 * @dom: a domain object
21501
 * @mountPoint: which mount point to trim
21502 21503 21504 21505 21506 21507
 * @minimum: Minimum contiguous free range to discard in bytes
 * @flags: extra flags, not used yet, so callers should always pass 0
 *
 * Calls FITRIM within the guest (hence guest agent may be
 * required depending on hypervisor used). Either call it on each
 * mounted filesystem (@mountPoint is NULL) or just on specified
21508
 * @mountPoint. @minimum hints that free ranges smaller than this
21509 21510 21511 21512
 * may be ignored (this is a hint and the guest may not respect
 * it).  By increasing this value, the fstrim operation will
 * complete more quickly for filesystems with badly fragmented
 * free space, although not all blocks will be discarded.
21513
 * If @minimum is not zero, the command may fail.
21514 21515 21516 21517 21518 21519 21520 21521 21522 21523 21524 21525 21526 21527 21528 21529 21530 21531 21532 21533
 *
 * Returns 0 on success, -1 otherwise.
 */
int
virDomainFSTrim(virDomainPtr dom,
                const char *mountPoint,
                unsigned long long minimum,
                unsigned int flags)
{
    VIR_DOMAIN_DEBUG(dom, "mountPoint=%s, minimum=%llu, flags=%x",
                     mountPoint, minimum, flags);

    virResetLastError();

    if (!VIR_IS_DOMAIN(dom)) {
        virLibDomainError(VIR_ERR_INVALID_DOMAIN, __FUNCTION__);
        virDispatchError(NULL);
        return -1;
    }

21534
    virCheckReadOnlyGoto(dom->conn->flags, error);
21535 21536 21537 21538 21539 21540 21541 21542 21543

    if (dom->conn->driver->domainFSTrim) {
        int ret = dom->conn->driver->domainFSTrim(dom, mountPoint,
                                                  minimum, flags);
        if (ret < 0)
            goto error;
        return ret;
    }

21544
    virReportUnsupportedError();
21545 21546 21547 21548 21549

error:
    virDispatchError(dom->conn);
    return -1;
}