Exemplo n.º 1
0
int main(int argc, char **argv) {
    int id = 0;
    conn = virConnectOpenReadOnly(NULL);
    if (conn == NULL) {
        fprintf(stderr, "Failed to connect to hypervisor\n");
        goto error;
    }

    if (argc > 1) {
        id = atoi(argv[1]);
    }
    if (id == 0) {
        int i, j, ids[10];
        i = virConnectListDomains(conn, &ids[0], 10);
        if (i<0) {
            fprintf(stderr, "Failed to list the domains\n");
            goto error;
        }
        for (j = 0;j < i;j++) {
            if (ids[j] != 0) {
                id = ids[j];
                break;
            }
        }
    }
    if (id == 0) {
        fprintf(stderr, "Failed find a running guest domain\n");
        goto error;
   }

error:
    if (conn != NULL)
        virConnectClose(conn);
    return(0);
}
Exemplo n.º 2
0
int main(int argc, char *argv[])
{
virConnectPtr conn;
int i;
int numDomains;
int *activeDomains;
virDomainPtr dom;
conn = virConnectOpen("qemu:///system");
if (conn == NULL) {
fprintf(stderr, "Failed to open connection to qemu:///system\n");
}
numDomains = virConnectNumOfDomains(conn);
activeDomains = malloc(sizeof(int) * numDomains);
numDomains = virConnectListDomains(conn, activeDomains, numDomains);
printf("Active domain IDs:\n");
for (i = 0 ; i < numDomains ; i++) {
printf(" %d\n", activeDomains[i]);
}
printf("Terminating Domain\n");
free(activeDomains);
int domainName = "sudip";
dom = virDomainLookupByName(conn,domainName);
virDomainDestroy(dom);
virDomainFree(dom);
printf("Domain sudip terminated successfully\n");

if (conn != NULL)
virConnectClose(conn);
return 0;
}
void libvirt_connect() {
    int i;
    int *activeDomainIDs;

    // connect to xend
    conn = virConnectOpen("xen:///");
    if (conn == NULL) {
        printf("Failed to open connection to xen");
        exit(0);
    }

    // get the Domain ID list
    numDomains = virConnectNumOfDomains(conn);
    activeDomainIDs = (int*) malloc(sizeof(int) * numDomains);
    activeDomains = (virDomainPtr*) malloc(sizeof(virDomainPtr) * numDomains);
    numDomains = virConnectListDomains(conn, activeDomainIDs, numDomains);

    // associate the Domain ID list to Domain name list
    printf("Active domain IDs:\n");
    for (i = 0; i < numDomains; i++) {
        activeDomains[i] = virDomainLookupByID(conn, activeDomainIDs[i]);
        printf("  [%s - %d]\n", virDomainGetName(activeDomains[i]), activeDomainIDs[i]);
    }

    // Domain ID list is useless
    free(activeDomainIDs);
}
Exemplo n.º 4
0
int libvirt_node_info_update(NodeInfo * ni)
{
    if (g_conn == NULL || ni == NULL)
        return -1;

    int ret = -1;
    int cpu_commit = 0;
    unsigned int mem_commit = 0;
    int *activeDomains = NULL;

    __this_lock();

    int numDomains = virConnectNumOfDomains(g_conn);
    if (numDomains <= 0) {
        ret = numDomains;
        goto out;
    }

    activeDomains = malloc(sizeof(int) * numDomains);
    if (activeDomains == NULL) {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        goto out;
    }

    numDomains = virConnectListDomains(g_conn, activeDomains, numDomains);
    if (numDomains <= 0) {
        ret = numDomains;
        goto out;
    }
    for (int i = 0; i< numDomains; i++) {
        /* skip id dom 0 */
        if (activeDomains[i] == 0)
            continue;
        virDomainPtr d = virDomainLookupByID(g_conn, activeDomains[i]);
	if (d == NULL) {
            logerror(_("error in %s(%d)\n"), __func__, __LINE__);
            goto out;
        }
        virDomainInfo di;
	if (virDomainGetInfo(d, &di)) {
            logerror(_("error in %s(%d)\n"), __func__, __LINE__);
            goto out;
        }
        cpu_commit += di.nrVirtCpu;
        mem_commit += di.maxMem;
        virDomainFree(d);
    }
    ni->cpu_commit = cpu_commit;
    ni->mem_commit = mem_commit;
    ret = numDomains;

out:
    __this_unlock();

    if (activeDomains)
        free(activeDomains);

    return ret;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
	virConnectPtr conn;
	int i;
	int numDomains;
	int *activeDomains;
	char **inactiveDomains;
	
	conn = virConnectOpen("qemu:///system");
	if (conn == NULL) 
	{
		fprintf(stderr, "Failed to open connection to qemu:///system\n");
		return -1;
	}

	numDomains = virConnectNumOfDomains(conn);
	if (numDomains == -1) 
	{
		fprintf(stderr, "Failed to get domian num of qemu\n");
		return -1;
	}
	
	activeDomains = malloc(sizeof(int) * numDomains);
	numDomains = virConnectListDomains(conn, activeDomains, numDomains);
	
	printf("%d Active domain list:\n", numDomains);
	for (i = 0 ; i < numDomains ; i++) 
	{
		printf("ID = %d, Name = %s\n", activeDomains[i], virDomainGetName(virDomainLookupByID(conn, activeDomains[i])));
	}
	free(activeDomains);
	
	printf("----------------------------\n");
	numDomains = virConnectNumOfDefinedDomains(conn);
	
	if (numDomains == -1) 
	{
		fprintf(stderr, "Failed to get defined domian num of qemu\n");
		return -1;
	}
	
	inactiveDomains = malloc(sizeof(char *) * numDomains);
	numDomains = virConnectListDefinedDomains(conn, inactiveDomains, numDomains);
	printf("%d Inactive domain list:\n", numDomains);
	for (i = 0 ; i < numDomains ; i++) 
	{
		/*All inactive domains's id should be 0*/
		printf("ID = %d, Name = %s\n", virDomainGetID(virDomainLookupByName(conn, inactiveDomains[i])), inactiveDomains[i]);
		free(inactiveDomains[i]);
	}
	free(inactiveDomains);
	
	virConnectClose(conn);
	return 0;
}
Exemplo n.º 6
0
static int
registerExisting(virConnectPtr vp, const char *path, int mode)
{
	int *d_ids = NULL;
	int d_count, x;
	virDomainPtr dom;
	virDomainInfo d_info;

	errno = EINVAL;
	if (!vp)
		return -1;

	d_count = virConnectNumOfDomains(vp);
	if (d_count <= 0) {
		if (d_count == 0) {
			/* Successful, but no domains running */
			errno = 0;
			return 0;
		}
		goto out_fail;
	}

	d_ids = malloc(sizeof (int) * d_count);
	if (!d_ids)
		goto out_fail;

	if (virConnectListDomains(vp, d_ids, d_count) < 0)
		goto out_fail;

	/* Ok, we have the domain IDs - let's get their names and states */
	for (x = 0; x < d_count; x++) {
		dom = virDomainLookupByID(vp, d_ids[x]);
		if (!dom) {
			/* XXX doom */
			goto out_fail;
		}

		if (virDomainGetInfo(dom, &d_info) < 0) {
			/* XXX no info for the domain?!! */
			virDomainFree(dom);
			goto out_fail;
		}

		if (d_info.state != VIR_DOMAIN_SHUTOFF &&
		    d_info.state != VIR_DOMAIN_CRASHED)
			domainStarted(dom, path, mode);

		virDomainFree(dom);
	}

      out_fail:
	free(d_ids);
	return 0;
}
Exemplo n.º 7
0
static PromiseResult VerifyVirtDomain(EvalContext *ctx, char *uri, enum cfhypervisors envtype, Attributes a, const Promise *pp)
{
    int num, i;

/* set up the library error handler */
    virSetErrorFunc(NULL, (void *) EnvironmentErrorHandler);

    if (CFVC[envtype] == NULL)
    {
        if ((CFVC[envtype] = virConnectOpenAuth(uri, virConnectAuthPtrDefault, 0)) == NULL)
        {
            Log(LOG_LEVEL_ERR, "Failed to connect to virtualization monitor '%s'", uri);
            return PROMISE_RESULT_NOOP;
        }
    }

    for (i = 0; i < CF_MAX_CONCURRENT_ENVIRONMENTS; i++)
    {
        CF_RUNNING[i] = -1;
        CF_SUSPENDED[i] = NULL;
    }

    num = virConnectListDomains(CFVC[envtype], CF_RUNNING, CF_MAX_CONCURRENT_ENVIRONMENTS);
    Log(LOG_LEVEL_VERBOSE, "Found %d running guest environments on this host (including enclosure)", num);
    ShowRunList(CFVC[envtype]);
    num = virConnectListDefinedDomains(CFVC[envtype], CF_SUSPENDED, CF_MAX_CONCURRENT_ENVIRONMENTS);
    Log(LOG_LEVEL_VERBOSE, "Found %d dormant guest environments on this host", num);
    ShowDormant();

    PromiseResult result = PROMISE_RESULT_NOOP;
    switch (a.env.state)
    {
    case ENVIRONMENT_STATE_CREATE:
        result = PromiseResultUpdate(result, CreateVirtDom(ctx, CFVC[envtype], a, pp));
        break;
    case ENVIRONMENT_STATE_DELETE:
        result = PromiseResultUpdate(result, DeleteVirt(ctx, CFVC[envtype], a, pp));
        break;
    case ENVIRONMENT_STATE_RUNNING:
        result = PromiseResultUpdate(result, RunningVirt(ctx, CFVC[envtype], a, pp));
        break;
    case ENVIRONMENT_STATE_SUSPENDED:
        result = PromiseResultUpdate(result, SuspendedVirt(ctx, CFVC[envtype], a, pp));
        break;
    case ENVIRONMENT_STATE_DOWN:
        result = PromiseResultUpdate(result, DownVirt(ctx, CFVC[envtype], a, pp));
        break;
    default:
        Log(LOG_LEVEL_INFO, "No state specified for this environment");
        break;
    }

    return result;
}
Exemplo n.º 8
0
static void VerifyVirtDomain(EvalContext *ctx, char *uri, enum cfhypervisors envtype, Attributes a, Promise *pp)
{
    int num, i;

/* set up the library error handler */
    virSetErrorFunc(NULL, (void *) EnvironmentErrorHandler);

    if (CFVC[envtype] == NULL)
    {
        if ((CFVC[envtype] = virConnectOpenAuth(uri, virConnectAuthPtrDefault, 0)) == NULL)
        {
            CfOut(OUTPUT_LEVEL_ERROR, "", " !! Failed to connect to virtualization monitor \"%s\"", uri);
            return;
        }
    }

    for (i = 0; i < CF_MAX_CONCURRENT_ENVIRONMENTS; i++)
    {
        CF_RUNNING[i] = -1;
        CF_SUSPENDED[i] = NULL;
    }

    num = virConnectListDomains(CFVC[envtype], CF_RUNNING, CF_MAX_CONCURRENT_ENVIRONMENTS);
    CfOut(OUTPUT_LEVEL_VERBOSE, "", " -> Found %d running guest environments on this host (including enclosure)", num);
    ShowRunList(CFVC[envtype]);
    num = virConnectListDefinedDomains(CFVC[envtype], CF_SUSPENDED, CF_MAX_CONCURRENT_ENVIRONMENTS);
    CfOut(OUTPUT_LEVEL_VERBOSE, "", " -> Found %d dormant guest environments on this host", num);
    ShowDormant();

    switch (a.env.state)
    {
    case ENVIRONMENT_STATE_CREATE:
        CreateVirtDom(ctx, CFVC[envtype], a, pp);
        break;
    case ENVIRONMENT_STATE_DELETE:
        DeleteVirt(ctx, CFVC[envtype], a, pp);
        break;
    case ENVIRONMENT_STATE_RUNNING:
        RunningVirt(ctx, CFVC[envtype], a, pp);
        break;
    case ENVIRONMENT_STATE_SUSPENDED:
        SuspendedVirt(ctx, CFVC[envtype], a, pp);
        break;
    case ENVIRONMENT_STATE_DOWN:
        DownVirt(ctx, CFVC[envtype], a, pp);
        break;
    default:
        CfOut(OUTPUT_LEVEL_INFORM, "", " !! No state specified for this environment");
        break;
    }
}
Exemplo n.º 9
0
static void VerifyVirtDomain(char *uri, enum cfhypervisors envtype, Attributes a, Promise *pp)
{
    int num, i;

/* set up the library error handler */
    virSetErrorFunc(NULL, (void *) EnvironmentErrorHandler);

    if (CFVC[envtype] == NULL)
    {
        if ((CFVC[envtype] = virConnectOpenAuth(uri, virConnectAuthPtrDefault, 0)) == NULL)
        {
            CfOut(cf_error, "", " !! Failed to connect to virtualization monitor \"%s\"", uri);
            return;
        }
    }

    for (i = 0; i < CF_MAX_CONCURRENT_ENVIRONMENTS; i++)
    {
        CF_RUNNING[i] = -1;
        CF_SUSPENDED[i] = NULL;
    }

    num = virConnectListDomains(CFVC[envtype], CF_RUNNING, CF_MAX_CONCURRENT_ENVIRONMENTS);
    CfOut(cf_verbose, "", " -> Found %d running guest environments on this host (including enclosure)", num);
    ShowRunList(CFVC[envtype]);
    num = virConnectListDefinedDomains(CFVC[envtype], CF_SUSPENDED, CF_MAX_CONCURRENT_ENVIRONMENTS);
    CfOut(cf_verbose, "", " -> Found %d dormant guest environments on this host", num);
    ShowDormant(CFVC[envtype]);

    switch (a.env.state)
    {
    case cfvs_create:
        CreateVirtDom(CFVC[envtype], uri, a, pp);
        break;
    case cfvs_delete:
        DeleteVirt(CFVC[envtype], uri, a, pp);
        break;
    case cfvs_running:
        RunningVirt(CFVC[envtype], uri, a, pp);
        break;
    case cfvs_suspended:
        SuspendedVirt(CFVC[envtype], uri, a, pp);
        break;
    case cfvs_down:
        DownVirt(CFVC[envtype], uri, a, pp);
        break;
    default:
        CfOut(cf_inform, "", " !! No state specified for this environment");
        break;
    }
}
Exemplo n.º 10
0
Arquivo: virt.cpp Projeto: kohn/rsi
std::string VM_Controller::get_vm_info(){
    Json::Value j(Json::arrayValue);
    int numActiveDomains = virConnectNumOfDomains(_conn);
    int *activeDomainsIDs = (int *)malloc(sizeof(int) * numActiveDomains);
    
    numActiveDomains = virConnectListDomains(_conn,
                                             activeDomainsIDs,
                                             numActiveDomains);
    for (int i = 0 ; i < numActiveDomains ; i++) {
        virDomainPtr dom = virDomainLookupByID(_conn, activeDomainsIDs[i]);
        virDomainInfo info;
        if(virDomainGetInfo(dom, &info) < 0){
            LOG_ERROR("could not get domain info");
            continue;
        }
        Json::Value j_dom(Json::objectValue);
        j_dom["id"] = activeDomainsIDs[i];
        j_dom["mem_total"] = (unsigned long long)info.maxMem;
        j_dom["vcpu"] = info.nrVirtCpu;
        j_dom["name"] = virDomainGetName(dom);
        j_dom["status"] = "running";
        j.append(j_dom);
    }
    free(activeDomainsIDs);

    int numInactiveDomains = virConnectNumOfDefinedDomains(_conn);
    char **inactiveDomainsNames = (char **)malloc(sizeof(char *)
                                                  * numInactiveDomains);
    numInactiveDomains = virConnectListDefinedDomains(_conn,
                                                      inactiveDomainsNames,
                                                      numInactiveDomains);
    if(numInactiveDomains < 0){
        LOG_ERROR("could not get defined domains");
        exit(-1);
    }
    
    for(int i=0; i< numInactiveDomains; i++){
        Json::Value j_dom(Json::objectValue);
        j_dom["status"] = "shutoff";
        j_dom["name"] = inactiveDomainsNames[i];
        free(inactiveDomainsNames[i]);
        j.append(j_dom);
    }
    free(inactiveDomainsNames);
    
    return j.toStyledString();
}
Exemplo n.º 11
0
static void refreshDomains(void)
{
	int i,*activeDomains;
	char *domName;
	char shc[50];

	for (i=0; i<MAX_DOMAINS;i++)
	{
		vms[i].dom = NULL;
        vms[i].pid = -1;
        memset(vms[i].ip,0,20*sizeof(char));
	}

	numDomains = virConnectNumOfDomains(conn);
    activeDomains = malloc(sizeof(int) * numDomains);
    numDomains = virConnectListDomains(conn, activeDomains, numDomains);

	if (numDomains==0)
	{
		printf("No active VMs\n");
		return -1;
	}

	for (i = 0 ; i < numDomains ; i++)
	{
		memset(shc,0,50*sizeof(char));

	    vms[i].dom = virDomainLookupByID(conn, activeDomains[i]);
	    domName = virDomainGetName(vms[i].dom);
	    sprintf(shc,"./vm-ip.sh %s", domName);
        pid=0;
	    examineVM(domName);
        vms[i].pid=pid;
        runShell(shc, vms[i].ip, 20);
        printf("Process %d runs the virtual machine %s on IP %s\n ", vms[i].pid, domName, vms[i].ip);
	}
	printf("\n");
    //initVMIFile(numDomains, sysmap);
	free(activeDomains);
}
Exemplo n.º 12
0
int main()
{
    int idCount;
    int i;
    int id;
    //int ids[MAXID];
	int *ids;
    //timeInfoNode timeInfos[MAXID];

    printf("--------------------------------------------------------\n");
    printf("             XEN Domain Monitor \n");
    printf("--------------------------------------------------------\n");

    /* NULL means connect to local Xen hypervisor */
    conn = virConnectOpenReadOnly(NULL);
    if (conn == NULL)
    {
        fprintf(stderr, "Failed to connect to hypervisor\n");
        closeConn();
        return 0;
    }

	/*char* caps;
	caps = virConnectGetCapabilities(conn);
	printf("Capabilities:\n%s\n",caps);
	free(caps);*/
	char *host;
	host = virConnectGetHostname(conn);
	fprintf(stdout, "Hostname:%s\n",host);
	free(host);
	int vcpus;
	vcpus = virConnectGetMaxVcpus(conn,NULL);
	fprintf(stdout, "Maxmum support vcpus:%d\n",vcpus);
	unsigned long long node_free_memory;
	node_free_memory = virNodeGetFreeMemory(conn);
	fprintf(stdout, "free memory:%lld\n",node_free_memory);
	virNodeInfo nodeinfo;
	virNodeGetInfo(conn,&nodeinfo);
	fprintf(stdout, "Model: %s\n", nodeinfo.model);
    fprintf(stdout, "Memory size: %lukb\n", nodeinfo.memory);
    fprintf(stdout, "Number of CPUs: %u\n", nodeinfo.cpus);
    fprintf(stdout, "MHz of CPUs: %u\n", nodeinfo.mhz);
    fprintf(stdout, "Number of NUMA nodes: %u\n", nodeinfo.nodes);
    fprintf(stdout, "Number of CPU sockets: %u\n", nodeinfo.sockets);
    fprintf(stdout, "Number of CPU cores per socket: %u\n", nodeinfo.cores);
    fprintf(stdout, "Number of CPU threads per core: %u\n", nodeinfo.threads);	
    fprintf(stdout, "Virtualization type: %s\n", virConnectGetType(conn));
	unsigned long ver;
	virConnectGetVersion(conn, &ver);
	fprintf(stdout, "Version: %lu\n", ver);
	/*unsigned long Libver;
	virConnectGetLibVersion(conn, &Libver);
	fprintf(stdout, "Libvirt Version: %lu\n", Libver);*/
	char *uri;
	uri = virConnectGetURI(conn);
	fprintf(stdout, "Canonical URI: %s\n", uri);
	free(uri);
	/* get the count of IDs and save these ID into ids[] */
    idCount = virConnectNumOfDomains(conn);
	ids = malloc(sizeof(int) *idCount);
	idCount = virConnectListDomains(conn,ids,idCount);
	//idCount = virConnectListDomains(conn, &ids[0], MAXID);
    if (idCount < 0)
    {
        fprintf(stderr, "Failed to list the domains\n");
        closeConn();
        return 0;
    }

    timeInfoNode timeInfos[idCount];
	printf("Domain Totals: %d\n", idCount);
    printf("ID\tCPU\tMEM\tMaxMEM\tVCPUs\tState\tNAME\n");

    /* loop get the CPUtime info by IDs */
    for (i = 0; i < idCount; i++)
    {
        id = ids[i];
        getTimeInfo(id, &(timeInfos[i]));
    }

    sleep(1);

    /* loop print the domain info and calculate the usage of cpus*/
    for (i = 0; i < idCount; i++)
    {
        id = ids[i];
        getDomainInfo(id, timeInfos[i]);
    }

    free(ids);
	printf("--------------------------------------------------------\n");
    closeConn();
    return 0;
}
Exemplo n.º 13
0
int get_domain_list(virConnectPtr conn, virDomainPtr **_list)
{
        char **names = NULL;
        int n_names;
        int *ids = NULL;
        int n_ids;
        virDomainPtr *list = NULL;
        int i;
        int idx = 0;

        n_names = virConnectNumOfDefinedDomains(conn);
        n_ids = virConnectNumOfDomains(conn);

        if ((n_names < 0) || (n_ids < 0))
                goto out;

        list = calloc(n_names + n_ids, sizeof(virDomainPtr));
        if (!list)
                return 0;

        if (n_names > 0) {
                names = calloc(n_names, sizeof(char *));
                if (!names)
                        goto out;
                
                
#if LIBVIR_VERSION_NUMBER<=2000
                n_names = virConnectListDefinedDomains(conn, 
                                                       (const char **)names, 
                                                       n_names);
#else
                n_names = virConnectListDefinedDomains(conn, 
                                                       (char ** const)names, 
                                                       n_names);
#endif
                if (n_names < 0)
                        goto out;
        }

        for (i = 0; i < n_names; i++) {
                virDomainPtr dom;
                
                dom = virDomainLookupByName(conn, names[i]);
                if (dom)
                        list[idx++] = dom;

                free(names[i]);
        }

        if (n_ids > 0) {
                ids = calloc(n_ids, sizeof(int));
                if (!ids)
                        goto out;
                
                n_ids = virConnectListDomains(conn, ids, n_ids);
                if (n_ids < 0)
                        goto out;
        }

        for (i = 0; i < n_ids; i++) {
                virDomainPtr dom;

                dom = virDomainLookupByID(conn, ids[i]);
                if (dom)
                        list[idx++] = dom;
        }

 out:
        free(names);
        free(ids);

        if (idx == 0) {
                free(list);
                list = NULL;
        }

        *_list = list;

        return idx;
}
Exemplo n.º 14
0
void
get_all_libvirt_domains (const char *libvirt_uri)
{
  virErrorPtr err;
  int n;
  size_t i;

  /* Get the list of all domains. */
  conn = virConnectOpenAuth (libvirt_uri, virConnectAuthPtrDefault,
                             VIR_CONNECT_RO);
  if (!conn) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not connect to libvirt (code %d, domain %d): %s\n"),
             guestfs_int_program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  n = virConnectNumOfDomains (conn);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not get number of running domains (code %d, domain %d): %s\n"),
             guestfs_int_program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  int ids[n];
  n = virConnectListDomains (conn, ids, n);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not list running domains (code %d, domain %d): %s\n"),
             guestfs_int_program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  add_domains_by_id (conn, ids, n);

  n = virConnectNumOfDefinedDomains (conn);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not get number of inactive domains (code %d, domain %d): %s\n"),
             guestfs_int_program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  char *names[n];
  n = virConnectListDefinedDomains (conn, names, n);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not list inactive domains (code %d, domain %d): %s\n"),
             guestfs_int_program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  add_domains_by_name (conn, names, n);

  /* You must free these even though the libvirt documentation doesn't
   * mention it.
   */
  for (i = 0; i < (size_t) n; ++i)
    free (names[i]);

  /* No domains? */
  if (nr_domains == 0)
    return;

  /* Sort the domains alphabetically by name for display. */
  qsort (domains, nr_domains, sizeof (struct domain), compare_domain_names);
}
Exemplo n.º 15
0
//!
//!
//!
//! @param[in] ptr
//!
//! @return Always returns NULL
//!
static void *tortura_thread(void *ptr)
{
    int i = 0;
    int iter = 0;
    int error = 0;
    int num_doms = 0;
    int dom_ids[MAXDOMS] = { 0 };
    long long tid = (*(long long *)ptr);
    virDomainPtr dom[MAXDOMS] = { NULL };
    virDomainInfo info[MAXDOMS] = { 0 };

    check_hypervisor_conn();
    for (iter = 0; iter < ITERS; iter++) {
        printf("thread %lld starting iteration %d\n", tid, iter);

        pthread_mutex_lock(&check_mutex);
        {
            num_doms = virConnectListDomains(conn, dom_ids, MAXDOMS);
        }
        pthread_mutex_unlock(&check_mutex);

        for (i = 0; i < num_doms; i++) {
            pthread_mutex_lock(&check_mutex);
            {
                dom[i] = virDomainLookupByID(conn, dom_ids[i]);
            }
            pthread_mutex_unlock(&check_mutex);

            if (!dom[i]) {
                printf("failed to look up domain %d\n", dom_ids[i]);
                continue;
            }
        }

        for (i = 0; i < num_doms; i++) {
            pthread_mutex_lock(&check_mutex);
            {
                error = virDomainGetInfo(dom[i], &info[i]);
            }
            pthread_mutex_unlock(&check_mutex);

            if (error < 0) {
                printf("failed to get info on domain %d\n", dom_ids[i]);
                continue;
            }
        }

        for (i = 0; i < num_doms; i++) {
            pthread_mutex_lock(&check_mutex);
            {
                error = virDomainFree(dom[i]);
            }
            pthread_mutex_unlock(&check_mutex);

            if (error < 0) {
                printf("failed to close domain %d\n", dom_ids[i]);
                continue;
            }
        }
    }

    return (NULL);
}
Exemplo n.º 16
0
void NodeWrap::syncDomains()
{
    /* Sync up with domains that are defined but not active. */
    int maxname = virConnectNumOfDefinedDomains(conn);
    if (maxname < 0) {
        REPORT_ERR(conn, "virConnectNumOfDefinedDomains");
        return;
    } else {
        char **dnames;
        dnames = (char **) malloc(sizeof(char *) * maxname);

        if ((maxname = virConnectListDefinedDomains(conn, dnames, maxname)) < 0) {
            REPORT_ERR(conn, "virConnectListDefinedDomains");
            free(dnames);
            return;
        }


        for (int i = 0; i < maxname; i++) {
            virDomainPtr domain_ptr;

            bool found = false;
            for (std::vector<DomainWrap*>::iterator iter = domains.begin();
                    iter != domains.end(); iter++) {
                if ((*iter)->domain_name == dnames[i]) {
                    found = true;
                    break;
                }
            }

            if (found) {
                continue;
            }

            domain_ptr = virDomainLookupByName(conn, dnames[i]);
            if (!domain_ptr) {
                REPORT_ERR(conn, "virDomainLookupByName");
            } else {
                DomainWrap *domain;
                try {
                    domain = new DomainWrap(agent, this, domain_ptr, conn);
                    printf("Created new domain: %s, ptr is %p\n", dnames[i], domain_ptr);
                    domains.push_back(domain);
                } catch (int i) {
                    printf ("Error constructing domain\n");
                    REPORT_ERR(conn, "constructing domain.");
                    delete domain;
                }
            }
        }
        for (int i = 0; i < maxname; i++) {
            free(dnames[i]);
        }

        free(dnames);
    }

    /* Go through all the active domains */
    int maxids = virConnectNumOfDomains(conn);
    if (maxids < 0) {
        REPORT_ERR(conn, "virConnectNumOfDomains");
        return;
    } else {
        int *ids;
        ids = (int *) malloc(sizeof(int *) * maxids);

        if ((maxids = virConnectListDomains(conn, ids, maxids)) < 0) {
            printf("Error getting list of defined domains\n");
            return;
        }

        for (int i = 0; i < maxids; i++) {
            virDomainPtr domain_ptr;
            char dom_uuid[VIR_UUID_STRING_BUFLEN];

            domain_ptr = virDomainLookupByID(conn, ids[i]);
            if (!domain_ptr) {
                REPORT_ERR(conn, "virDomainLookupByID");
                continue;
            }

            if (virDomainGetUUIDString(domain_ptr, dom_uuid) < 0) {
                REPORT_ERR(conn, "virDomainGetUUIDString");
                continue;
            }

            bool found = false;
            for (std::vector<DomainWrap*>::iterator iter = domains.begin();
                    iter != domains.end(); iter++) {
                if (strcmp((*iter)->domain_uuid.c_str(), dom_uuid) == 0) {
                    found = true;
                    break;
                }
            }

            if (found) {
                virDomainFree(domain_ptr);
                continue;
            }

            DomainWrap *domain;
            try {
                domain = new DomainWrap(agent, this, domain_ptr, conn);
                printf("Created new domain: %d, ptr is %p\n", ids[i], domain_ptr);
                domains.push_back(domain);
            } catch (int i) {
                printf ("Error constructing domain\n");
                REPORT_ERR(conn, "constructing domain.");
                delete domain;
            }
        }

        free(ids);
    }

    /* Go through our list of domains and ensure that they still exist. */
    for (std::vector<DomainWrap*>::iterator iter = domains.begin(); iter != domains.end();) {

        printf("verifying domain %s\n", (*iter)->domain_name.c_str());
        virDomainPtr ptr = virDomainLookupByUUIDString(conn, (*iter)->domain_uuid.c_str());
        if (ptr == NULL) {
            REPORT_ERR(conn, "virDomainLookupByUUIDString");
            delete (*iter);
            iter = domains.erase(iter);
        } else {
            virDomainFree(ptr);
            iter++;
        }
    }
}
Exemplo n.º 17
0
void adopt_instances()
{
	int dom_ids[MAXDOMS];
	int num_doms = 0;
	int i;
       	virDomainPtr dom = NULL;

	if (! check_hypervisor_conn())
		return;
        
	logprintfl (EUCAINFO, "looking for existing domains\n");
	virSetErrorFunc (NULL, libvirt_error_handler);
        
	num_doms = virConnectListDomains(nc_state.conn, dom_ids, MAXDOMS);
	if (num_doms == 0) {
		logprintfl (EUCAINFO, "no currently running domains to adopt\n");
		return;
	} if (num_doms < 0) {
		logprintfl (EUCAWARN, "WARNING: failed to find out about running domains\n");
		return;
	}

	for ( i=0; i<num_doms; i++) {
		int error;
		virDomainInfo info;
		const char * dom_name;
		ncInstance * instance;

		sem_p(hyp_sem);
		dom = virDomainLookupByID(nc_state.conn, dom_ids[i]);
		sem_v(hyp_sem);
		if (!dom) {
			logprintfl (EUCAWARN, "WARNING: failed to lookup running domain #%d, ignoring it\n", dom_ids[i]);
			continue;
		}

		sem_p(hyp_sem);
		error = virDomainGetInfo(dom, &info);
		sem_v(hyp_sem);
		if (error < 0 || info.state == VIR_DOMAIN_NOSTATE) {
			logprintfl (EUCAWARN, "WARNING: failed to get info on running domain #%d, ignoring it\n", dom_ids[i]);
			continue;
		}

		if (info.state == VIR_DOMAIN_SHUTDOWN ||
				info.state == VIR_DOMAIN_SHUTOFF ||
				info.state == VIR_DOMAIN_CRASHED ) {
			logprintfl (EUCADEBUG, "ignoring non-running domain #%d\n", dom_ids[i]);
			continue;
		}

		sem_p(hyp_sem);
		if ((dom_name = virDomainGetName(dom))==NULL) {
		        sem_v(hyp_sem);
		        logprintfl (EUCAWARN, "WARNING: failed to get name of running domain #%d, ignoring it\n", dom_ids[i]);
			continue;
		}
		sem_v(hyp_sem);

		if (!strcmp(dom_name, "Domain-0"))
			continue;

		if ((instance = scRecoverInstanceInfo (dom_name))==NULL) {
			logprintfl (EUCAWARN, "WARNING: failed to recover Eucalyptus metadata of running domain %s, ignoring it\n", dom_name);
			continue;
		}

		change_state (instance, info.state);                    
		sem_p (inst_sem);
		int err = add_instance (&global_instances, instance);
		sem_v (inst_sem);
		if (err) {
			free_instance (&instance);
			continue;
		}

		logprintfl (EUCAINFO, "- adopted running domain %s from user %s\n", instance->instanceId, instance->userId);
		/* TODO: try to look up IPs? */

		sem_p(hyp_sem);
		virDomainFree (dom);
		sem_v(hyp_sem);
	}
}
Exemplo n.º 18
0
int default_selector(virConnectPtr conn, virDomainPtr domsPtr_sche_lst[], int *domPtr_sche_lst_nxt)
{
	int doms_actvie_nxt = 0;
	virDomainPtr domsPtr_active_lst[MAX_DOMS_NR];
	virDomainInfo domain_info;

	int i = 0;
	int *dom_active_id_lst;
	double dom_cpu_uti = 0.0;

	/*
	 * 	get the active domain, store the domian_ptr in doms_active_Ptr_lst[i];
	 */
	doms_actvie_nxt = virConnectNumOfDomains(conn);
	if(doms_actvie_nxt < 0){
		perror("failed to execute virConnectNumOfDomains");
		return ERROR;
	}
	dom_active_id_lst = malloc(sizeof(int) * doms_actvie_nxt);
	doms_actvie_nxt = virConnectListDomains(conn, dom_active_id_lst, doms_actvie_nxt);
	if(doms_actvie_nxt < 0){
		perror("failed to execute virConnectListDomains");
		return ERROR;
	}

	for(i = 0; i < doms_actvie_nxt; i++){
		domsPtr_active_lst[i] = virDomainLookupByID(conn, dom_active_id_lst[i]);
		if(domsPtr_active_lst[i] == NULL){
			perror("failed to execute virDomainLookupByID");
			return ERROR;
		}

	}
	free(dom_active_id_lst);
	dom_active_id_lst = NULL;

	/*
	 * 	query every domains's used memory
	 * 	set domsPtr_active_lst[i] = NULL,
	 * 	if the domain's mem is less than the MEM_THREASHOLD.
	 */

	for(i = 0; i < doms_actvie_nxt; i++){
		if(virDomainGetInfo(domsPtr_active_lst[i], &domain_info) < 0){
			perror("failed to virDomainGetInfo");
			return ERROR;
		}

		//DEBUG print every domain memory.
		printf("dom_mem_max : %d\n", domain_info.maxMem);
		printf("dom_mem_used : %d\n", domain_info.memory);

		if(domain_info.memory < MEM_THRESHOLD){
			free(domsPtr_active_lst[i]);
			domsPtr_active_lst[i] = NULL;
		}
	}

	/*
	 * 	query every domain CPU total utilization.
	 * 	populate domsPtr_sche_lst
	 */
	*domPtr_sche_lst_nxt = 0;
	for(i = 0; i < doms_actvie_nxt; i++){
		if(domsPtr_active_lst[i] != NULL){
			dom_cpu_uti = domain_get_cpu_util(conn, domsPtr_active_lst[i]);
			//DEBUG print every domain cpu_utili.
			printf("dom_cpu_utilization : %f\n",dom_cpu_uti);
			if(dom_cpu_uti > CPU_THRESHOLD)
				domsPtr_sche_lst[(*domPtr_sche_lst_nxt)++] = domsPtr_active_lst[i];
			else
				continue;
		}
	}
	return SUCCESS;
}
Exemplo n.º 19
0
void
get_domains_from_libvirt (void)
{
  virErrorPtr err;
  virConnectPtr conn;
  int n;
  size_t i, j, nr_disks_added;

  nr_domains = 0;
  domains = NULL;

  /* Get the list of all domains. */
  conn = virConnectOpenReadOnly (libvirt_uri);
  if (!conn) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not connect to libvirt (code %d, domain %d): %s"),
             program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  n = virConnectNumOfDomains (conn);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not get number of running domains (code %d, domain %d): %s"),
             program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  int ids[n];
  n = virConnectListDomains (conn, ids, n);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not list running domains (code %d, domain %d): %s"),
             program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  add_domains_by_id (conn, ids, n);

  n = virConnectNumOfDefinedDomains (conn);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not get number of inactive domains (code %d, domain %d): %s"),
             program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  char *names[n];
  n = virConnectListDefinedDomains (conn, names, n);
  if (n == -1) {
    err = virGetLastError ();
    fprintf (stderr,
             _("%s: could not list inactive domains (code %d, domain %d): %s"),
             program_name, err->code, err->domain, err->message);
    exit (EXIT_FAILURE);
  }

  add_domains_by_name (conn, names, n);

  /* You must free these even though the libvirt documentation doesn't
   * mention it.
   */
  for (i = 0; i < (size_t) n; ++i)
    free (names[i]);

  virConnectClose (conn);

  /* No domains? */
  if (nr_domains == 0)
    return;

  /* Sort the domains alphabetically by name for display. */
  qsort (domains, nr_domains, sizeof (struct domain), compare_domain_names);

  print_title ();

  /* To minimize the number of times we have to launch the appliance,
   * shuffle as many domains together as we can, but not exceeding
   * MAX_DISKS per request.  If --one-per-guest was requested then only
   * request disks from a single guest each time.
   * Interesting application for NP-complete knapsack problem here.
   */
  if (one_per_guest) {
    for (i = 0; i < nr_domains; ++i)
      multi_df (&domains[i], 1);
  } else {
    for (i = 0; i < nr_domains; /**/) {
      nr_disks_added = 0;

      /* Make a request with domains [i..j-1]. */
      for (j = i; j < nr_domains; ++j) {
        if (nr_disks_added + domains[j].nr_disks > MAX_DISKS)
          break;
        nr_disks_added += domains[j].nr_disks;
      }
      multi_df (&domains[i], j-i);

      i = j;
    }
  }

  /* Free up domains structure. */
  for (i = 0; i < nr_domains; ++i)
    free_domain (&domains[i]);
  free (domains);
}
Exemplo n.º 20
0
void main()
{

    int i,val=-1,choice,choice_id,num_domains;
    int *active_domains;
    virConnectPtr conn;
    virDomainPtr vdp;

    conn = virConnectOpen("xen:///");

    if (conn == NULL) {
        fprintf(stderr, "Error opening connection to XEN:///  \n");
        return 1;
    }
    else
    {

		//For finding Active Devices
        num_domains=virConnectNumOfDomains(conn);
        active_domanins=malloc(sizeof(int) * num_domains);
        num_domains = virConnectListDomains(conn, active_domains, num_domains);

        printf("Active domain IDs : \n");
        for (i = 0 ; i < num_domains ; i++) {
            printf("  %d\n", active_domains[i]);
        }
        free(active_domains);

        while(1)
        {
            
            printf("1.Start\n2.Suspend\n3.Resume\n4.stop\n5.exit ");
            scanf("%d",&choice);

            printf("\n Please Insert the Active Domian ID ");
            scanf("%d",&choice_id);
  
            vdp=virDomainLookupById(conn,choice_id);
        
            switch(choice)
            {
                case 1:/* Start */
		       val=virDomainCreate(vdp);
                       if(val==0)      
                           printf("Success");
                       else
                           printf("Failed");   
                       break;
                case 2:/* Suspend */
		       val=virDomainSuspend(vdp);
                       if(val==0)
                           printf("Success");
                       else
                           printf("Failed");   
                       break;
                case 3:/* Resume */ 
		        val=virDomainResume(vdp);
                        if(val==0)                     
                            printf("Success");
                        else
                            printf("Failed");   
                        break;

                case 4: /* stop */
			val=virDomainStop(vdp);
                        if(val==0)                     
                            printf("Success");
                        else
                            printf("Failed");   
                        break;
                default:exit(1);
            }
        }
        virConnectClose(conn);
    }
}
Exemplo n.º 21
0
int main (int argc, char * argv[])
{ 
    virConnectPtr conn = NULL;
    int dom_ids [MAXDOMS];
    int num_doms = 0;
    char *hypervisor, hypervisorURL[32], cmd[1024];
    char *eucahome=NULL;
    
    //  logfile (NULL, EUCAFATAL); // suppress all messages
    
    if (argc != 2) {
        fprintf (stderr, "error: test_nc expects one parameter (name of hypervisor)\n");
        exit (1);
    }
    
    hypervisor = argv[1];
    if (!strcmp(hypervisor, "kvm")) {
        snprintf(hypervisorURL, 32, "qemu:///system");
    } else if (!strcmp(hypervisor, "xen")) {
        snprintf(hypervisorURL, 32, "xen:///");      
    } else if (!strcmp(hypervisor, "not_configured")) {
        fprintf (stderr, "error: HYPERVISOR variable is not set in eucalyptus.conf\n");
        exit (1);
    } else {
        fprintf (stderr, "error: hypervisor type (%s) is not recognized\n", hypervisor);
        exit (1);
    }
    
    // check that commands that NC needs are there
    
    if (system("perl --version")) {
        fprintf (stderr, "error: could not run perl\n");
        exit (1);
    }
    
    eucahome = getenv (EUCALYPTUS_ENV_VAR_NAME);
    if (!eucahome) {
        eucahome = strdup (""); // root by default
    } else {
        eucahome = strdup(eucahome);
    }
    
    add_euca_to_path (eucahome);

    fprintf (stderr, "looking for system utilities...\n");
    if (diskutil_init(FALSE)) // NC does not require GRUB for now
        exit (1);
    
    // check if euca2ools commands for bundle-instance are available
    fprintf (stderr, "ok\n\nlooking for euca2ools...\n");
    static char * helpers_name [3] = {
        "euca-bundle-upload",
        "euca-check-bucket",
        "euca-delete-bundle"
    };

    char * helpers_path [3]; // load paths from eucalyptus.conf or set to NULL
    helpers_path [0] = find_conf_value (eucahome, "NC_BUNDLE_UPLOAD_PATH");
    helpers_path [1] = find_conf_value (eucahome, "NC_CHECK_BUCKET_PATH");
    helpers_path [2] = find_conf_value (eucahome, "NC_DELETE_BUNDLE_PATH");

    if (verify_helpers (helpers_name, helpers_path, 3) > 0) {
       if (verify_helpers (helpers_name, NULL, 3) > 0) {
             fprintf (stderr, "error: failed to find required euca2ools\n");
             exit (1);
       }
    }

    // ensure hypervisor information is available
    fprintf (stderr, "ok\n\nchecking the hypervisor...\n");
    if (!strcmp(hypervisor, "kvm")) {
        snprintf(cmd, 1024, "%s/usr/lib/eucalyptus/euca_rootwrap %s/usr/share/eucalyptus/get_sys_info", eucahome, eucahome);
    } else {
        snprintf(cmd, 1024, "%s/usr/lib/eucalyptus/euca_rootwrap %s/usr/share/eucalyptus/get_xen_info", eucahome, eucahome);
    }
    if (system(cmd)) {
        fprintf (stderr, "error: could not run '%s'\n", cmd);
        exit (1);
    }
    
    // check that libvirt can query the hypervisor
    conn = virConnectOpen (hypervisorURL); // NULL means local hypervisor
    if (conn == NULL) {
        print_libvirt_error ();
        fprintf (stderr, "error: failed to connect to hypervisor\n");
        exit (1);
    }
    
    num_doms = virConnectListDomains (conn, dom_ids, MAXDOMS);
    if (num_doms < 0) {
        print_libvirt_error ();
        fprintf (stderr, "error: failed to query running domains\n");
        exit (1);
    }

    fprintf (stdout, "NC test was successful\n");
    return 0;
}
Exemplo n.º 22
0
void main()
{
    virConnectPtr connection;
    virDomainPtr vdp_id, vdp_name;
    int i,ret_val=-1;
    int ch,ch_id,domainnum;
    int *domains;
    char name[25];
    const char *active_name;
    connection = virConnectOpen("xen:///");

    if (connection == NULL) 
    {    fprintf(stderr, "Error opening connection to XEN:///  \n");
        exit(1);
    }
    else
    {
        domainnum=virConnectNumOfDomains(connection);
        domains=malloc(sizeof(int) * domainnum);
        domainnum = virConnectListDomains(connection, domains, domainnum);
    
        printf("\t\t ----Active Domains----  \n");
        for (i = 0 ; i < domainnum ; i++) 
        {
            vdp_id=virDomainLookupByID(connection,i);
            active_name=virDomainGetName(vdp_id);
            printf(" \t\t%s \n", active_name);
         }
         free(domains);

        while(1)
        {
            
           

            printf("1.Start\n2.Suspend\n3.Resume\n4.stop\n5.exit\n ");
            printf("Enter Your Choice : ");
            scanf("%d",&ch);

            if(ch != 5)
            {
                    printf("\n Please Insert the Active Domian Name: ");
                    scanf("%s",name);
                    vdp_name = virDomainLookupByName(connection,name);
            }

            switch(ch)
            {
                case 1:
                     
  		               ret_val=virDomainCreate(vdp_name);
                       if(ret_val==0)      
                           printf("Domain %s started\n", name);
                       else
                           printf("Start Operation Failed\n");   
                       break;
                case 2:
                       
		               ret_val=virDomainSuspend(vdp_name);
                       if(ret_val==0)
                           printf("Domain %s Suspended\n", name);
                       else
                           printf("Suspend Operation Failed\n");   
                       break;
                case 3:
                        
		                ret_val=virDomainResume(vdp_name);
                        if(ret_val==0)                     
                            printf("Domain %s Resumed\n", name);
                        else
                            printf("Resume Operation Failed\n");   
                        break;

                case 4: 
                       
		            	ret_val=virDomainShutdown(vdp_name);
                        if(ret_val==0)                     
                            printf("Domain %s Stopped\n", name);
                        else
                            printf("Stop Operation Failed\n");   
                        break;
                case 5: 
                        exit(1);
                default:
                        exit(1);
            }
            
        }
        virConnectClose(connection);
    }
}
void main()
{

    int i,val=-1,ch,no_domains;
    char name[50];
    int *act_domains;
    virConnectPtr con_ptr;
    virDomainPtr dom_ptr;

    con_ptr = virConnectOpen("xen:///");

    if (con_ptr == NULL) {
        fprintf(stderr, "Error opening connection to XEN:///  \n");
        return 1;
    }
    else
    {
        no_domains=virConnectNumOfDomains(con_ptr);
        act_domains=malloc(sizeof(int) * no_domains);
        no_domains = virConnectListDomains(con_ptr, act_domains, no_domains);
        free(act_domains);

        while(1)
        {
            
            printf("1.Start\n2.Suspend\n3.Resume\n4.Shutdown\n5.exit ");
            scanf("%d",&ch);

            printf("\n Enter Active Domian name ");
            scanf("%s",&name);
  
            dom_ptr=virDomainLookupByName(con_ptr,name);
        
            switch(ch)
            {
                case 1:
		       val=virDomainCreate(dom_ptr);
                       if(val==0)      
                           printf("Success");
                       else
                           printf("Failed");   
                       break;
                case 2:
		       val=virDomainSuspend(dom_ptr);
                       if(val==0)
                           printf("Success");
                       else
                           printf("Failed");   
                       break;
                case 3:
		        val=virDomainResume(dom_ptr);
                        if(val==0)                     
                            printf("Success");
                        else
                            printf("Failed");   
                        break;

                case 4:
			val=virDomainShutdown(dom_ptr);
                        if(val==0)                     
                            printf("Success");
                        else
                            printf("Failed");   
                        break;
                default:exit(1);
            }
        }
        virConnectClose(con_ptr);
    }
}
Exemplo n.º 24
0
static int
refresh_lists (void)
{
    int n;

    n = virConnectNumOfDomains (conn);
    if (n < 0) {
        VIRT_ERROR (conn, "reading number of domains");
        return -1;
    }

    if (n > 0) {
        int i;
        int *domids;

        /* Get list of domains. */
        domids = malloc (sizeof (*domids) * n);
        if (domids == NULL) {
            ERROR (PLUGIN_NAME " plugin: malloc failed.");
            return -1;
        }

        n = virConnectListDomains (conn, domids, n);
        if (n < 0) {
            VIRT_ERROR (conn, "reading list of domains");
            sfree (domids);
            return -1;
        }

        free_block_devices ();
        free_interface_devices ();
        free_domains ();

        /* Fetch each domain and add it to the list, unless ignore. */
        for (i = 0; i < n; ++i) {
            virDomainPtr dom = NULL;
            const char *name;
            char *xml = NULL;
            xmlDocPtr xml_doc = NULL;
            xmlXPathContextPtr xpath_ctx = NULL;
            xmlXPathObjectPtr xpath_obj = NULL;
            int j;

            dom = virDomainLookupByID (conn, domids[i]);
            if (dom == NULL) {
                VIRT_ERROR (conn, "virDomainLookupByID");
                /* Could be that the domain went away -- ignore it anyway. */
                continue;
            }

            name = virDomainGetName (dom);
            if (name == NULL) {
                VIRT_ERROR (conn, "virDomainGetName");
                goto cont;
            }

            if (il_domains && ignorelist_match (il_domains, name) != 0)
                goto cont;

            if (add_domain (dom) < 0) {
                ERROR (PLUGIN_NAME " plugin: malloc failed.");
                goto cont;
            }

            /* Get a list of devices for this domain. */
            xml = virDomainGetXMLDesc (dom, 0);
            if (!xml) {
                VIRT_ERROR (conn, "virDomainGetXMLDesc");
                goto cont;
            }

            /* Yuck, XML.  Parse out the devices. */
            xml_doc = xmlReadDoc ((xmlChar *) xml, NULL, NULL, XML_PARSE_NONET);
            if (xml_doc == NULL) {
                VIRT_ERROR (conn, "xmlReadDoc");
                goto cont;
            }

            xpath_ctx = xmlXPathNewContext (xml_doc);

            /* Block devices. */
            xpath_obj = xmlXPathEval
                ((xmlChar *) "/domain/devices/disk/target[@dev]",
                 xpath_ctx);
            if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
                xpath_obj->nodesetval == NULL)
                goto cont;

            for (j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
                xmlNodePtr node;
                char *path = NULL;

                node = xpath_obj->nodesetval->nodeTab[j];
                if (!node) continue;
                path = (char *) xmlGetProp (node, (xmlChar *) "dev");
                if (!path) continue;

                if (il_block_devices &&
                    ignore_device_match (il_block_devices, name, path) != 0)
                    goto cont2;

                add_block_device (dom, path);
            cont2:
                if (path) xmlFree (path);
            }
            xmlXPathFreeObject (xpath_obj);

            /* Network interfaces. */
            xpath_obj = xmlXPathEval
                ((xmlChar *) "/domain/devices/interface[target[@dev]]",
                 xpath_ctx);
            if (xpath_obj == NULL || xpath_obj->type != XPATH_NODESET ||
                xpath_obj->nodesetval == NULL)
                goto cont;

            xmlNodeSetPtr xml_interfaces = xpath_obj->nodesetval;

            for (j = 0; j < xml_interfaces->nodeNr; ++j) {
                char *path = NULL;
                char *address = NULL;
                xmlNodePtr xml_interface;

                xml_interface = xml_interfaces->nodeTab[j];
                if (!xml_interface) continue;
                xmlNodePtr child = NULL;

                for (child = xml_interface->children; child; child = child->next) {
                    if (child->type != XML_ELEMENT_NODE) continue;

                    if (xmlStrEqual(child->name, (const xmlChar *) "target")) {
                        path = (char *) xmlGetProp (child, (const xmlChar *) "dev");
                        if (!path) continue;
                    } else if (xmlStrEqual(child->name, (const xmlChar *) "mac")) {
                        address = (char *) xmlGetProp (child, (const xmlChar *) "address");
                        if (!address) continue;
                    }
                }

                if (il_interface_devices &&
                    (ignore_device_match (il_interface_devices, name, path) != 0 ||
                     ignore_device_match (il_interface_devices, name, address) != 0))
                    goto cont3;

                add_interface_device (dom, path, address, j+1);
                cont3:
                    if (path) xmlFree (path);
                    if (address) xmlFree (address);
            }

        cont:
            if (xpath_obj) xmlXPathFreeObject (xpath_obj);
            if (xpath_ctx) xmlXPathFreeContext (xpath_ctx);
            if (xml_doc) xmlFreeDoc (xml_doc);
            sfree (xml);
        }

        sfree (domids);
    }

    return 0;
}
Exemplo n.º 25
0
int libvirt_open() {
	conn = virConnectOpenReadOnly("xen:///");
	if(conn == NULL) {
	  printf("libvirt connection open error on uri \n"); 
	  return 0;
	}
	int n;
	n = virConnectNumOfDomains(conn);
	if(n < 0) {
		printf("Error reading number of domains \n");
		return -1;
	}

	int i;
	int *domids;

	domids = malloc(sizeof(int) * n);
	if(domids == 0) {
		printf("libvirt domain ids malloc failed");
		return -1;
	}
	n = virConnectListDomains(conn, domids, n);
	if(n < 0) {
		printf("Error reading list of domains \n");
		free(domids);
		return -1;
	}

	free_block_devices();
	free_interface_devices();
	free_domains();

	for (i = 0; i < n ; ++i) {
		virDomainPtr dom = NULL;
		const char *name;
		char *xml = NULL;
		xmlDocPtr xml_doc = NULL;
		xmlXPathContextPtr xpath_ctx = NULL;
		xmlXPathObjectPtr xpath_obj = NULL;
		int j;

		//printf("Publishing Domain Id : %d \n ", domids[i]);
		dom = virDomainLookupByID(conn, domids[i]);
		if(dom == NULL) {
			printf("Domain no longer active or moved away .. \n");
		}
		name = virDomainGetName(dom);
		//printf("Publishing Domain Name : %s \n ", name);
		if(name == NULL) {
			printf("Domain name not valid .. \n");
			goto cont;	
		}
		if(add_domain(dom) < 0) {
			printf("libvirt plugin malloc failed .. \n");
			goto cont;
		}
		xml = virDomainGetXMLDesc(dom, 0);
		if(!xml) {
			printf("Virt domain xml description error ..\n");
			goto cont;
		}
		//printf("Publishing XML : \n %s \n ", xml);

		xml_doc = xmlReadDoc((xmlChar *) xml, NULL, NULL, XML_PARSE_NONET);
		if(xml_doc == NULL) {
			printf("XML read doc error ..\n");
			goto cont;
		}

		xpath_ctx = xmlXPathNewContext(xml_doc);
		xpath_obj = xmlXPathEval((xmlChar *) "/domain/devices/disk/target[@dev]", xpath_ctx);
		if(xpath_obj == NULL || xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
			goto cont;
		}

		for(j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
			xmlNodePtr node;
			char *path = NULL;
			node = xpath_obj->nodesetval->nodeTab[j];
			if(!node) continue;
			path = (char *) xmlGetProp (node, (xmlChar *) "dev");
			if(!path) continue;
			add_block_device(dom, path);
		}
		xmlXPathFreeObject(xpath_obj);

		xpath_obj = xmlXPathEval((xmlChar *) "/domain/devices/interface/target[@dev]", xpath_ctx);
		if(xpath_obj == NULL || xpath_obj->type != XPATH_NODESET || xpath_obj->nodesetval == NULL) {
			goto cont;
		}

		for(j = 0; j < xpath_obj->nodesetval->nodeNr; ++j) {
			xmlNodePtr node;
			char *path = NULL;
			node = xpath_obj->nodesetval->nodeTab[j];
			if(!node) continue;
			path = (char *) xmlGetProp(node, (xmlChar *) "dev");
			if(!path) continue;
			add_interface_device(dom, path);
		}
		cont:
			if(xpath_obj) xmlXPathFreeObject(xpath_obj);
			if(xpath_ctx) xmlXPathFreeContext(xpath_ctx);
			if(xml_doc) xmlFreeDoc(xml_doc);
			if(xml) free(xml);
	}
	free(domids);
	return 0;
}
Exemplo n.º 26
0
//!
//! Main entry point of the application
//!
//! @param[in] argc the number of parameter passed on the command line
//! @param[in] argv the list of arguments
//!
//! @return Always return 0
//!
int main(int argc, char *argv[])
{
    int dom_ids[MAXDOMS] = { 0 };
    int num_doms = 0;
    char *eucahome = NULL;
    char *hypervisor = NULL;
    char rootWrap[EUCA_MAX_PATH] = "";
    char cmd[EUCA_MAX_PATH] = "";
    char hypervisorURL[32] = "";
    virConnectPtr conn = NULL;

    //  logfile (NULL, EUCAFATAL); // suppress all messages

    if (argc != 2) {
        fprintf(stderr, "error: test_nc expects one parameter (name of hypervisor)\n");
        exit(1);
    }

    hypervisor = argv[1];
    if (!strcmp(hypervisor, "kvm") || !strcmp(hypervisor, "qemu")) {
        snprintf(hypervisorURL, 32, "qemu:///system");
    } else if (!strcmp(hypervisor, "xen")) {
        snprintf(hypervisorURL, 32, "xen:///");
    } else if (!strcmp(hypervisor, "not_configured")) {
        fprintf(stderr, "error: HYPERVISOR variable is not set in eucalyptus.conf\n");
        exit(1);
    } else {
        fprintf(stderr, "error: hypervisor type (%s) is not recognized\n", hypervisor);
        exit(1);
    }

    // check that commands that NC needs are there
    if (euca_execlp(NULL, "perl", "--version", NULL) != EUCA_OK) {
        fprintf(stderr, "error: could not run perl\n");
        exit(1);
    }

    if ((eucahome = getenv(EUCALYPTUS_ENV_VAR_NAME)) == NULL) {
        eucahome = strdup("");         // root by default
    } else {
        eucahome = strdup(eucahome);
        // Sanitize this string
        if (euca_sanitize_path(eucahome) != EUCA_OK) {
            EUCA_FREE(eucahome);
            eucahome = strdup("");
        }
    }

    add_euca_to_path(eucahome);

    fprintf(stderr, "looking for system utilities...\n");
    if (diskutil_init(0)) {
        EUCA_FREE(eucahome);
        exit(1);
    }
    // ensure hypervisor information is available
    fprintf(stderr, "ok\n\nchecking the hypervisor...\n");
    snprintf(rootWrap, sizeof(rootWrap), EUCALYPTUS_ROOTWRAP, eucahome);
    if (!strcmp(hypervisor, "kvm") || !strcmp(hypervisor, "qemu")) {
        snprintf(cmd, sizeof(cmd), EUCALYPTUS_HELPER_DIR "/get_sys_info", eucahome);
    } else {
        snprintf(cmd, sizeof(cmd), EUCALYPTUS_HELPER_DIR "/get_xen_info", eucahome);
    }

    if (euca_execlp(NULL, rootWrap, cmd, NULL) != EUCA_OK) {
        fprintf(stderr, "error: could not run '%s %s'\n", rootWrap, cmd);
        EUCA_FREE(eucahome);
        exit(1);
    }
    // check that libvirt can query the hypervisor
    // NULL means local hypervisor
    if ((conn = virConnectOpen(hypervisorURL)) == NULL) {
        print_libvirt_error();
        fprintf(stderr, "error: failed to connect to hypervisor\n");
        EUCA_FREE(eucahome);
        exit(1);
    }

    if ((num_doms = virConnectListDomains(conn, dom_ids, MAXDOMS)) < 0) {
        print_libvirt_error();
        fprintf(stderr, "error: failed to query running domains\n");
        EUCA_FREE(eucahome);
        exit(1);
    }

    fprintf(stdout, "NC test was successful\n");
    EUCA_FREE(eucahome);
    return (0);
}