static int mymain(void) { int id = 0; int ro = 0; virConnectPtr conn; virDomainPtr dom; int status; virCommandPtr cmd; struct utsname ut; /* Skip test if xend is not running. Calling xend on a non-xen kernel causes some versions of xend to issue a crash report, so we first probe uname results. */ uname(&ut); if (strstr(ut.release, "xen") == NULL) return EXIT_AM_SKIP; cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL); if (virCommandRun(cmd, &status) != 0 || status != 0) { virCommandFree(cmd); return EXIT_AM_SKIP; } virCommandFree(cmd); virSetErrorFunc(NULL, errorHandler); conn = virConnectOpen(NULL); if (conn == NULL) { ro = 1; conn = virConnectOpenReadOnly(NULL); } if (conn == NULL) { fprintf(stderr, "First virConnectOpen() failed\n"); return EXIT_FAILURE; } dom = virDomainLookupByID(conn, id); if (dom == NULL) { fprintf(stderr, "First lookup for domain %d failed\n", id); return EXIT_FAILURE; } virDomainFree(dom); virConnectClose(conn); if (ro == 1) conn = virConnectOpenReadOnly(NULL); else conn = virConnectOpen(NULL); if (conn == NULL) { fprintf(stderr, "Second virConnectOpen() failed\n"); return EXIT_FAILURE; } dom = virDomainLookupByID(conn, id); if (dom == NULL) { fprintf(stderr, "Second lookup for domain %d failed\n", id); return EXIT_FAILURE; } virDomainFree(dom); virConnectClose(conn); return EXIT_SUCCESS; }
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); }
static void getDomainInfo(int id) { virConnectPtr conn = NULL; /* the hypervisor connection */ virDomainPtr dom = NULL; /* the domain being checked */ virDomainInfo info; /* the information being fetched */ int ret; /* NULL means connect to local Xen hypervisor */ conn = virConnectOpenReadOnly(NULL); if (conn == NULL) { fprintf(stderr, "Failed to connect to hypervisor\n"); goto error; } /* Find the domain of the given id */ dom = virDomainLookupByID(conn, id); if (dom == NULL) { fprintf(stderr, "Failed to find Domain %d\n", id); goto error; } /* Get the information */ ret = virDomainGetInfo(dom, &info); if (ret < 0) { fprintf(stderr, "Failed to get information for Domain %d\n", id); goto error; } printf("Domains %d: %d CPUs\n", id, info.nrVirtCpu); error: if (dom != NULL) virDomainFree(dom); if (conn != NULL) virConnectClose(conn); }
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; }
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; }
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; }
std::string VM_Controller::get_vm_detail_by_id(int domain_id){ virDomainPtr dom = virDomainLookupByID(_conn, domain_id); if(dom == NULL){ Json::Value j; j["status"] = "no such domain"; return j.toStyledString(); } std::string res = get_vm_detail(dom); virDomainFree(dom); return res; }
/** * SuspendAndResumeDomain: * @id: the id of the domain * * extract the domain 0 information */ static void SuspendAndResumeDomain(int id) { virDomainPtr dom = NULL; /* the domain being checked */ int ret, state; /* Find the domain of the given id */ dom = virDomainLookupByID(conn, id); if (dom == NULL) { fprintf(stderr, "Failed to find Domain %d\n", id); goto error; } /* Check state */ state = checkDomainState(dom); if ((state == VIR_DOMAIN_RUNNING) || (state == VIR_DOMAIN_NOSTATE) || (state == VIR_DOMAIN_BLOCKED)) { printf("Suspending domain...\n"); ret = virDomainSuspend(dom); if (ret < 0) { fprintf(stderr, "Failed to suspend Domain %d\n", id); goto error; } state = checkDomainState(dom); if (state != VIR_DOMAIN_PAUSED) { fprintf(stderr, "Domain %d state is not suspended\n", id); } else { printf("Domain suspended, resuming it...\n"); } ret = virDomainResume(dom); if (ret < 0) { fprintf(stderr, "Failed to resume Domain %d\n", id); goto error; } state = checkDomainState(dom); if ((state == VIR_DOMAIN_RUNNING) || (state == VIR_DOMAIN_NOSTATE) || (state == VIR_DOMAIN_BLOCKED)) { printf("Domain resumed\n"); } else { fprintf(stderr, "Domain %d state indicate it is not resumed\n", id); } } else { fprintf(stderr, "Domain %d is not in a state where it should be suspended\n", id); goto error; } error: if (dom != NULL) virDomainFree(dom); }
static void add_domains_by_id (virConnectPtr conn, int *ids, size_t n) { size_t i; virDomainPtr dom; for (i = 0; i < n; ++i) { if (ids[i] != 0) { /* RHBZ#538041 */ dom = virDomainLookupByID (conn, ids[i]); if (dom) /* transient errors are possible here, ignore them */ add_domain (dom); } } }
std::string VM_Controller::close_vm(int domain_id){ Json::Value j(Json::objectValue); j["status"] = "ok"; virDomainPtr dom = virDomainLookupByID(_conn, domain_id); if(dom == NULL){ j["status"] = "no such domain"; return j.toStyledString(); } if(virDomainDestroy(dom) < 0){ j["status"] = "could not shutdown domain"; return j.toStyledString(); } return j.toStyledString(); }
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(); }
void getDomainInfo(int id, timeInfoNode infos) { virDomainPtr dom = NULL; virDomainInfo info; int ret; struct timeval realTime; int cpu_diff, real_diff; float usage; /* Find the domain of the given id */ dom = virDomainLookupByID(conn, id); if (dom == NULL) { fprintf(stderr, "Failed to find Domain %d\n", id); freeDom(dom); closeConn(); } /* Get the information of the domain */ ret = virDomainGetInfo(dom, &info); if (ret < 0) { fprintf(stderr, "Failed to get information for Domain %d\n", id); freeDom(dom); closeConn(); } /* get the end of realTime*/ if (gettimeofday(&realTime, NULL) == - 1) { fprintf(stderr, "Failed to get start time\n"); return; } /* calculate the usage of cpu */ cpu_diff = (info.cpuTime - infos.cpu_time) / 10000; real_diff = 1000 *(realTime.tv_sec - infos.real_time.tv_sec) + (realTime.tv_usec - infos.real_time.tv_usec); usage = cpu_diff / (float)(real_diff); /* print the results */ printf("%d\t%.3f%\t%lu\t%lu\t%hu\t%0X\t%s\n", id, usage, info.memory / 1024, info.maxMem / 1024, info.nrVirtCpu, info.state, virDomainGetName(dom)); freeDom(dom); }
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); }
static void ShowRunList(virConnectPtr vc) { int i; virDomainPtr dom; const char *name; for (i = 0; i < CF_MAX_CONCURRENT_ENVIRONMENTS; i++) { if (CF_RUNNING[i] > 0) { if ((dom = virDomainLookupByID(vc, CF_RUNNING[i]))) { Log(LOG_LEVEL_VERBOSE, "Found a running virtual domain with id %d", CF_RUNNING[i]); } if ((name = virDomainGetName(dom))) { Log(LOG_LEVEL_VERBOSE, "Found a running virtual domain called '%s'", name); } virDomainFree(dom); } } }
static void ShowRunList(virConnectPtr vc) { int i; virDomainPtr dom; const char *name; for (i = 0; i < CF_MAX_CONCURRENT_ENVIRONMENTS; i++) { if (CF_RUNNING[i] > 0) { if ((dom = virDomainLookupByID(vc, CF_RUNNING[i]))) { CfOut(cf_verbose, "", " -> Found a running virtual domain with id %d\n", CF_RUNNING[i]); } if ((name = virDomainGetName(dom))) { CfOut(cf_verbose, "", " ---> Found a running virtual domain called \"%s\"\n", name); } virDomainFree(dom); } } }
/* get the start time of each domain */ void getTimeInfo(int id, timeInfoNode * infos) { virDomainPtr dom = NULL; virDomainInfo info; int ret; /* Find the domain of the given id */ dom = virDomainLookupByID(conn, id); if (dom == NULL) { fprintf(stderr, "Failed to find Domain %d\n", id); freeDom(dom); closeConn(); } /* Get the information of the domain */ ret = virDomainGetInfo(dom, &info); if (ret < 0) { fprintf(stderr, "Failed to get information for Domain %d\n", id); freeDom(dom); closeConn(); } /* get the start of realTime*/ if (gettimeofday(&(infos->real_time), NULL) == - 1) { fprintf(stderr, "Failed to get start time\n"); return; } /* get the start of CPUTime*/ infos->cpu_time = info.cpuTime; /* nanosecond */ freeDom(dom); }
static PromiseResult CreateVirtDom(EvalContext *ctx, virConnectPtr vc, Attributes a, const Promise *pp) { int alloc_file = false; char *xml_file; const char *name; char defaultxml[CF_MAXVARSIZE]; virDomainPtr dom; int i; snprintf(defaultxml, CF_MAXVARSIZE - 1, "<domain type='test'>" " <name>%s</name>" " <memory>8388608</memory>" " <currentMemory>2097152</currentMemory>" " <vcpu>2</vcpu>" " <os>" " <type>hvm</type>" " </os>" "</domain>", pp->promiser); for (i = 0; i < CF_MAX_CONCURRENT_ENVIRONMENTS; i++) { if (CF_RUNNING[i] > 0) { dom = virDomainLookupByID(vc, CF_RUNNING[i]); name = virDomainGetName(dom); if (name && strcmp(name, pp->promiser) == 0) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Found a running environment called '%s' - promise kept", name); return PROMISE_RESULT_NOOP; } virDomainFree(dom); } } for (i = 0; CF_SUSPENDED[i] != NULL; i++) { if (strcmp(CF_SUSPENDED[i], pp->promiser) == 0) { Log(LOG_LEVEL_INFO, "Found an existing, but suspended, environment id = %s, called '%s'", CF_SUSPENDED[i], CF_SUSPENDED[i]); } } if(a.env.spec) { xml_file = xstrdup(a.env.spec); alloc_file = true; } else { Log(LOG_LEVEL_VERBOSE, "No spec file is promised, so reverting to default settings"); xml_file = defaultxml; } PromiseResult result = PROMISE_RESULT_NOOP; if ((dom = virDomainCreateXML(vc, xml_file, 0))) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Created a virtual domain '%s'", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); if (a.env.cpus != CF_NOINT) { int maxcpus; if ((maxcpus = virConnectGetMaxVcpus(vc, virConnectGetType(vc))) == -1) { Log(LOG_LEVEL_VERBOSE, "Can't determine the available CPU resources"); } else { if (a.env.cpus > maxcpus) { Log(LOG_LEVEL_INFO, "The promise to allocate %d CPUs in domain '%s' cannot be kept - only %d exist on the host", a.env.cpus, pp->promiser, maxcpus); } else if (virDomainSetVcpus(dom, (unsigned int) a.env.cpus) == -1) { Log(LOG_LEVEL_INFO, "Unable to adjust CPU count to %d", a.env.cpus); } else { Log(LOG_LEVEL_INFO, "Verified that environment CPU count is now %d", a.env.cpus); } } } if (a.env.memory != CF_NOINT) { unsigned long maxmem; if ((maxmem = virDomainGetMaxMemory(dom)) == -1) { Log(LOG_LEVEL_VERBOSE, "Can't determine the available CPU resources"); } else { if (virDomainSetMaxMemory(dom, (unsigned long) a.env.memory) == -1) { Log(LOG_LEVEL_INFO, " Unable to set the memory limit to %d", a.env.memory); } else { Log(LOG_LEVEL_INFO, "Setting the memory limit to %d", a.env.memory); } if (virDomainSetMemory(dom, (unsigned long) a.env.memory) == -1) { Log(LOG_LEVEL_INFO, " Unable to set the current memory to %d", a.env.memory); } } } if (a.env.disk != CF_NOINT) { Log(LOG_LEVEL_VERBOSE, "Info: env_disk parameter is not currently supported on this platform"); } virDomainFree(dom); } else { virErrorPtr vp; vp = virGetLastError(); cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Failed to create a virtual domain '%s' - check spec for errors: '%s'", pp->promiser, vp->message); result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); Log(LOG_LEVEL_VERBOSE, "Quoted spec file: %s", xml_file); } if (alloc_file) { free(xml_file); } return result; }
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; }
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; }
//! //! //! //! @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); }
int main(int argvc, char *argv[]){ static virConnectPtr conn = NULL; static virDomainPtr dom = NULL; char * Sysinfo; char* Capabilities; char* Hostname; int Vcpunum ; const char* ConnectType; unsigned long * hvVer; int IsAlive; conn = virConnectOpen("xen:///"); if(conn == NULL){ fprintf(stderr,"Failed to open connection to xen"); return -1; } dom = virDomainLookupByID(conn,1); if(dom == NULL){ fprintf(stderr,"Failed to create a dom"); return -1; } Capabilities = virConnectGetCapabilities(conn);//get capabilities if(Capabilities == NULL){ fprintf(stdout,"failed to GetCapabilities"); return -1; } fprintf(stdout,"ConnectCapabilities %s\n",Capabilities); free(Capabilities); Sysinfo = virConnectGetSysinfo(conn,0);//Get Sysinfo if(Sysinfo ==NULL){ fprintf(stdout,"failed to getinfo"); return -1; } fprintf(stdout,"Sysinfo:%s\n",Sysinfo); free(Sysinfo); Hostname = virConnectGetHostname(conn);//get hostname if(Hostname == NULL){ fprintf(stderr,"failed to get hostname"); return -1; } fprintf(stdout,"Hostname:%s\n",Hostname); free(Hostname); Vcpunum = virConnectGetMaxVcpus(conn,"xen");//Get Vcpunum if(Vcpunum <0){ fprintf(stdout,"failed to GetCpunum"); return -1; } fprintf(stdout,"Vcpunum: %d\n",Vcpunum); ConnectType = virConnectGetType(conn);//Connect Type if(ConnectType ==NULL){ fprintf(stdout,"failed to GetConnectType"); return -1; } fprintf(stdout,"ConnectType is that :%s\n",ConnectType); if(virConnectGetVersion(conn,hvVer)<0){ fprintf(stderr,"Failed to Get Version"); return -1; } fprintf(stdout,"ConnectVersion: %lu\n",*hvVer); IsAlive = virConnectIsAlive(conn); if(IsAlive == 1 ){ fprintf(stdout,"alive\n"); } else if(IsAlive == 0){ fprintf(stdout,"dead\n"); } else fprintf(stdout,"Failed to get Connect Status\n"); free(dom); virConnectClose(conn); return 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++; } } }
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); } }
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; }
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); } }
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; }
static int CreateVirtDom(virConnectPtr vc, char *uri, Attributes a, Promise *pp) { int alloc_file = false; char *xml_file; const char *name; char defaultxml[CF_MAXVARSIZE]; virDomainPtr dom; int i; snprintf(defaultxml, CF_MAXVARSIZE - 1, "<domain type='test'>" " <name>%s</name>" " <memory>8388608</memory>" " <currentMemory>2097152</currentMemory>" " <vcpu>2</vcpu>" " <os>" " <type>hvm</type>" " </os>" "</domain>", pp->promiser); for (i = 0; i < CF_MAX_CONCURRENT_ENVIRONMENTS; i++) { if (CF_RUNNING[i] > 0) { dom = virDomainLookupByID(vc, CF_RUNNING[i]); name = virDomainGetName(dom); if (name && strcmp(name, pp->promiser) == 0) { cfPS(cf_verbose, CF_NOP, "", pp, a, " -> Found a running environment called \"%s\" - promise kept\n", name); return true; } virDomainFree(dom); } } for (i = 0; CF_SUSPENDED[i] != NULL; i++) { if (strcmp(CF_SUSPENDED[i], pp->promiser) == 0) { CfOut(cf_inform, "", " -> Found an existing, but suspended, environment id = %s, called \"%s\"\n", CF_SUSPENDED[i], CF_SUSPENDED[i]); } } if(a.env.spec) { xml_file = xstrdup(a.env.spec); alloc_file = true; } else { CfOut(cf_verbose, "", "No spec file is promised, so reverting to default settings"); xml_file = defaultxml; } if ((dom = virDomainCreateXML(vc, xml_file, 0))) { cfPS(cf_verbose, CF_CHG, "", pp, a, " -> Created a virtual domain \"%s\"\n", pp->promiser); if (a.env.cpus != CF_NOINT) { int maxcpus; if ((maxcpus = virConnectGetMaxVcpus(vc, virConnectGetType(vc))) == -1) { CfOut(cf_verbose, "", " !! Can't determine the available CPU resources"); } else { if (a.env.cpus > maxcpus) { CfOut(cf_inform, "", " !! The promise to allocate %d CPUs in domain \"%s\" cannot be kept - only %d exist on the host", a.env.cpus, pp->promiser, maxcpus); } else if (virDomainSetVcpus(dom, (unsigned int) a.env.cpus) == -1) { CfOut(cf_inform, "", " -> Unable to adjust CPU count to %d", a.env.cpus); } else { CfOut(cf_inform, "", " -> Verified that environment CPU count is now %d", a.env.cpus); } } } if (a.env.memory != CF_NOINT) { unsigned long maxmem; if ((maxmem = virDomainGetMaxMemory(dom)) == -1) { CfOut(cf_verbose, "", " !! Can't determine the available CPU resources"); } else { if (virDomainSetMaxMemory(dom, (unsigned long) a.env.memory) == -1) { CfOut(cf_inform, "", " !!! Unable to set the memory limit to %d", a.env.memory); } else { CfOut(cf_inform, "", " -> Setting the memory limit to %d", a.env.memory); } if (virDomainSetMemory(dom, (unsigned long) a.env.memory) == -1) { CfOut(cf_inform, "", " !!! Unable to set the current memory to %d", a.env.memory); } } } if (a.env.disk != CF_NOINT) { CfOut(cf_verbose, "", " -> Info: env_disk parameter is not currently supported on this platform"); } virDomainFree(dom); } else { virErrorPtr vp; vp = virGetLastError(); cfPS(cf_verbose, CF_FAIL, "", pp, a, " !! Failed to create a virtual domain \"%s\" - check spec for errors: %s", pp->promiser, vp->message); CfOut(cf_verbose, "", "Quoted spec file: %s", xml_file); } if (alloc_file) { free(xml_file); } return true; }