libvirt.c 29.6 KB
Newer Older
D
Daniel Veillard 已提交
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
 *
5
 * Copyright (C) 2005,2006 Red Hat, Inc.
D
Daniel Veillard 已提交
6 7 8 9 10 11
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
 */

12
#include "libvirt.h"
D
Daniel Veillard 已提交
13

14
#include <stdio.h>
15
#include <stdlib.h>
16
#include <string.h>
17 18 19
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
20
#include <xs.h>
D
Daniel Veillard 已提交
21
#include "internal.h"
22
#include "xen_internal.h"
23
#include "xend_internal.h"
24 25
#include "hash.h"

D
Daniel Veillard 已提交
26 27 28 29 30

/*
 * TODO:
 * - use lock to protect against concurrent accesses ?
 * - use reference counting to garantee coherent pointer state ?
31 32
 * - error reporting layer
 * - memory wrappers for malloc/free ?
D
Daniel Veillard 已提交
33 34
 */

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
/**
 * virGetVersion:
 * @libVer: return value for the library version (OUT)
 * @type: hypervisor type
 * @typeVer: return value for the version of the hypervisor (OUT)
 *
 * Provides two information back, @libVer is the version of the library
 * while @typeVer will be the version of the hypervisor type @type against
 * which the library was compiled. If @type is NULL, "Xen" is assumed, if
 * @type is unknown or not availble, an error code will be returned and 
 * @typeVer will be 0.
 *
 * 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
virGetVersion(unsigned long *libVer, const char *type, unsigned long *typeVer) {
    if (libVer == NULL)
        return(-1);
    *libVer = LIBVIR_VERSION_NUMBER;

    if (typeVer != NULL) {
	if ((type == NULL) || (!strcasecmp(type, "Xen"))) {
	    if ((DOM0_INTERFACE_VERSION & 0xFFFF0000) == (0xAAAA0000)) {
	        /* one time glitch hopefully ! */
                *typeVer = 2 * 1000000 +
		           ((DOM0_INTERFACE_VERSION >> 8) & 0xFF) * 1000 +
			   (DOM0_INTERFACE_VERSION & 0xFF);
	    } else {
		*typeVer = (DOM0_INTERFACE_VERSION >> 24) * 1000000 +
			   ((DOM0_INTERFACE_VERSION >> 16) & 0xFF) * 1000 +
			   (DOM0_INTERFACE_VERSION & 0xFFFF);
	    }
	} else {
	    *typeVer = 0;
	    return(-1);
	}
    }
    return(0);
}

D
Daniel Veillard 已提交
76
/**
77
 * virConnectOpen:
D
Daniel Veillard 已提交
78 79 80
 * @name: optional argument currently unused, pass NULL
 *
 * This function should be called first to get a connection to the 
81
 * Hypervisor and xen store
D
Daniel Veillard 已提交
82 83 84
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
 */
85 86 87
virConnectPtr
virConnectOpen(const char *name) {
    virConnectPtr ret = NULL;
88
    int handle = -1;
89 90 91 92 93
    struct xs_handle *xshandle = NULL;

    /* we can only talk to the local Xen supervisor ATM */
    if (name != NULL) 
        return(NULL);
94

95
    handle = xenHypervisorOpen();
96 97 98
    if (handle == -1)
        goto failed;
    xshandle = xs_daemon_open();
99
    if (xshandle == NULL)
100 101
        goto failed;

102
    ret = (virConnectPtr) malloc(sizeof(virConnect));
103 104
    if (ret == NULL)
        goto failed;
105
    ret->magic = VIR_CONNECT_MAGIC;
106
    ret->handle = handle;
107
    ret->xshandle = xshandle;
108 109
    if (xend_setup(ret) < 0)
        goto failed;
110
    ret->domains = virHashCreate(20);
111
    ret->flags = 0;
112 113
    if (ret->domains == NULL)
        goto failed;
114 115

    return(ret);
116 117
failed:
    if (handle >= 0)
118
        xenHypervisorClose(handle);
119
    if (xshandle != NULL)
120
        xs_daemon_close(xshandle);
121 122 123 124 125 126
    if (ret != NULL)
        free(ret);
    return(NULL);
}

/**
127
 * virConnectOpenReadOnly:
128 129
 * @name: optional argument currently unused, pass NULL
 *
130 131 132
 * This function should be called first to get a restricted connection to the 
 * libbrary functionalities. The set of APIs usable are then restricted
 * on the available methods to control the domains.
133 134 135
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
 */
