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); }
/* --------------- * Misc utils * --------------- */ int virshDomainState(vshControl *ctl, virDomainPtr dom, int *reason) { virDomainInfo info; virshControlPtr priv = ctl->privData; if (reason) *reason = -1; if (!priv->useGetInfo) { int state; if (virDomainGetState(dom, &state, reason, 0) < 0) { virErrorPtr err = virGetLastError(); if (err && err->code == VIR_ERR_NO_SUPPORT) priv->useGetInfo = true; else return -1; } else { return state; } } /* fall back to virDomainGetInfo if virDomainGetState is not supported */ if (virDomainGetInfo(dom, &info) < 0) return -1; else return info.state; }
int libvirt_domain_save(char * name, int idonweb) { virDomainPtr domain; domain = virDomainLookupByName(g_conn, name); if (domain == NULL) { logerror(_("%s: connect domain by name(%s) error.\n"), __func__, name); return -1; } virDomainInfo info; if (virDomainGetInfo(dom, &info) < 0) { logprintfl(SCERROR, "Cannot check guest state\n"); return -3; } if (info.state == VIR_DOMAIN_SHUTOFF) { logprintfl(SCERROR, "Not saving guest that isn't running\n"); return -4; } const char *filename = ""; if (virDomainSave(dom, filename) < 0) { fprintf(stderr, "Unable to save guest to %s\n", filename); } fprintf(stdout, "Guest state saved to %s\n", filename); virConnectClose(conn); return 0; }
static int libvirt_status(const char *vm_name, void *priv) { struct libvirt_info *info = (struct libvirt_info *)priv; virDomainPtr vdp; virDomainInfo vdi; int ret = 0; dbg_printf(5, "%s %s\n", __FUNCTION__, vm_name); VALIDATE(info); if (is_uuid(vm_name)) { vdp = virDomainLookupByUUIDString(info->vp, (const char *)vm_name); } else { vdp = virDomainLookupByName(info->vp, vm_name); } if (!vdp || ((virDomainGetInfo(vdp, &vdi) == 0) && (vdi.state == VIR_DOMAIN_SHUTOFF))) { ret = RESP_OFF; } if (vdp) virDomainFree(vdp); return ret; }
static int libvirt_off(const char *vm_name, const char *src, uint32_t seqno, void *priv) { struct libvirt_info *info = (struct libvirt_info *)priv; virDomainPtr vdp = NULL; virDomainInfo vdi; virDomainPtr (*virt_lookup_fn)(virConnectPtr, const char *); int ret = -1; int i; dbg_printf(5, "ENTER %s %s %u\n", __FUNCTION__, vm_name, seqno); VALIDATE(info); if (is_uuid(vm_name)) virt_lookup_fn = virDomainLookupByUUIDString; else virt_lookup_fn = virDomainLookupByName; for (i = 0 ; i < info->vp_count ; i++) { vdp = virt_lookup_fn(info->vp[i], vm_name); if (vdp) break; } if (!vdp) { dbg_printf(2, "[libvirt:OFF] Domain %s does not exist\n", vm_name); return 1; } if (virDomainGetInfo(vdp, &vdi) == 0 && vdi.state == VIR_DOMAIN_SHUTOFF) { dbg_printf(2, "[libvirt:OFF] Nothing to do - " "domain %s is already off\n", vm_name); virDomainFree(vdp); return 0; } syslog(LOG_NOTICE, "Destroying domain %s\n", vm_name); dbg_printf(2, "[libvirt:OFF] Calling virDomainDestroy for %s\n", vm_name); ret = virDomainDestroy(vdp); virDomainFree(vdp); if (ret < 0) { syslog(LOG_NOTICE, "Failed to destroy domain %s: %d\n", vm_name, ret); dbg_printf(2, "[libvirt:OFF] Failed to destroy domain: %s %d\n", vm_name, ret); return 1; } if (ret) { syslog(LOG_NOTICE, "Domain %s still exists; fencing failed\n", vm_name); dbg_printf(2, "[libvirt:OFF] Domain %s still exists; fencing failed\n", vm_name); return 1; } dbg_printf(2, "[libvirt:OFF] Success for %s\n", vm_name); return 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; }
static inline int wait_domain(const char *vm_name, virConnectPtr vp, int timeout) { int tries = 0; int response = 1; int ret; virDomainPtr vdp; virDomainInfo vdi; int uuid_check; uuid_check = is_uuid(vm_name); if (uuid_check) { vdp = virDomainLookupByUUIDString(vp, (const char *)vm_name); } else { vdp = virDomainLookupByName(vp, vm_name); } if (!vdp) return 0; /* Check domain liveliness. If the domain is still here, we return failure, and the client must then retry */ /* XXX On the xen 3.0.4 API, we will be able to guarantee synchronous virDomainDestroy, so this check will not be necessary */ do { if (++tries > timeout) break; sleep(1); if (uuid_check) { vdp = virDomainLookupByUUIDString(vp, (const char *)vm_name); } else { vdp = virDomainLookupByName(vp, vm_name); } if (!vdp) { dbg_printf(2, "Domain no longer exists\n"); response = 0; break; } memset(&vdi, 0, sizeof(vdi)); ret = virDomainGetInfo(vdp, &vdi); virDomainFree(vdp); if (ret < 0) continue; if (vdi.state == VIR_DOMAIN_SHUTOFF) { dbg_printf(2, "Domain has been shut off\n"); response = 0; break; } dbg_printf(4, "Domain still exists (state %d) after %d seconds\n", vdi.state, tries); } while (1); return response; }
static int suspend_and_resume(virConnectPtr conn, const char *dom_name, unsigned int seconds) { int ret = -1; virDomainPtr dom; virDomainInfo dom_info; if (!(dom = virDomainLookupByName(conn, dom_name))) { ERROR("Unable to find domain '%s'", dom_name); goto cleanup; } if (virDomainGetInfo(dom, &dom_info) < 0) { ERROR("Unable to get domain info"); goto cleanup; } DEBUG("Domain state %d", dom_info.state); switch (dom_info.state) { case VIR_DOMAIN_NOSTATE: case VIR_DOMAIN_RUNNING: case VIR_DOMAIN_BLOCKED: /* In these states the domain can be suspended */ DEBUG("Suspending domain"); if (virDomainSuspend(dom) < 0) { ERROR("Unable to suspend domain"); goto cleanup; } DEBUG("Domain suspended. Entering sleep for %u seconds.", seconds); sleep(seconds); DEBUG("Sleeping done. Resuming the domain."); if (virDomainResume(dom) < 0) { ERROR("Unable to resume domain"); goto cleanup; } break; default: /* In all other states domain can't be suspended */ ERROR("Domain is not in a state where it can be suspended: %d", dom_info.state); goto cleanup; } ret = 0; cleanup: if (dom) virDomainFree(dom); return ret; }
/** * checkDomainState: * @dom: the domain * * Return the current state of a domain or -1 if non-exsitant */ static int checkDomainState(virDomainPtr dom) { virDomainInfo info; /* the information being fetched */ int ret; ret = virDomainGetInfo(dom, &info); if (ret < 0) { return(-1); } return(info.state); }
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; }
static int checkDomainState(virDomainPtr dom) { virDomainInfo info; int ret; ret = virDomainGetInfo(dom, &info); if (ret < 0 ) { return(-1); } return(info.state); }
/* * CPU bandwidth allocation, e.g. 40% CPU, cpu_bw_perc ~ [0 - 100%] * TODO: don't support dynamically change the "period" parameter yet, it only * allocate cpu_quota according to the current period and bw_percentage * TODO: think about the real situation, say we have 8 pCPUs, and the domain * has 2 vCPUs. The the domain take 2 / 8 = 25% of the total physical CPU * resource at most. Does cfs.quota / cfs.period work for only ONE CPU or mean * all CPUs ? If it aims at one CPU, the following function works for each vCPU * of the domain, then it should never exceed its upper bound. */ int alloccpu(virConnectPtr conn, virDomainPtr domain, double cpu_bw_perc) { int ret = -1; unsigned long long cpu_period; long long cpu_quota = -1; virNodeInfo nodeinfo; virDomainInfo dominfo; unsigned int nr_pcpu = 0, nr_vcpu = 0; printf("cpu_bw_perc = %.2lf | ", cpu_bw_perc); if (-1 == virNodeGetInfo(conn, &nodeinfo)) goto cleanup; nr_pcpu = nodeinfo.cpus; printf("nr_pcpu = %u | ", nr_pcpu); if (-1 == virDomainGetInfo(domain, &dominfo)) goto cleanup; nr_vcpu = dominfo.nrVirtCpu; printf("nr_vcpu = %u | ", nr_vcpu); if (-1 == get_vcpu_period(domain, &cpu_period)) goto cleanup; printf("cpu_period = %llu | ", cpu_period); if (cpu_bw_perc <= (double)(nr_vcpu*100/nr_pcpu)) { /* * Compute the new quota which should be allocated to the domain, the * quota is applied to each vcpu, thus the cpu_bw_percentage should be * divided by nr_vcpu. */ cpu_quota = (long long)(cpu_bw_perc / nr_vcpu * nr_pcpu * cpu_period); printf("Choose 1:cpu_quota = %lld\n", cpu_quota); } else { /* * allocate at most (nr_vcpu / nr_pcpu) bandwidth for the domain */ cpu_quota = (long long)(cpu_period); printf("Choose 2:cpu_quota = %lld\n", cpu_quota); } if (-1 == set_vcpu_quota_ll(domain, &cpu_quota)) goto cleanup; ret = 0; cleanup: return ret; }
timearg GetVirtInfo::GetCpuTime(QString VM_name) { virDomainPtr vm_ptr = virDomainLookupByName(conn, qPrintable(VM_name)); if(vm_ptr == NULL) { printf("error finding domain\n"); virConnectClose(conn); exit(1); } virDomainInfo info_s; struct timeval real_time_s; timearg return_arg; if(virDomainGetInfo(vm_ptr, &info_s) != 0) { printf("error get domain info\n"); virDomainFree(vm_ptr); virConnectClose(conn); exit(1); } if(gettimeofday(&real_time_s, NULL) == -1) { printf("error get time of day\n"); virDomainFree(vm_ptr); virConnectClose(conn); exit(1); } return_arg.info = info_s; return_arg.real_time = real_time_s; virDomainFree(vm_ptr); return return_arg; /* sleep(1); if(virDomainGetInfo(vm_ptr, &info_e) !=0) { printf("error get domain info\n"); virDomainFree(vm_ptr); virConnectClose(conn); exit(1); } if(gettimeofday(&real_time_e, NULL) == -1) { printf("error get time of day\n"); virDomainFree(vm_ptr); virConnectClose(conn); exit(1); } cpu_diff = (info_e.cpuTime - info_s.cpuTime) / 1000; real_diff = 1000000 * (real_time_e.tv_sec - real_time_s.tv_sec) +(real_time_e.tv_usec - real_time_s.tv_usec); virDomainFree(vm_ptr); usage = cpu_diff / (float) (real_diff); return usage*100;*/ }
static int isActiveDomain(virDomainPtr dom) { virDomainInfo info; /* the information being fetched */ int ret; ret = virDomainGetInfo(dom, &info); if (ret < 0) return -1; //if (ret==VIR_DOMAIN_RUNNING) if ((ret == VIR_DOMAIN_RUNNING) || (ret == VIR_DOMAIN_NOSTATE) || (ret == VIR_DOMAIN_BLOCKED)) return 1; else return 0; }
static int libvirt_off(const char *vm_name, const char *src, uint32_t seqno, void *priv) { struct libvirt_info *info = (struct libvirt_info *)priv; virDomainPtr vdp; virDomainInfo vdi; int ret = -1; dbg_printf(5, "%s %s\n", __FUNCTION__, vm_name); VALIDATE(info); if (is_uuid(vm_name)) { vdp = virDomainLookupByUUIDString(info->vp, (const char *)vm_name); } else { vdp = virDomainLookupByName(info->vp, vm_name); } if (!vdp) { dbg_printf(2, "Nothing to do - domain does not exist\n"); return 1; } if (((virDomainGetInfo(vdp, &vdi) == 0) && (vdi.state == VIR_DOMAIN_SHUTOFF))) { dbg_printf(2, "Nothing to do - domain is off\n"); virDomainFree(vdp); return 0; } syslog(LOG_NOTICE, "Destroying domain %s\n", vm_name); dbg_printf(2, "[OFF] Calling virDomainDestroy\n"); ret = virDomainDestroy(vdp); if (ret < 0) { syslog(LOG_NOTICE, "Failed to destroy domain: %d\n", ret); printf("virDomainDestroy() failed: %d\n", ret); return 1; } if (ret) { syslog(LOG_NOTICE, "Domain %s still exists; fencing failed\n", vm_name); printf("Domain %s still exists; fencing failed\n", vm_name); return 1; } return 0; }
static int libvirt_on(const char *vm_name, const char *src, uint32_t seqno, void *priv) { struct libvirt_info *info = (struct libvirt_info *)priv; virDomainPtr vdp; virDomainInfo vdi; int ret = -1; dbg_printf(5, "%s %s\n", __FUNCTION__, vm_name); VALIDATE(info); if (is_uuid(vm_name)) { vdp = virDomainLookupByUUIDString(info->vp, (const char *)vm_name); } else { vdp = virDomainLookupByName(info->vp, vm_name); } if (vdp && ((virDomainGetInfo(vdp, &vdi) == 0) && (vdi.state != VIR_DOMAIN_SHUTOFF))) { dbg_printf(2, "Nothing to do - domain is running\n"); if (vdp) virDomainFree(vdp); return 0; } syslog(LOG_NOTICE, "Starting domain %s\n", vm_name); dbg_printf(2, "[ON] Calling virDomainCreate\n"); ret = virDomainCreate(vdp); if (ret < 0) { syslog(LOG_NOTICE, "Failed to start domain: %d\n", ret); printf("virDomainCreate() failed: %d\n", ret); return 1; } if (ret) { syslog(LOG_NOTICE, "Domain %s did not start\n", vm_name); printf("Domain %s did not start\n", vm_name); return 1; } syslog(LOG_NOTICE, "Domain %s started\n", vm_name); return 0; }
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); }
struct domain_info_list *libvirt_domain_info_list() { int i; struct domain_info_list *domain_info_list = (struct domain_info_list *) calloc(1, sizeof(struct domain_info_list)); domain_info_list->num_domains = nr_domains; domain_info_list->domain_info = (struct domain_info *) calloc(nr_domains, sizeof(struct domain_info)); for(i = 0; i < nr_domains; ++i) { if(virDomainGetInfo(domains[i], &vir_domain_info) != 0) continue; domain_info_list->domain_info[i].domain_name = strdup(virDomainGetName(domains[i])); domain_info_list->domain_info[i].domain_id = virDomainGetID(domains[i]); domain_info_list->domain_info[i].domain_state = vir_domain_info.state; domain_info_list->domain_info[i].domain_mem_max = vir_domain_info.maxMem; domain_info_list->domain_info[i].domain_mem_used = vir_domain_info.memory; domain_info_list->domain_info[i].domain_num_vcpus = vir_domain_info.nrVirtCpu; domain_info_list->domain_info[i].domain_cpu_total_time = vir_domain_info.cpuTime; } return domain_info_list; }
std::string VM_Controller::get_vm_detail(virDomainPtr dom){ Json::Value j; j["status"] = "ok"; virDomainInfo info; if(virDomainGetInfo(dom, &info) < 0){ LOG_ERROR("could not get domain info"); j["status"] = "no such domain"; return j.toStyledString(); } // basic info int state; virDomainGetState(dom, &state, NULL, 0); j["vm_status"] = state_code2string(state); if(virDomainIsActive(dom)){ j["id"] = virDomainGetID(dom); } j["name"] = virDomainGetName(dom); j["vcpu"] = virDomainGetMaxVcpus(dom); j["mem_total"] = (unsigned long long)virDomainGetMaxMemory(dom); // more detailed info char *domain_xml = virDomainGetXMLDesc(dom, VIR_DOMAIN_XML_SECURE); tinyxml2::XMLDocument doc; doc.Parse(domain_xml); j["img_path"] = doc.RootElement() ->FirstChildElement("devices") ->FirstChildElement("disk") ->FirstChildElement("source") ->Attribute("file"); tinyxml2::XMLElement *graphics = doc.RootElement() ->FirstChildElement("devices") ->FirstChildElement("graphics"); j["vnc_port"] = graphics->Attribute("port"); virDomainFree(dom); return j.toStyledString(); }
/* * runtime memory allocate for domain */ int allocmem(virDomainPtr domain, double mem_perc) { int ret = -1; struct phy_statistics *pinfo = (struct phy_statistics *)malloc(sizeof(struct phy_statistics) * 1); unsigned long vmemsz; virDomainInfoPtr dominfo; dominfo = (virDomainInfo *)malloc(sizeof(virDomainInfo)); get_phy_memstat(pinfo); vmemsz = (unsigned long)(mem_perc * pinfo->memtotal / 100); printf("mem_perc=%.2lf |memtotal=%lu |vmemsz=%lu ", mem_perc, pinfo->memtotal, vmemsz); if (-1 == virDomainGetInfo(domain, dominfo)) goto cleanup; /* memory size can't be too small, or OOM would kill the VM process */ if (vmemsz < VIR_MEM_LOW_BOUND_IN_BYTES) { vmemsz = VIR_MEM_LOW_BOUND_IN_BYTES; } else if (vmemsz > dominfo->maxMem) { /* memory size < maxMem, for qemu, maxMem can't be changed at runtime */ fprintf(stderr, "allocate %lu memory to domain which is larger" "than the maxMem [%lu]\n", vmemsz, dominfo->maxMem); goto cleanup; } printf("-----finally,we set vmemsz=%lu\n", vmemsz); /* should also set a lower memory bound for the domain */ if (-1 == virDomainSetMemory(domain, vmemsz)) goto cleanup; ret = 0; cleanup: return ret; }
static int libvirt_status(const char *vm_name, void *priv) { struct libvirt_info *info = (struct libvirt_info *)priv; virDomainPtr vdp = NULL; virDomainInfo vdi; int ret = 0; int i; virDomainPtr (*virt_lookup_fn)(virConnectPtr, const char *); dbg_printf(5, "ENTER %s %s\n", __FUNCTION__, vm_name); VALIDATE(info); if (is_uuid(vm_name)) virt_lookup_fn = virDomainLookupByUUIDString; else virt_lookup_fn = virDomainLookupByName; for (i = 0 ; i < info->vp_count ; i++) { vdp = virt_lookup_fn(info->vp[i], vm_name); if (vdp) break; } if (!vdp) { dbg_printf(2, "[libvirt:STATUS] Unknown VM %s - return OFF\n", vm_name); return RESP_OFF; } if (virDomainGetInfo(vdp, &vdi) == 0 && vdi.state == VIR_DOMAIN_SHUTOFF) { dbg_printf(2, "[libvirt:STATUS] VM %s is OFF\n", vm_name); ret = RESP_OFF; } if (vdp) virDomainFree(vdp); return ret; }
/* 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); }
/** * @brief provides the state of the Domain in form of integer * @return integer representing state of domain * * The return value respresents the integer from the enum virDomainState * (http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState) * * If the correct state cannot be ascertained, -1 is returned. */ int Domain::state() { int state; int reason; if (m_domain) { if (m_libVersion > 8000) { if (virDomainGetState(m_domain, &state, &reason, 0) != -1) { return state; } } else { virDomainInfo info; if (virDomainGetInfo(m_domain, &info) != -1) { return info.state; } } } return -1; }
int libvirt_read_stats(void) { int i; printf("Num Domains : %d .. \n", nr_domains); for(i = 0; i < nr_domains; ++i) { //virDomainInfo info; virVcpuInfoPtr vinfo = NULL; int j; if(virDomainGetInfo(domains[i], &vir_domain_info) != 0) continue; vinfo = malloc(vir_domain_info.nrVirtCpu * sizeof vinfo[0]); if(vinfo == NULL){ printf("libvirt plugin malloc failed ..\n"); continue; } if(virDomainGetVcpus(domains[i], vinfo, vir_domain_info.nrVirtCpu, NULL, 0) != 0) { free(vinfo); continue; } for(j = 0; j < vir_domain_info.nrVirtCpu; j++) { printf("VCPU number : %u .. \n", (unsigned int) vinfo[j].number); printf("VCPU time : %llu .. \n", (unsigned long long) vinfo[j].cpuTime); } free(vinfo); } printf("Num Block Devices : %d .. \n", nr_block_devices); for(i = 0; i < nr_block_devices; ++i) { struct _virDomainBlockStats stats; if(virDomainBlockStats(block_devices[i].dom, block_devices[i].path, &stats, sizeof stats) != 0) continue; if((stats.rd_req != -1) && (stats.wr_req != -1)) { printf("Read reqs : %llu \n", (unsigned long long) stats.rd_req); printf("Write reqs : %llu \n", (unsigned long long) stats.wr_req); } if((stats.rd_bytes != -1) && (stats.rd_bytes != -1)) { printf("Read bytes : %llu \n", (unsigned long long) stats.rd_bytes); printf("Write bytes : %llu \n", (unsigned long long) stats.wr_bytes); } } printf("Num Interface Devices : %d .. \n", nr_interface_devices); for(i = 0; i < nr_interface_devices; ++i) { struct _virDomainInterfaceStats stats; if(virDomainInterfaceStats(interface_devices[i].dom, interface_devices[i].path, &stats, sizeof stats) != 0) continue; if((stats.rx_bytes != -1) && (stats.tx_bytes != -1)) { printf("Recieved bytes : %llu \n", (unsigned long long) stats.rx_bytes); printf("Transmitted bytes : %llu \n", (unsigned long long) stats.tx_bytes); } if((stats.rx_packets != -1) && (stats.tx_packets != -1)) { printf("Recieved packets : %llu \n", (unsigned long long) stats.rx_packets); printf("Transmitted packets : %llu \n",(unsigned long long) stats.tx_packets); } if((stats.rx_errs != -1) && (stats.tx_errs != -1)) { printf("Recieved errors : %llu \n", (unsigned long long) stats.rx_errs); printf("Transmitted errors : %llu \n", (unsigned long long) stats.tx_errs); } if((stats.rx_drop != -1) && (stats.tx_drop != -1)) { printf("Recieved dropped : %ll \n", (unsigned long long) stats.rx_drop); printf("Transmitted dropped : %ll \n", (unsigned long long) stats.tx_drop); } } }
static int libvirt_reboot(const char *vm_name, const char *src, uint32_t seqno, void *priv) { struct libvirt_info *info = (struct libvirt_info *)priv; virDomainPtr vdp = NULL, nvdp; virDomainInfo vdi; char *domain_desc; virConnectPtr vcp = NULL; virDomainPtr (*virt_lookup_fn)(virConnectPtr, const char *); int ret; int i; dbg_printf(5, "ENTER %s %s %u\n", __FUNCTION__, vm_name, seqno); VALIDATE(info); if (is_uuid(vm_name)) virt_lookup_fn = virDomainLookupByUUIDString; else virt_lookup_fn = virDomainLookupByName; for (i = 0 ; i < info->vp_count ; i++) { vdp = virt_lookup_fn(info->vp[i], vm_name); if (vdp) { vcp = info->vp[i]; break; } } if (!vdp || !vcp) { dbg_printf(2, "[libvirt:REBOOT] Nothing to do - domain %s does not exist\n", vm_name); return 1; } if (virDomainGetInfo(vdp, &vdi) == 0 && vdi.state == VIR_DOMAIN_SHUTOFF) { dbg_printf(2, "[libvirt:REBOOT] Nothing to do - domain %s is off\n", vm_name); virDomainFree(vdp); return 0; } syslog(LOG_NOTICE, "Rebooting domain %s\n", vm_name); dbg_printf(5, "[libvirt:REBOOT] Rebooting domain %s...\n", vm_name); domain_desc = virDomainGetXMLDesc(vdp, 0); if (!domain_desc) { dbg_printf(5, "[libvirt:REBOOT] Failed getting domain description " "from libvirt for %s...\n", vm_name); } dbg_printf(2, "[libvirt:REBOOT] Calling virDomainDestroy(%p) for %s\n", vdp, vm_name); ret = virDomainDestroy(vdp); if (ret < 0) { dbg_printf(2, "[libvirt:REBOOT] virDomainDestroy() failed for %s: %d/%d\n", vm_name, ret, errno); if (domain_desc) free(domain_desc); virDomainFree(vdp); return 1; } ret = wait_domain(vm_name, vcp, 15); if (ret) { syslog(LOG_NOTICE, "Domain %s still exists; fencing failed\n", vm_name); dbg_printf(2, "[libvirt:REBOOT] Domain %s still exists; fencing failed\n", vm_name); if (domain_desc) free(domain_desc); virDomainFree(vdp); return 1; } if (!domain_desc) return 0; /* 'on' is not a failure */ ret = 0; dbg_printf(3, "[[ XML Domain Info ]]\n"); dbg_printf(3, "%s\n[[ XML END ]]\n", domain_desc); dbg_printf(2, "[libvirt:REBOOT] Calling virDomainCreateLinux() for %s\n", vm_name); nvdp = virDomainCreateLinux(vcp, domain_desc, 0); if (nvdp == NULL) { /* More recent versions of libvirt or perhaps the * KVM back-end do not let you create a domain from * XML if there is already a defined domain description * with the same name that it knows about. You must * then call virDomainCreate() */ dbg_printf(2, "[libvirt:REBOOT] virDomainCreateLinux() failed for %s; " "Trying virDomainCreate()\n", vm_name); if (virDomainCreate(vdp) < 0) { syslog(LOG_NOTICE, "Could not restart %s\n", vm_name); dbg_printf(1, "[libvirt:REBOOT] Failed to recreate guest %s!\n", vm_name); } } free(domain_desc); virDomainFree(vdp); return ret; }
static int lv_read (void) { time_t t; int i; if (conn == NULL) { /* `conn_string == NULL' is acceptable. */ conn = virConnectOpenReadOnly (conn_string); if (conn == NULL) { c_complain (LOG_ERR, &conn_complain, PLUGIN_NAME " plugin: Unable to connect: " "virConnectOpenReadOnly failed."); return -1; } } c_release (LOG_NOTICE, &conn_complain, PLUGIN_NAME " plugin: Connection established."); time (&t); /* Need to refresh domain or device lists? */ if ((last_refresh == (time_t) 0) || ((interval > 0) && ((last_refresh + interval) <= t))) { if (refresh_lists () != 0) { if (conn != NULL) virConnectClose (conn); conn = NULL; return -1; } last_refresh = t; } #if 0 for (i = 0; i < nr_domains; ++i) fprintf (stderr, "domain %s\n", virDomainGetName (domains[i])); for (i = 0; i < nr_block_devices; ++i) fprintf (stderr, "block device %d %s:%s\n", i, virDomainGetName (block_devices[i].dom), block_devices[i].path); for (i = 0; i < nr_interface_devices; ++i) fprintf (stderr, "interface device %d %s:%s\n", i, virDomainGetName (interface_devices[i].dom), interface_devices[i].path); #endif /* Get CPU usage, memory, VCPU usage for each domain. */ for (i = 0; i < nr_domains; ++i) { virDomainInfo info; virVcpuInfoPtr vinfo = NULL; virDomainMemoryStatPtr minfo = NULL; int status; int j; status = virDomainGetInfo (domains[i], &info); if (status != 0) { ERROR (PLUGIN_NAME " plugin: virDomainGetInfo failed with status %i.", status); continue; } if (info.state != VIR_DOMAIN_RUNNING) { /* only gather stats for running domains */ continue; } cpu_submit (info.cpuTime, domains[i], "virt_cpu_total"); memory_submit ((gauge_t) info.memory * 1024, domains[i]); vinfo = malloc (info.nrVirtCpu * sizeof (vinfo[0])); if (vinfo == NULL) { ERROR (PLUGIN_NAME " plugin: malloc failed."); continue; } status = virDomainGetVcpus (domains[i], vinfo, info.nrVirtCpu, /* cpu map = */ NULL, /* cpu map length = */ 0); if (status < 0) { ERROR (PLUGIN_NAME " plugin: virDomainGetVcpus failed with status %i.", status); sfree (vinfo); continue; } for (j = 0; j < info.nrVirtCpu; ++j) vcpu_submit (vinfo[j].cpuTime, domains[i], vinfo[j].number, "virt_vcpu"); sfree (vinfo); minfo = malloc (VIR_DOMAIN_MEMORY_STAT_NR * sizeof (virDomainMemoryStatStruct)); if (minfo == NULL) { ERROR ("virt plugin: malloc failed."); continue; } status = virDomainMemoryStats (domains[i], minfo, VIR_DOMAIN_MEMORY_STAT_NR, 0); if (status < 0) { ERROR ("virt plugin: virDomainMemoryStats failed with status %i.", status); sfree (minfo); continue; } for (j = 0; j < status; j++) { memory_stats_submit ((gauge_t) minfo[j].val * 1024, domains[i], minfo[j].tag); } sfree (minfo); } /* Get block device stats for each domain. */ for (i = 0; i < nr_block_devices; ++i) { struct _virDomainBlockStats stats; if (virDomainBlockStats (block_devices[i].dom, block_devices[i].path, &stats, sizeof stats) != 0) continue; if ((stats.rd_req != -1) && (stats.wr_req != -1)) submit_derive2 ("disk_ops", (derive_t) stats.rd_req, (derive_t) stats.wr_req, block_devices[i].dom, block_devices[i].path); if ((stats.rd_bytes != -1) && (stats.wr_bytes != -1)) submit_derive2 ("disk_octets", (derive_t) stats.rd_bytes, (derive_t) stats.wr_bytes, block_devices[i].dom, block_devices[i].path); } /* for (nr_block_devices) */ /* Get interface stats for each domain. */ for (i = 0; i < nr_interface_devices; ++i) { struct _virDomainInterfaceStats stats; char *display_name = NULL; switch (interface_format) { case if_address: display_name = interface_devices[i].address; break; case if_number: display_name = interface_devices[i].number; break; case if_name: default: display_name = interface_devices[i].path; } if (virDomainInterfaceStats (interface_devices[i].dom, interface_devices[i].path, &stats, sizeof stats) != 0) continue; if ((stats.rx_bytes != -1) && (stats.tx_bytes != -1)) submit_derive2 ("if_octets", (derive_t) stats.rx_bytes, (derive_t) stats.tx_bytes, interface_devices[i].dom, display_name); if ((stats.rx_packets != -1) && (stats.tx_packets != -1)) submit_derive2 ("if_packets", (derive_t) stats.rx_packets, (derive_t) stats.tx_packets, interface_devices[i].dom, display_name); if ((stats.rx_errs != -1) && (stats.tx_errs != -1)) submit_derive2 ("if_errors", (derive_t) stats.rx_errs, (derive_t) stats.tx_errs, interface_devices[i].dom, display_name); if ((stats.rx_drop != -1) && (stats.tx_drop != -1)) submit_derive2 ("if_dropped", (derive_t) stats.rx_drop, (derive_t) stats.tx_drop, interface_devices[i].dom, display_name); } /* for (nr_interface_devices) */ return 0; }
static PromiseResult DownVirt(EvalContext *ctx, virConnectPtr vc, Attributes a, const Promise *pp) { virDomainPtr dom; virDomainInfo info; dom = virDomainLookupByName(vc, pp->promiser); PromiseResult result = PROMISE_RESULT_NOOP; if (dom) { if (virDomainGetInfo(dom, &info) == -1) { cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Unable to probe virtual domain '%s'", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); virDomainFree(dom); return result; } switch (info.state) { case VIR_DOMAIN_BLOCKED: case VIR_DOMAIN_RUNNING: if (virDomainShutdown(dom) == -1) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' failed to shutdown", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); virDomainFree(dom); return result; } cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Virtual domain '%s' running, terminating", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); break; case VIR_DOMAIN_SHUTOFF: case VIR_DOMAIN_SHUTDOWN: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Virtual domain '%s' is down - promise kept", pp->promiser); break; case VIR_DOMAIN_PAUSED: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' is suspended - ignoring promise", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); break; case VIR_DOMAIN_CRASHED: if (virDomainSuspend(dom) == -1) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' is crashed and failed to shutdown", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); virDomainFree(dom); return false; } cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Virtual domain '%s' is in a crashed state, terminating", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); break; default: Log(LOG_LEVEL_VERBOSE, "Virtual domain '%s' is reported as having no state, whatever that means", pp->promiser); break; } virDomainFree(dom); } else { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Virtual domain '%s' cannot be found - take promise as kept", pp->promiser); } return result; }
static PromiseResult SuspendedVirt(EvalContext *ctx, virConnectPtr vc, Attributes a, const Promise *pp) { virDomainPtr dom; virDomainInfo info; dom = virDomainLookupByName(vc, pp->promiser); PromiseResult result = PROMISE_RESULT_NOOP; if (dom) { if (virDomainGetInfo(dom, &info) == -1) { cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Unable to probe virtual domain '%s'", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); virDomainFree(dom); return result; } switch (info.state) { case VIR_DOMAIN_BLOCKED: case VIR_DOMAIN_RUNNING: if (virDomainSuspend(dom) == -1) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' failed to suspend", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); virDomainFree(dom); return result; } cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Virtual domain '%s' running, suspending", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); break; case VIR_DOMAIN_SHUTDOWN: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' is shutting down", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); Log(LOG_LEVEL_VERBOSE, "It is currently impossible to know whether it will reboot or not - deferring promise check until it has completed its shutdown"); break; case VIR_DOMAIN_PAUSED: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Virtual domain '%s' is suspended - promise kept", pp->promiser); break; case VIR_DOMAIN_SHUTOFF: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Virtual domain '%s' is down - promise kept", pp->promiser); break; case VIR_DOMAIN_CRASHED: if (virDomainSuspend(dom) == -1) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' is crashed has failed to suspend", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); virDomainFree(dom); return result; } cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Virtual domain '%s' is in a crashed state, suspending", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); break; default: Log(LOG_LEVEL_VERBOSE, "Virtual domain '%s' is reported as having no state, whatever that means", pp->promiser); break; } virDomainFree(dom); } else { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Virtual domain '%s' cannot be found - take promise as kept", pp->promiser); } return result; }
static PromiseResult RunningVirt(EvalContext *ctx, virConnectPtr vc, Attributes a, const Promise *pp) { virDomainPtr dom; virDomainInfo info; dom = virDomainLookupByName(vc, pp->promiser); PromiseResult result = PROMISE_RESULT_NOOP; if (dom) { if (virDomainGetInfo(dom, &info) == -1) { cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Unable to probe virtual domain '%s'", pp->promiser); virDomainFree(dom); return PROMISE_RESULT_FAIL; } switch (info.state) { case VIR_DOMAIN_RUNNING: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Virtual domain '%s' running - promise kept", pp->promiser); break; case VIR_DOMAIN_BLOCKED: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "Virtual domain '%s' running but waiting for a resource - promise kept as far as possible", pp->promiser); break; case VIR_DOMAIN_SHUTDOWN: cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' is shutting down", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); Log(LOG_LEVEL_VERBOSE, "It is currently impossible to know whether it will reboot or not - deferring promise check until it has completed its shutdown"); break; case VIR_DOMAIN_PAUSED: if (virDomainResume(dom) == -1) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' failed to resume after suspension", pp->promiser); virDomainFree(dom); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); return result; } cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Virtual domain '%s' was suspended, resuming", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); break; case VIR_DOMAIN_SHUTOFF: if (virDomainCreate(dom) == -1) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' failed to resume after halting", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); virDomainFree(dom); return result; } cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Virtual domain '%s' was inactive, booting...", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); break; case VIR_DOMAIN_CRASHED: if (virDomainReboot(dom, 0) == -1) { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_INTERRUPTED, pp, a, "Virtual domain '%s' has crashed and rebooting failed", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); virDomainFree(dom); return result; } cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Virtual domain '%s' has crashed, rebooting...", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); break; default: Log(LOG_LEVEL_VERBOSE, "Virtual domain '%s' is reported as having no state, whatever that means", pp->promiser); break; } if (a.env.cpus > 0) { if (virDomainSetVcpus(dom, a.env.cpus) == -1) { Log(LOG_LEVEL_INFO, " Unable to set the number of cpus to %d", a.env.cpus); } else { Log(LOG_LEVEL_INFO, "Setting the number of virtual cpus to %d", a.env.cpus); } } if (a.env.memory != CF_NOINT) { 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 { Log(LOG_LEVEL_VERBOSE, "Virtual domain '%s' cannot be located, attempting to recreate", pp->promiser); result = PromiseResultUpdate(result, CreateVirtDom(ctx, vc, a, pp)); } return result; }