virsh.c 2.4 KB
Newer Older
1
/*
2
 * virsh.c: a Xen shell used to exercise the libvir API
3 4 5 6 7 8 9 10
 *
 * Copyright (C) 2005 Red Hat, Inc.
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
 */

11
#include "libvir.h"
12
#include <stdio.h>
13 14
#include <unistd.h>
#include <sys/types.h>
15

16
#define MAX_DOM 100
17
int errcode = 0;
18 19
virConnectPtr conn;
virDomainPtr dom0;
20 21
int ids[MAX_DOM];

22
static void printDomain(virDomainPtr dom) {
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    virDomainInfo info;

    printf("id %d: name %s ", virDomainGetID(dom), virDomainGetName(dom));
    virDomainGetInfo(dom, &info);
    if (virDomainGetInfo(dom, &info) < 0) {
        printf("failed to get informations\n");
    } else {
        switch (info.state) {
	    case VIR_DOMAIN_RUNNING:
	        printf("running ");
		break;
            case VIR_DOMAIN_BLOCKED:
	        printf("blocked ");
		break;
            case VIR_DOMAIN_PAUSED:
	        printf("paused ");
		break;
            case VIR_DOMAIN_SHUTDOWN:
	        printf("in shutdown ");
		break;
            case VIR_DOMAIN_SHUTOFF:
	        printf("shut off ");
		break;
	    default:
	        break;
	}
        printf("%lu CPU time, %lu mem used, %lu max_mem\n",
	       info.cpuTime, info.pages * 4096, info.maxPages * 4096);
    }

53
}
54 55

int main(int argc, char **argv) {
56
    int ret, i;
57
    virDomainPtr dom;
58
    
59
    if (getuid() == 0) {
60
	conn = virConnectOpen(NULL);
61
    } else {
62
	conn = virConnectOpenReadOnly(NULL);
63
    }
64 65 66 67 68
    if (conn == NULL) {
        fprintf(stderr, "Failed to connect to the hypervisor\n");
        errcode = 1;
	goto done;
    }
69
    dom0 = virDomainLookupByID(conn, 0);
70 71 72 73 74
    if (dom0 == NULL) {
        fprintf(stderr, "Failed to get domain 0 informations\n");
	errcode = 2;
	goto done;
    }
75

76 77 78
    printf("Dom0: ");
    printDomain(dom0);

79
    ret = virConnectListDomains(conn, &ids[0], MAX_DOM);
80 81 82 83 84 85 86 87 88 89
    if (ret < 0) {
        fprintf(stderr, "Failed to list active domains\n");
	errcode = 3;
	goto done;
    }
    printf("Found %d more active domains\n", ret - 1);
    for (i = 0;i < ret;i++) {
        if (ids[i] == 0)
	    continue;
        printf("  ");
90
	dom = virDomainLookupByID(conn, ids[i]);
91 92 93 94 95 96 97
	if (dom == NULL) {
	    printf("domain %d disapeared\n", ids[i]);
	} else {
	    printDomain(dom);
	}
    }
    
98 99
done:
    if (conn != NULL) {
100
        ret = virConnectClose(conn);
101 102 103 104 105 106
	if (ret != 0) {
	    fprintf(stderr, "Failed to connect to the hypervisor\n");
	    if (errcode == 0)
		errcode = 1;
	}
    }
107
    return(errcode);
108
}