136 137
virConnectPtr
virConnectOpenReadOnly(const char *name) {
138 139
    int method = 0;
    int handle;
140
    virConnectPtr ret = NULL;
141 142 143 144 145 146
    struct xs_handle *xshandle = NULL;

    /* we can only talk to the local Xen supervisor ATM */
    if (name != NULL) 
        return(NULL);

147 148 149
    handle = xenHypervisorOpen();
    if (handle >= 0)
        method++;
150 151 152
    else
        handle = -1;

153
    xshandle = xs_daemon_open_readonly();
154 155
    if (xshandle != NULL)
        method++;
156

157
    ret = (virConnectPtr) malloc(sizeof(virConnect));
158 159
    if (ret == NULL)
        goto failed;
160
    ret->magic = VIR_CONNECT_MAGIC;
161
    ret->handle = handle;
162
    ret->xshandle = xshandle;
163 164
    if (xend_setup(ret) == 0)
        method++;
165 166
    ret->domains = virHashCreate(20);
    ret->flags = VIR_CONNECT_RO;
167
    if ((ret->domains == NULL) || (method == 0))
168 169 170 171
        goto failed;

    return(ret);
failed:
172 173
    if (handle >= 0)
        xenHypervisorClose(handle);
174 175
    if (xshandle != NULL)
        xs_daemon_close(xshandle);
176 177 178
    if (ret != NULL) {
        if (ret->domains != NULL)
	    virHashFree(ret->domains, NULL);
179
        free(ret);
180
    }
181
    return(NULL);
D
Daniel Veillard 已提交
182 183
}

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
/**
 * virConnectCheckStoreID:
 * @conn: pointer to the hypervisor connection
 * @id: the id number as returned from Xenstore
 *
 * the xenstore sometimes list non-running domains, double check
 * from the hypervisor if we have direct access
 *
 * Returns -1 if the check failed, 0 if successful or not possible to check
 */
static int
virConnectCheckStoreID(virConnectPtr conn, int id) {
    if (conn->handle >= 0) {
	dom0_getdomaininfo_t dominfo;
	int tmp;

	dominfo.domain = id;
	tmp = xenHypervisorGetDomainInfo(conn->handle, id, &dominfo);
	if (tmp < 0)
	    return(-1);
    }
    return(0);
}

208
/**
209
 * virDomainFreeName:
210 211 212 213 214 215 216
 * @domain: a domain object
 *
 * Destroy the domain object, this is just used by the domain hash callback.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
static int
217 218
virDomainFreeName(virDomainPtr domain, const char *name ATTRIBUTE_UNUSED) {
    return(virDomainFree(domain));
219 220
}

D
Daniel Veillard 已提交
221
/**
222
 * virConnectClose:
D
Daniel Veillard 已提交
223 224 225 226 227 228 229 230 231 232
 * @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.
 *
 * Returns 0 in case of success or -1 in case of error.
 */
int
233
virConnectClose(virConnectPtr conn) {
234
    xend_cleanup(conn);
K
Karel Zak 已提交
235
    if (!VIR_IS_CONNECT(conn))
D
Daniel Veillard 已提交
236
        return(-1);
237
    virHashFree(conn->domains, (virHashDeallocator) virDomainFreeName);
D
Daniel Veillard 已提交
238
    conn->magic = -1;
239 240
    if (conn->xshandle != NULL)
	xs_daemon_close(conn->xshandle);
241
    conn->xshandle = NULL;
242
    if (conn->handle != -1)
243
	xenHypervisorClose(conn->handle);
244
    conn->handle = -1;
D
Daniel Veillard 已提交
245 246 247 248
    free(conn);
    return(0);
}

249 250 251 252 253 254 255 256 257 258
/**
 * virConnectGetType:
 * @conn: pointer to the hypervisor connection
 *
 * Get the name of the Hypervisor software used.
 *
 * Returns NULL in case of error, a static zero terminated string otherwise.
 */
const char *
virConnectGetType(virConnectPtr conn) {
K
Karel Zak 已提交
259
    if (!VIR_IS_CONNECT(conn))
260 261 262 263
        return(NULL);
    return("Xen");
}

D
Daniel Veillard 已提交
264
/**
265
 * virConnectGetVersion:
D
Daniel Veillard 已提交
266
 * @conn: pointer to the hypervisor connection
267
 * @hvVer: return value for the version of the running hypervisor (OUT)
D
Daniel Veillard 已提交
268
 *
269 270 271
 * Get the version level of the Hypervisor running. This may work only with 
 * hypervisor call, i.e. with priviledged access to the hypervisor, not
 * with a Read-Only connection.
D
Daniel Veillard 已提交
272
 *
273 274 275
 * 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 已提交
276
 */
277 278 279
int
virConnectGetVersion(virConnectPtr conn, unsigned long *hvVer) {
    unsigned long ver;
280

K
Karel Zak 已提交
281 282 283 284
    if (!VIR_IS_CONNECT(conn))
	return(-1);
    
    if (hvVer == NULL)
D
Daniel Veillard 已提交
285
        return(-1);
286 287
    
    /* this can't be extracted from the Xenstore */
288 289
    if (conn->handle < 0) {
        *hvVer = 0;
290
        return(0);
291
    }
292 293

    ver = xenHypervisorGetVersion(conn->handle);
294 295
    *hvVer = (ver >> 16) * 1000000 + (ver & 0xFFFF) * 1000;
    return(0);
296 297 298
}

/**
299
 * virConnectListDomains:
300 301 302 303 304 305 306 307 308
 * @conn: pointer to the hypervisor connection
 * @ids: array to collect the list of IDs of active domains
 * @maxids: size of @ids
 *
 * Collect the list of active domains, and store their ID in @maxids
 *
 * Returns the number of domain found or -1 in case of error
 */
int
309
virConnectListDomains(virConnectPtr conn, int *ids, int maxids) {
310 311 312 313 314
    int ret = -1;
    unsigned int num, i;
    long id;
    char **idlist = NULL, *endptr;

K
Karel Zak 已提交
315 316 317 318
    if (!VIR_IS_CONNECT(conn))
	return(-1);
    
    if ((ids == NULL) || (maxids <= 0))
319 320
        return(-1);
    
321 322 323 324 325 326 327 328 329 330 331
    /* TODO: implement the API with Xend interfaces */
    idlist = xend_get_domains(conn);
    if (idlist != NULL) {
        for (ret = 0,i = 0;(idlist[i] != NULL) && (ret < maxids);i++) {
	    id = xend_get_domain_id(conn, idlist[i]);
	    if (id >= 0)
	        ids[ret++] = (int) id;
	}
	goto done;
    }
    if (conn->xshandle != NULL) {
332
	idlist = xs_directory(conn->xshandle, 0, "/local/domain", &num);
333
	if (idlist == NULL)
334
	    goto done;
335

336 337 338 339 340 341 342 343 344 345
	for (ret = 0,i = 0;(i < num) && (ret < maxids);i++) {
	    id = strtol(idlist[i], &endptr, 10);
	    if ((endptr == idlist[i]) || (*endptr != 0)) {
		ret = -1;
		goto done;
	    }
	    if (virConnectCheckStoreID(conn, (int) id) < 0)
		continue;
	    ids[ret++] = (int) id;
	}
346 347 348 349 350 351 352
    }

done:
    if (idlist != NULL)
        free(idlist);

    return(ret);
D
Daniel Veillard 已提交
353 354
}

K
 
Karel Zak 已提交
355 356 357 358
/**
 * virConnectNumOfDomains:
 * @conn: pointer to the hypervisor connection
 *
359 360
 * Provides the number of active domains.
 *
K
 
Karel Zak 已提交
361 362 363 364 365 366 367 368
 * Returns the number of domain found or -1 in case of error
 */
int
virConnectNumOfDomains(virConnectPtr conn) {
    int ret = -1;
    unsigned int num;
    char **idlist = NULL;

K
Karel Zak 已提交
369 370 371
    if (!VIR_IS_CONNECT(conn))
	return(-1);

372 373 374 375 376 377 378 379 380 381 382 383 384 385
    /* 
     * try first with Xend interface
     */
    idlist = xend_get_domains(conn);
    if (idlist != NULL) {
        char **tmp = idlist;

        ret = 0;
        while (*tmp != NULL) {
	    tmp++;
	    ret++;
	}
	
    } else if (conn->xshandle != NULL) {
386 387 388 389
        idlist = xs_directory(conn->xshandle, 0, "/local/domain", &num);
	if (idlist) {
	    free(idlist);
	    ret = num;
390
	}
K
 
Karel Zak 已提交
391 392 393 394
    }
    return(ret);
}

D
Daniel Veillard 已提交
395
/**
396
 * virDomainCreateLinux:
D
Daniel Veillard 已提交
397 398 399 400 401
 * @conn: pointer to the hypervisor connection
 * @kernel_path: the file path to the kernel image
 * @initrd_path: an optional file path to an initrd
 * @cmdline: optional command line parameters for the kernel
 * @memory: the memory size in kilobytes
402
 * @flags: an optional set of virDomainFlags
D
Daniel Veillard 已提交
403
 *
404 405
 * Launch a new Linux guest domain, unimplemented yet, API to be defined.
 * This would function requires priviledged access to the hypervisor.
D
Daniel Veillard 已提交
406 407 408
 * 
 * Returns a new domain object or NULL in case of failure
 */
409 410
virDomainPtr
virDomainCreateLinux(virConnectPtr conn, const char *kernel_path,
411 412 413 414
		     const char *initrd_path ATTRIBUTE_UNUSED,
		     const char *cmdline ATTRIBUTE_UNUSED,
		     unsigned long memory,
		     unsigned int flags ATTRIBUTE_UNUSED) {
K
Karel Zak 已提交
415 416 417 418

    if (!VIR_IS_CONNECT(conn))
	return(NULL);
    if ((kernel_path == NULL) || (memory < 4096))
D
Daniel Veillard 已提交
419 420 421 422 423
        return(NULL);
    TODO
    return(NULL);
}

424 425 426 427 428 429 430 431 432 433 434 435
/**
 * virConnectDoStoreList:
 * @conn: pointer to the hypervisor connection
 * @path: the absolute path of the directory in the store to list
 * @nb: OUT pointer to the number of items found
 *
 * Internal API querying the Xenstore for a list
 *
 * Returns a string which must be freed by the caller or NULL in case of error
 */
static char **
virConnectDoStoreList(virConnectPtr conn, const char *path, unsigned int *nb) {
436 437 438 439
    if ((conn == NULL) || (conn->xshandle == NULL) || (path == NULL) ||
        (nb == NULL))
        return(NULL);

440
    return xs_directory(conn->xshandle, 0, path, nb);
441 442 443
}

/**
444
 * virDomainDoStoreQuery:
445 446 447 448 449 450 451 452
 * @domain: a domain object
 * @path: the relative path of the data in the store to retrieve
 *
 * Internal API querying the Xenstore for a string value.
 *
 * Returns a string which must be freed by the caller or NULL in case of error
 */
static char *
453
virDomainDoStoreQuery(virDomainPtr domain, const char *path) {
454 455
    char s[256];
    unsigned int len = 0;
K
Karel Zak 已提交
456 457 458
    
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
	return(NULL);
459 460
    if (domain->conn->xshandle == NULL)
        return(NULL);
461 462 463 464

    snprintf(s, 255, "/local/domain/%d/%s", domain->handle, path);
    s[255] = 0;

465
    return xs_read(domain->conn->xshandle, 0, &s[0], &len);
466 467
}

468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
/**
 * virDomainDoStoreWrite:
 * @domain: a domain object
 * @path: the relative path of the data in the store to retrieve
 *
 * Internal API setting up a string value in the Xenstore
 * Requires write access to the XenStore
 *
 * Returns 0 in case of success, -1 in case of failure
 */
static int
virDomainDoStoreWrite(virDomainPtr domain, const char *path,
                      const char *value) {
    char s[256];

    int ret = -1;

K
Karel Zak 已提交
486
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
487
	return(-1);
488 489
    if (domain->conn->xshandle == NULL)
        return(-1);
K
Karel Zak 已提交
490
    if (domain->conn->flags & VIR_CONNECT_RO)
491 492 493 494 495
        return(-1);

    snprintf(s, 255, "/local/domain/%d/%s", domain->handle, path);
    s[255] = 0;

496
    if (xs_write(domain->conn->xshandle, 0, &s[0], value, strlen(value)))
497 498 499 500 501
        ret = 0;

    return(ret);
}

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
/**
 * virDomainGetVM:
 * @domain: a domain object
 *
 * Internal API extracting a xenstore vm path.
 *
 * Returns the new string or NULL in case of error
 */
char *
virDomainGetVM(virDomainPtr domain)
{
    char *vm;
    char query[200];
    unsigned int len;
    
K
Karel Zak 已提交
517
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
518
	return(NULL);
519 520
    if (domain->conn->xshandle == NULL)
        return(NULL);
K
Karel Zak 已提交
521
    
522 523 524 525
    snprintf(query, 199, "/local/domain/%d/vm", 
             virDomainGetID(domain));
    query[199] = 0;

526
    vm = xs_read(domain->conn->xshandle, 0, &query[0], &len);
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

    return(vm);
}

/**
 * virDomainGetVMInfo:
 * @domain: a domain object
 * @vm: the xenstore vm path
 * @name: the value's path
 *
 * Internal API extracting one information the device used 
 * by the domain from xensttore
 *
 * Returns the new string or NULL in case of error
 */
char *
virDomainGetVMInfo(virDomainPtr domain, const char *vm, 
                   const char *name) {
    char s[256];
    char *ret = NULL;
    unsigned int len = 0;
    
K
Karel Zak 已提交
549
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
550
	return(NULL);
551 552
    if (domain->conn->xshandle==NULL)
	return(NULL);
K
Karel Zak 已提交
553
    
554 555 556
    snprintf(s, 255, "%s/%s", vm, name);
    s[255] = 0;

557
    ret = xs_read(domain->conn->xshandle, 0, &s[0], &len);
558 559 560 561

    return(ret);
}

562
/**
563
 * virDomainLookupByID:
564 565 566 567 568 569 570
 * @conn: pointer to the hypervisor connection
 * @id: the domain ID number
 *
 * Try to find a domain based on the hypervisor ID number
 *
 * Returns a new domain object or NULL in case of failure
 */
571 572
virDomainPtr
virDomainLookupByID(virConnectPtr conn, int id) {
573
    char *path = NULL;
574
    virDomainPtr ret;
575
    char *name = NULL;
576

K
Karel Zak 已提交
577 578 579
    if (!VIR_IS_CONNECT(conn))
	return(NULL);
    if (id < 0)
580 581
        return(NULL);

582 583 584 585 586
    /* lookup is easier with the Xen store so try it first */
    if (conn->xshandle != NULL) {
	path = xs_get_domain_path(conn->xshandle, (unsigned int) id);
    }
    /* fallback to xend API then */
587
    if (path == NULL) {
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        char **names = xend_get_domains(conn);
	char **tmp = names;
	int ident;

	if (names != NULL) {
	    while (*tmp != NULL) {
		ident = xend_get_domain_id(conn, *tmp);
		if (ident == id) {
		    name = strdup(*tmp);
		    break;
		}
		tmp++;
	    }
	    free(names);
	}
603
    }
604

605
    ret = (virDomainPtr) malloc(sizeof(virDomain));
606
    if (ret == NULL) {
607 608
        if (path != NULL)
	    free(path);
609 610
	return(NULL);
    }
611
    ret->magic = VIR_DOMAIN_MAGIC;
612 613
    ret->conn = conn;
    ret->handle = id;
614
    ret->path = path;
615 616 617 618
    if (name == NULL)
	ret->name = virDomainDoStoreQuery(ret, "name");
    else
        ret->name = name;
619
    if (ret->name == NULL) {
620 621
        if (path != NULL)
	    free(path);
622 623 624
        free(ret);
	return(NULL);
    }
625 626 627 628

    return(ret);
}

629 630 631 632 633
/**
 * virDomainLookupByName:
 * @conn: pointer to the hypervisor connection
 * @name: name for the domain
 *
634
 * Try to lookup a domain on the given hypervisor based on its name.
635 636 637 638 639 640 641
 *
 * Returns a new domain object or NULL in case of failure
 */
virDomainPtr
virDomainLookupByName(virConnectPtr conn, const char *name) {
    virDomainPtr ret = NULL;
    unsigned int num, i, len;
642
    long id = -1;
643
    char **idlist = NULL, *endptr;
644 645
    char prop[200], *tmp, *path = NULL;
    unsigned char *uuid = NULL;
646
    int found = 0;
647
    struct xend_domain *xenddomain = NULL;
648

K
Karel Zak 已提交
649 650 651
    if (!VIR_IS_CONNECT(conn))
	return(NULL);
    if (name == NULL)
652 653
        return(NULL);

654 655 656 657 658 659 660 661 662 663
    /* try first though Xend */
    xenddomain = xend_get_domain(conn, name);
    if (xenddomain != NULL) {
        id = xenddomain->live->id;
	uuid = xenddomain->uuid;
	found = 1;
	goto do_found;
    }

    /* then though the XenStore */
664
    if (conn->xshandle != NULL) {
665
        idlist = xs_directory(conn->xshandle, 0, "/local/domain", &num);
666 667 668 669 670 671 672 673 674 675 676 677
        if (idlist == NULL)
            goto done;

        for (i = 0;i < num;i++) {
             id = strtol(idlist[i], &endptr, 10);
	     if ((endptr == idlist[i]) || (*endptr != 0)) {
	         goto done;
	     }
	     if (virConnectCheckStoreID(conn, (int) id) < 0)
	         continue;
             snprintf(prop, 199, "/local/domain/%s/name", idlist[i]);
	     prop[199] = 0;
678
	     tmp = xs_read(conn->xshandle, 0, prop, &len);
679 680 681 682 683 684 685 686
	     if (tmp != NULL) {
	         found = !strcmp(name, tmp);
	         free(tmp);
	         if (found)
	             break;
	     }
        }
        path = xs_get_domain_path(conn->xshandle, (unsigned int) id);
687
    }
688 689 690

do_found:

691 692 693 694 695 696 697
    if (found) {
	ret = (virDomainPtr) malloc(sizeof(virDomain));
	if (ret == NULL)
	    goto done;
	ret->magic = VIR_DOMAIN_MAGIC;
	ret->conn = conn;
	ret->handle = id;
698 699 700
	ret->path = path;
	if (uuid != NULL)
	    memcpy(ret->uuid, uuid, 16);
701 702 703 704
	ret->name = strdup(name);
    }

done:
705 706
    if (xenddomain != NULL)
	free(xenddomain);
707 708 709 710 711 712
    if (idlist != NULL)
        free(idlist);

    return(ret);
}

D
Daniel Veillard 已提交
713
/**
714
 * virDomainDestroy:
D
Daniel Veillard 已提交
715 716 717 718
 * @domain: a domain object
 *
 * 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.
719 720
 * The data structure is freed and should not be used thereafter if the
 * call does not return an error.
721
 * This function may requires priviledged access
D
Daniel Veillard 已提交
722 723
 *
 * Returns 0 in case of success and -1 in case of failure.
724
 */
D
Daniel Veillard 已提交
725
int
726
virDomainDestroy(virDomainPtr domain) {
727 728
    int ret;

K
Karel Zak 已提交
729 730
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
	return(-1);
731 732 733 734 735 736 737 738 739 740

    /*
     * try first with the xend method
     */
    ret = xend_destroy(domain->conn, domain->name);
    if (ret == 0) {
        virDomainFree(domain);
	return(0);
    }

741 742 743
    ret = xenHypervisorDestroyDomain(domain->conn->handle, domain->handle);
    if (ret < 0)
        return(-1);
744
    
745 746
    virDomainFree(domain);
    return(0);
747 748 749 750 751 752 753 754 755 756 757 758 759
}

/**
 * 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
virDomainFree(virDomainPtr domain) {
K
Karel Zak 已提交
760 761
    if (!VIR_IS_DOMAIN(domain))
	return(-1);
762 763 764 765 766 767 768 769
    domain->magic = -1;
    domain->handle = -1;
    if (domain->path != NULL)
        free(domain->path);
    if (domain->name)
        free(domain->name);
    free(domain);
    return(0);
D
Daniel Veillard 已提交
770 771 772
}

/**
773
 * virDomainSuspend:
D
Daniel Veillard 已提交
774 775 776 777
 * @domain: a domain object
 *
 * Suspends an active domain, the process is frozen without further access
 * to CPU resources and I/O but the memory used by the domain at the 
778
 * hypervisor level will stay allocated. Use virDomainResume() to reactivate
D
Daniel Veillard 已提交
779
 * the domain.
780
 * This function may requires priviledged access.
D
Daniel Veillard 已提交
781 782 783 784
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
785
virDomainSuspend(virDomainPtr domain) {
786 787
    int ret;

K
Karel Zak 已提交
788 789
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
	return(-1);
790 791 792 793 794 795
    /* first try though the Xen daemon */
    ret = xend_pause(domain->conn, domain->name);
    if (ret == 0)
        return(0);

    /* then try a direct hypervisor access */
796
    return(xenHypervisorPauseDomain(domain->conn->handle, domain->handle));
D
Daniel Veillard 已提交
797 798 799
}

/**
800
 * virDomainResume:
D
Daniel Veillard 已提交
801 802 803
 * @domain: a domain object
 *
 * Resume an suspended domain, the process is restarted from the state where
804
 * it was frozen by calling virSuspendDomain().
805
 * This function may requires priviledged access
D
Daniel Veillard 已提交
806 807 808 809
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
810
virDomainResume(virDomainPtr domain) {
811 812
    int ret;

K
Karel Zak 已提交
813 814
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
	return(-1);
815 816 817 818 819 820
    /* first try though the Xen daemon */
    ret = xend_unpause(domain->conn, domain->name);
    if (ret == 0)
        return(0);

    /* then try a direct hypervisor access */
821
    return(xenHypervisorResumeDomain(domain->conn->handle, domain->handle));
D
Daniel Veillard 已提交
822 823
}

824 825 826 827 828 829
/**
 * virDomainSave:
 * @domain: a domain object
 * @to: path for the output file
 *
 * This method will suspend a domain and save its memory contents to
830 831 832
 * a file on disk. After the call, if successful, the domain is not
 * listed as running anymore (this may be a problem).
 * Use virDomainRestore() to restore a domain after saving.
833 834 835 836 837 838
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainSave(virDomainPtr domain, const char *to) {
    int ret;
839
    char filepath[4096];
840

841
    if ((!VIR_IS_CONNECTED_DOMAIN(domain)) || (to == NULL))
842 843
	return(-1);

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    /*
     * We must absolutize the file path as the save is done out of process
     * TODO: check for URI when libxml2 is linked in.
     */
    if (to[0] != '/') {
	unsigned int len, t;

	t = strlen(to);
	if (getcwd(filepath, sizeof(filepath) - (t + 3)) == NULL)
	    return(-1);
	len = strlen(filepath);
	/* that should be covered by getcwd() semantic, but be 100% sure */
	if (len > sizeof(filepath) - (t + 3))
	    return(-1); 
	filepath[len] = '/';
	strcpy(&filepath[len + 1], to);
	to = &filepath[0];

    }

864 865 866 867 868 869
    ret = xend_save(domain->conn, domain->name, to);
    return(ret);
}

/**
 * virDomainRestore:
870
 * @conn: pointer to the hypervisor connection
871 872 873 874 875 876 877
 * @from: path to the 
 *
 * This method will restore a domain saved to disk by virDomainSave().
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
878
virDomainRestore(virConnectPtr conn, const char *from) {
879
    int ret;
880
    char filepath[4096];
881

882
    if ((!VIR_IS_CONNECT(conn)) || (from == NULL))
883
	return(-1);
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    /*
     * We must absolutize the file path as the restore is done out of process
     * TODO: check for URI when libxml2 is linked in.
     */
    if (from[0] != '/') {
	unsigned int len, t;

	t = strlen(from);
	if (getcwd(filepath, sizeof(filepath) - (t + 3)) == NULL)
	    return(-1);
	len = strlen(filepath);
	/* that should be covered by getcwd() semantic, but be 100% sure */
	if (len > sizeof(filepath) - (t + 3))
	    return(-1); 
	filepath[len] = '/';
	strcpy(&filepath[len + 1], from);
	from = &filepath[0];
    }
902
    
903
    ret = xend_restore(conn, from);
904 905 906
    return(ret);
}

907 908 909 910 911
/**
 * virDomainShutdown:
 * @domain: a domain object
 *
 * Shutdown a domain, the domain object is still usable there after but
912 913
 * the domain OS is being stopped. Note that the guest OS may ignore the
 * request.
914 915 916 917 918 919 920 921 922 923
 *
 * TODO: should we add an option for reboot, knowing it may not be doable
 *       in the general case ?
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainShutdown(virDomainPtr domain) {
    int ret;

K
Karel Zak 已提交
924 925 926
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
	return(-1);
    
927 928 929 930
    /*
     * try first with the xend daemon
     */
    ret = xend_shutdown(domain->conn, domain->name);
931
    /* disabled as this seems to not work ...
932 933
    if (ret == 0)
        return(0);
934
     */
935
    /*
936

937 938 939 940 941 942 943 944 945 946
     * this is very hackish, the domU kernel probes for a special 
     * node in the xenstore and launch the shutdown command if found.
     */
    ret = virDomainDoStoreWrite(domain, "control/shutdown", "halt");
    if (ret == 0) {
        domain->flags |= DOMAIN_IS_SHUTDOWN;
    }
    return(ret);
}

947
/**
948
 * virDomainGetName:
949 950 951 952 953 954 955 956
 * @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 *
957
virDomainGetName(virDomainPtr domain) {
K
Karel Zak 已提交
958 959
    if (!VIR_IS_DOMAIN(domain))
	return(NULL);
960 961 962 963
    return(domain->name);
}

/**
964
 * virDomainGetID:
965 966 967 968 969 970 971
 * @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
972
virDomainGetID(virDomainPtr domain) {
K
Karel Zak 已提交
973 974
    if (!VIR_IS_DOMAIN(domain))
	return((unsigned int) -1);
975
    return(domain->handle);
976 977
}

978 979 980 981 982 983 984 985 986 987 988 989
/**
 * virDomainGetOSType:
 * @domain: a domain object
 *
 * Get the type of domain operation system.
 *
 * Returns the new string or NULL in case of error
 */
char *
virDomainGetOSType(virDomainPtr domain) {
    char *vm, *str = NULL;
    
K
Karel Zak 已提交
990 991 992
    if (!VIR_IS_DOMAIN(domain))
	return(NULL);
    
993 994 995 996 997
    vm = virDomainGetVM(domain);
    if (vm) {
    	str = virDomainGetVMInfo(domain, vm, "image/ostype");
	free(vm);
    }
998 999 1000
    if (str == NULL)
        str = strdup("linux");

1001 1002 1003
    return(str);
}

1004
/**
1005
 * virDomainGetMaxMemory:
1006 1007 1008 1009 1010 1011 1012 1013 1014
 * @domain: a domain object or NULL
 * 
 * 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.
 *
 * Returns the memory size in kilobytes or 0 in case of error.
 */
unsigned long
1015
virDomainGetMaxMemory(virDomainPtr domain) {
1016 1017
    unsigned long ret = 0;

K
Karel Zak 已提交
1018 1019 1020
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
	return(0);
    
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    if (domain->conn->flags & VIR_CONNECT_RO) {
        char *tmp;

	tmp = virDomainDoStoreQuery(domain, "memory/target");
	if (tmp != NULL) {
	    ret = (unsigned long) atol(tmp);
	    free(tmp);
	}
    } else {
        dom0_getdomaininfo_t dominfo;
	int tmp;

	dominfo.domain = domain->handle;
        tmp = xenHypervisorGetDomainInfo(domain->conn->handle, domain->handle,
	                                 &dominfo);
	if (tmp >= 0)
	    ret = dominfo.max_pages * 4;
    }
    return(ret);
1040 1041
}

D
Daniel Veillard 已提交
1042
/**
1043
 * virDomainSetMaxMemory:
D
Daniel Veillard 已提交
1044 1045 1046 1047 1048 1049
 * @domain: a domain object or NULL
 * @memory: the memory size in kilobytes
 * 
 * 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.
1050
 * This function requires priviledged access to the hypervisor.
D
Daniel Veillard 已提交
1051 1052 1053 1054
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
1055
virDomainSetMaxMemory(virDomainPtr domain, unsigned long memory) {
1056 1057 1058
    int ret;
    char s[256], v[30];
    
K
Karel Zak 已提交
1059 1060 1061
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
	return(-1);
    if (memory < 4096)
D
Daniel Veillard 已提交
1062
        return(-1);
1063 1064
    if (domain->conn->flags & VIR_CONNECT_RO)
        return(-1);
1065 1066
    if (domain->conn->xshandle==NULL)
	return(-1);
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    ret = xenHypervisorSetMaxMemory(domain->conn->handle, domain->handle,
                                    memory);
    if (ret < 0)
        return(-1);

    /*
     * try to update at the Xenstore level too
     * Failing to do so should not be considered fatal though as long
     * as the hypervisor call succeeded
     */
    snprintf(s, 255, "/local/domain/%d/memory/target", domain->handle);
    s[255] = 0;
    snprintf(v, 29, "%lu", memory);
    v[30] = 0;

1082 1083
    if (!xs_write(domain->conn->xshandle, 0, &s[0], &v[0], strlen(v)))
        ret = -1;
1084 1085

    return(ret);
D
Daniel Veillard 已提交
1086 1087
}

1088 1089
/**
 * virDomainGetInfo:
1090
 * @domain: a domain object
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
 * @info: pointer to a virDomainInfo structure allocated by the user
 * 
 * Extract information about a domain. Note that if the connection
 * used to get the domain is limited only a partial set of the informations
 * can be extracted.
 *
 * Returns 0 in case of success and -1 in case of failure.
 */
int
virDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info) {
    int ret;
1102 1103 1104 1105
    char *tmp, **tmp2;
    unsigned int nb_vcpus;
    char request[200];

1106

K
Karel Zak 已提交
1107
    if (!VIR_IS_CONNECTED_DOMAIN(domain))
1108
	return(-1);
K
Karel Zak 已提交
1109 1110 1111
    if (info == NULL)
	return(-1);
    
1112
    memset(info, 0, sizeof(virDomainInfo));
K
Karel Zak 已提交
1113
    
1114 1115 1116 1117
    /*
     * if we have direct access though the hypervisor do a direct call
     */
    if (domain->conn->handle >= 0) {
1118
        dom0_getdomaininfo_t dominfo;
1119 1120

	dominfo.domain = domain->handle;
1121 1122
        ret = xenHypervisorGetDomainInfo(domain->conn->handle, domain->handle,
	                                 &dominfo);
1123
        if (ret < 0)
1124 1125
	    goto xend_info;

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
	switch (dominfo.flags & 0xFF) {
	    case DOMFLAGS_DYING:
	        info->state = VIR_DOMAIN_SHUTDOWN;
		break;
	    case DOMFLAGS_SHUTDOWN:
	        info->state = VIR_DOMAIN_SHUTOFF;
		break;
	    case DOMFLAGS_PAUSED:
	        info->state = VIR_DOMAIN_PAUSED;
		break;
	    case DOMFLAGS_BLOCKED:
	        info->state = VIR_DOMAIN_BLOCKED;
		break;
	    case DOMFLAGS_RUNNING:
	        info->state = VIR_DOMAIN_RUNNING;
		break;
	    default:
	        info->state = VIR_DOMAIN_NONE;
	}
1145 1146 1147 1148

	/*
	 * the API brings back the cpu time in nanoseconds,
	 * convert to microseconds, same thing convert to
1149
         * kilobytes from page counts
1150
	 */
1151
	info->cpuTime = dominfo.cpu_time;
1152 1153
	info->memory = dominfo.tot_pages * 4;
	info->maxMem = dominfo.max_pages * 4;
1154
	info->nrVirtCpu = dominfo.nr_online_vcpus;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
	return(0);
    }

xend_info:
    /*
     * try to extract the informations though access to the Xen Daemon
     */
    if (xend_get_domain_info(domain, info) == 0)
        return(0);

    /*
     * last fallback, try to get the inforamtions from the Xen store
     */

    tmp = virDomainDoStoreQuery(domain, "running");
    if (tmp != NULL) {
	if (tmp[0] == '1')
	    info->state = VIR_DOMAIN_RUNNING;
	free(tmp);
    } else {
	info->state = VIR_DOMAIN_NONE;
    }
    tmp = virDomainDoStoreQuery(domain, "memory/target");
    if (tmp != NULL) {
	info->memory = atol(tmp);
	info->maxMem = atol(tmp);
	free(tmp);
    } else {
	info->memory = 0;
	info->maxMem = 0;
    }
#if 0
    /* doesn't seems to work */
    tmp = virDomainDoStoreQuery(domain, "cpu_time");
    if (tmp != NULL) {
	info->cpuTime = atol(tmp);
	free(tmp);
    } else {
	info->cpuTime = 0;
    }
#endif
    snprintf(request, 199, "/local/domain/%d/cpu", domain->handle);
    request[199] = 0;
    tmp2 = virConnectDoStoreList(domain->conn, request, &nb_vcpus);
    if (tmp2 != NULL) {
	info->nrVirtCpu = nb_vcpus;
	free(tmp2);
1202 1203 1204
    }
    return(0);
}
1205