static int __domain_op_simple(char * name, int op) { if (g_conn == NULL) return -1; virDomainPtr domain; domain = virDomainLookupByName(g_conn, name); if (domain == NULL) { logerror(_("%s: connect domain by name(%s) error. " "domain may not exist\n"), __func__, name); return -1; } int ret; if (op == __DOMAIN_OP_STOP) ret = virDomainShutdown(domain); else if (op == __DOMAIN_OP_STOP_FORCE) ret = virDomainDestroy(domain); else if (op == __DOMAIN_OP_REBOOT) ret = virDomainReboot(domain, 0); else ret = -1; virDomainFree(domain); return ret; }
bool VirshType::killVMFast(const char* vmname, virConnectPtr libvirt_con) { vmprintf(D_FULLDEBUG, "Inside VirshType::killVMFast\n"); if( !vmname || (vmname[0] == '\0') ) { return false; } priv_state priv = set_root_priv(); virDomainPtr dom = virDomainLookupByName(libvirt_con, vmname); set_priv(priv); if(dom == NULL) { virErrorPtr err = virConnGetLastError(libvirt_con); if (err && err->code != VIR_ERR_NO_DOMAIN) { vmprintf(D_ALWAYS, "Error finding domain %s: %s\n", vmname, (err ? err->message : "No reason found")); return false; } else { return true; } } priv = set_root_priv(); bool ret = (virDomainDestroy(dom) == 0); virDomainFree(dom); set_priv(priv); return ret; }
static int DeleteVirt(virConnectPtr vc, char *uri, Attributes a, Promise *pp) { virDomainPtr dom; int ret = true; dom = virDomainLookupByName(vc, pp->promiser); if (dom) { if (virDomainDestroy(dom) == -1) { cfPS(cf_verbose, CF_FAIL, "", pp, a, " !! Failed to delete virtual domain \"%s\"\n", pp->promiser); ret = false; } else { cfPS(cf_verbose, CF_CHG, "", pp, a, " -> Deleted virtual domain \"%s\"\n", pp->promiser); } virDomainFree(dom); } else { cfPS(cf_verbose, CF_NOP, "", pp, a, " -> No such virtual domain called \"%s\" - promise kept\n", pp->promiser); } return ret; }
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; }
static PromiseResult DeleteVirt(EvalContext *ctx, virConnectPtr vc, Attributes a, const Promise *pp) { virDomainPtr dom; dom = virDomainLookupByName(vc, pp->promiser); PromiseResult result = PROMISE_RESULT_NOOP; if (dom) { if (virDomainDestroy(dom) == -1) { cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Failed to delete virtual domain '%s'", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); } else { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, pp, a, "Deleted virtual domain '%s'", pp->promiser); result = PromiseResultUpdate(result, PROMISE_RESULT_CHANGE); } virDomainFree(dom); } else { cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, pp, a, "No such virtual domain called '%s' - promise kept", pp->promiser); } return result; }
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; }
static int DeleteVirt(EvalContext *ctx, virConnectPtr vc, Attributes a, Promise *pp) { virDomainPtr dom; int ret = true; dom = virDomainLookupByName(vc, pp->promiser); if (dom) { if (virDomainDestroy(dom) == -1) { cfPS(ctx, OUTPUT_LEVEL_VERBOSE, PROMISE_RESULT_FAIL, "", pp, a, " !! Failed to delete virtual domain \"%s\"\n", pp->promiser); ret = false; } else { cfPS(ctx, OUTPUT_LEVEL_VERBOSE, PROMISE_RESULT_CHANGE, "", pp, a, " -> Deleted virtual domain \"%s\"\n", pp->promiser); } virDomainFree(dom); } else { cfPS(ctx, OUTPUT_LEVEL_VERBOSE, PROMISE_RESULT_NOOP, "", pp, a, " -> No such virtual domain called \"%s\" - promise kept\n", pp->promiser); } return ret; }
static int doTerminateInstance( struct nc_state_t *nc, ncMetadata *meta, char *instanceId, int *shutdownState, int *previousState) { ncInstance *instance, *vninstance; virConnectPtr *conn; int err; sem_p (inst_sem); instance = find_instance(&global_instances, instanceId); sem_v (inst_sem); if (instance == NULL) return NOT_FOUND; /* try stopping the KVM domain */ conn = check_hypervisor_conn(); if (conn) { sem_p(hyp_sem); virDomainPtr dom = virDomainLookupByName(*conn, instanceId); sem_v(hyp_sem); if (dom) { /* also protect 'destroy' commands, just in case */ sem_p (hyp_sem); err = virDomainDestroy (dom); sem_v (hyp_sem); if (err==0) { logprintfl (EUCAINFO, "destroyed domain for instance %s\n", instanceId); } sem_p(hyp_sem); virDomainFree(dom); /* necessary? */ sem_v(hyp_sem); } else { if (instance->state != BOOTING) logprintfl (EUCAWARN, "warning: domain %s to be terminated not running on hypervisor\n", instanceId); } } /* change the state and let the monitoring_thread clean up state */ sem_p (inst_sem); if (instance->state==BOOTING) { change_state (instance, CANCELED); } else { change_state (instance, SHUTOFF); } sem_v (inst_sem); *previousState = instance->stateCode; *shutdownState = instance->stateCode; return OK; }
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; }
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(); }
static int testDomainCreateXMLNew(const void *data) { const objecteventTest *test = data; lifecycleEventCounter counter; int eventId = VIR_DOMAIN_EVENT_ID_LIFECYCLE; virDomainPtr dom = NULL; int id; int ret = -1; lifecycleEventCounter_reset(&counter); id = virConnectDomainEventRegisterAny(test->conn, NULL, eventId, VIR_DOMAIN_EVENT_CALLBACK(&domainLifecycleCb), &counter, NULL); if (id < 0) goto cleanup; dom = virDomainCreateXML(test->conn, domainDef, 0); if (dom == NULL || virEventRunDefaultImpl() < 0) goto cleanup; if (counter.startEvents != 1 || counter.unexpectedEvents > 0) goto cleanup; if (virConnectDomainEventDeregisterAny(test->conn, id) != 0) goto cleanup; id = -1; ret = 0; cleanup: if (id >= 0) virConnectDomainEventDeregisterAny(test->conn, id); if (dom) { virDomainDestroy(dom); virDomainFree(dom); } return ret; }
static int testDomainCreateXMLOld(const void *data) { const objecteventTest *test = data; lifecycleEventCounter counter; virDomainPtr dom = NULL; int ret = -1; bool registered = false; lifecycleEventCounter_reset(&counter); if (virConnectDomainEventRegister(test->conn, domainLifecycleCb, &counter, NULL) != 0) goto cleanup; registered = true; dom = virDomainCreateXML(test->conn, domainDef, 0); if (dom == NULL || virEventRunDefaultImpl() < 0) goto cleanup; if (counter.startEvents != 1 || counter.unexpectedEvents > 0) goto cleanup; if (virConnectDomainEventDeregister(test->conn, domainLifecycleCb) != 0) goto cleanup; registered = false; ret = 0; cleanup: if (registered) virConnectDomainEventDeregister(test->conn, domainLifecycleCb); if (dom) { virDomainDestroy(dom); virDomainFree(dom); } return ret; }
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; }
int startDomain(char *xml, char *uri) { int id, tries, res = 0; char *port = NULL; char *xmldesc = NULL; virDomainPtr dp = NULL; if (cp == NULL) { cp = libvirtConnect(uri); if (cp == NULL) { DPRINTF("Connection to %s failed\n", uri); return -EIO; } } DPRINTF("Starting domain\n"); dp = virDomainCreateXML(cp, xml, 0); if (dp == NULL) { DPRINTF("virDomainCreateXML call failed\n"); DPRINTF("XML File data:\n%s\n", xml); return -EINVAL; } DPRINTF("Domain started\n"); tries = 0; xmldesc = virDomainGetXMLDesc(dp, 0); if (xmldesc == NULL) { if (tries > 5) { DPRINTF("Cannot get domain XML description\n"); virDomainFree(dp); return -EIO; } sleep(1); tries++; } port = xml_query(xmldesc, "//domain/devices/graphics/@port"); free(xmldesc); if (port == NULL) { DPRINTF("Port lookup failed, node not accessible\n"); virDomainFree(dp); return -ENOENT; } DPRINTF("Graphics port number: %s\n", port); id = virDomainGetID(dp); DPRINTF("Domain created with ID %d\n", id); #ifdef USE_HACK if (startVNCViewer(NULL, NULL, 1) != VNC_STATUS_UNSUPPORTED) { char path[1024] = { 0 }; char buf[2048] = { 0 }; char cmd[4096] = { 0 }; snprintf(path, sizeof(path), "/proc/%d/exe", getpid()); readlink(path, buf, sizeof(buf)); snprintf(cmd, sizeof(cmd), "%s -v localhost:%s -f -l console 2> /dev/null", buf, port); DPRINTF("About to run '%s'\n", cmd); res = WEXITSTATUS(system(cmd)); } else res = VNC_STATUS_NO_CONNECTION; #else res = startVNCViewer("localhost", port, 1); #endif if (((virDomainIsActive(dp)) && (!domainIsOff)) || (res != VNC_STATUS_SHUTDOWN)) { DPRINTF("Domain is active, destroying...\n"); virDomainDestroy(dp); } DPRINTF("Domain %d done.\n", id); virDomainFree(dp); DPRINTF("Returning with %d\n", lastErrorCode); return lastErrorCode; }
//! //! Defines the thread that does the actual reboot of an instance. //! //! @param[in] arg a transparent pointer to the argument passed to this thread handler //! //! @return Always return NULL //! static void *rebooting_thread(void *arg) { #define REATTACH_RETRIES 3 int i = 0; int err = 0; int error = 0; int rc = 0; int log_level_for_devstring = EUCATRACE; char *xml = NULL; char *remoteDevStr = NULL; char path[MAX_PATH] = ""; char lpath[MAX_PATH] = ""; char resourceName[1][MAX_SENSOR_NAME_LEN] = { {0} }; char resourceAlias[1][MAX_SENSOR_NAME_LEN] = { {0} }; ncVolume *volume = NULL; ncInstance *instance = ((ncInstance *) arg); virDomainPtr dom = NULL; virConnectPtr *conn = NULL; logprintfl(EUCADEBUG, "[%s] spawning rebooting thread\n", instance->instanceId); if ((xml = file2str(instance->libvirtFilePath)) == NULL) { logprintfl(EUCAERROR, "[%s] cannot obtain instance XML file %s\n", instance->instanceId, instance->libvirtFilePath); return NULL; } if ((conn = check_hypervisor_conn()) == NULL) { logprintfl(EUCAERROR, "[%s] cannot restart instance %s, abandoning it\n", instance->instanceId, instance->instanceId); change_state(instance, SHUTOFF); EUCA_FREE(xml); return NULL; } sem_p(hyp_sem); { dom = virDomainLookupByName(*conn, instance->instanceId); } sem_v(hyp_sem); if (dom == NULL) { EUCA_FREE(xml); return NULL; } sem_p(hyp_sem); { // for KVM, must stop and restart the instance logprintfl(EUCADEBUG, "[%s] destroying domain\n", instance->instanceId); error = virDomainDestroy(dom); // @todo change to Shutdown? is this synchronous? virDomainFree(dom); } sem_v(hyp_sem); if (error) { EUCA_FREE(xml); return NULL; } // Add a shift to values of three of the metrics: ones that // drop back to zero after a reboot. The shift, which is based // on the latest value, ensures that values sent upstream do // not go backwards . sensor_shift_metric(instance->instanceId, "CPUUtilization"); sensor_shift_metric(instance->instanceId, "NetworkIn"); sensor_shift_metric(instance->instanceId, "NetworkOut"); // domain is now shut down, create a new one with the same XML sem_p(hyp_sem); { logprintfl(EUCAINFO, "[%s] rebooting\n", instance->instanceId); dom = virDomainCreateLinux(*conn, xml, 0); } sem_v(hyp_sem); EUCA_FREE(xml); euca_strncpy(resourceName[0], instance->instanceId, MAX_SENSOR_NAME_LEN); sensor_refresh_resources(resourceName, resourceAlias, 1); // refresh stats so we set base value accurately // re-attach each volume previously attached for (i = 0; i < EUCA_MAX_VOLUMES; ++i) { volume = &instance->volumes[i]; if (strcmp(volume->stateName, VOL_STATE_ATTACHED) && strcmp(volume->stateName, VOL_STATE_ATTACHING)) continue; // skip the entry unless attached or attaching logprintfl(EUCADEBUG, "[%s] volumes [%d] = '%s'\n", instance->instanceId, i, volume->stateName); // get credentials, decrypt them remoteDevStr = get_iscsi_target(volume->remoteDev); if (!remoteDevStr || !strstr(remoteDevStr, "/dev")) { logprintfl(EUCAERROR, "[%s] failed to get local name of host iscsi device when re-attaching\n", instance->instanceId); rc = 1; } else { // set the path snprintf(path, sizeof(path), EUCALYPTUS_VOLUME_XML_PATH_FORMAT, instance->instancePath, volume->volumeId); // vol-XXX.xml snprintf(lpath, sizeof(lpath), EUCALYPTUS_VOLUME_LIBVIRT_XML_PATH_FORMAT, instance->instancePath, volume->volumeId); // vol-XXX-libvirt.xml // read in libvirt XML, which may have been modified by the hook above if ((xml = file2str(lpath)) == NULL) { logprintfl(EUCAERROR, "[%s][%s] failed to read volume XML from %s\n", instance->instanceId, volume->volumeId, lpath); rc = 1; } } EUCA_FREE(remoteDevStr); if (!rc) { // zhill - wrap with retry in case libvirt is dumb. err = 0; for (i = 1; i < REATTACH_RETRIES; i++) { // protect libvirt calls because we've seen problems during concurrent libvirt invocations sem_p(hyp_sem); { err = virDomainAttachDevice(dom, xml); } sem_v(hyp_sem); if (err) { logprintfl(EUCAERROR, "[%s][%s] failed to reattach volume (attempt %d of %d)\n", instance->instanceId, volume->volumeId, i, REATTACH_RETRIES); logprintfl(EUCADEBUG, "[%s][%s] error from virDomainAttachDevice: %d xml: %s\n", instance->instanceId, volume->volumeId, err, xml); sleep(3); // sleep a bit and retry } else { logprintfl(EUCAINFO, "[%s][%s] volume reattached as '%s'\n", instance->instanceId, volume->volumeId, volume->localDevReal); break; } } log_level_for_devstring = EUCATRACE; if (err) log_level_for_devstring = EUCADEBUG; logprintfl(log_level_for_devstring, "[%s][%s] remote device string: %s\n", instance->instanceId, volume->volumeId, volume->remoteDev); } EUCA_FREE(xml); } if (dom == NULL) { logprintfl(EUCAERROR, "[%s] failed to restart instance\n", instance->instanceId); change_state(instance, SHUTOFF); return NULL; } sem_p(hyp_sem); { virDomainFree(dom); } sem_v(hyp_sem); return NULL; #undef REATTACH_RETRIES }
/* thread that does the actual reboot */ static void * rebooting_thread (void *arg) { virConnectPtr *conn; ncInstance * instance = (ncInstance *)arg; struct stat statbuf; int rc = 0; // RESTARTING, // FAILED_RESTART, // SUCCESS_RESTART logprintfl (EUCADEBUG, "{%u} spawning rebooting thread\n", (unsigned int)pthread_self()); char * xml = file2str (instance->libvirtFilePath); if (xml == NULL) { logprintfl (EUCAERROR, "cannot obtain XML file %s\n", instance->libvirtFilePath); return NULL; } conn = check_hypervisor_conn(); if (! conn) { logprintfl (EUCAERROR, "cannot restart instance %s, abandoning it\n", instance->instanceId); change_state (instance, SHUTOFF); free (xml); return NULL; } sem_p(inst_sem); change_task_state (instance, REBOOTING); copy_instances (); sem_v(inst_sem); sem_p (hyp_sem); virDomainPtr dom = virDomainLookupByName(*conn, instance->instanceId); sem_v (hyp_sem); if (dom == NULL) { free (xml); sem_p(inst_sem); change_task_state (instance, FAILED_REBOOT); sem_v(inst_sem); return NULL; } sem_p (hyp_sem); // for KVM, must stop and restart the instance int error = virDomainDestroy (dom); // TODO: change to Shutdown? TODO: is this synchronous? virDomainFree(dom); sem_v (hyp_sem); if (error) { free (xml); sem_p(inst_sem); change_task_state (instance, FAILED_REBOOT); sem_v(inst_sem); return NULL; } #if 0 // domain is now shut down, create a new one with the same XML sem_p (hyp_sem); dom = virDomainCreateLinux (*conn, xml, 0); sem_v (hyp_sem); free (xml); char *remoteDevStr=NULL; // re-attach each volume previously attached for (int i=0; i < EUCA_MAX_VOLUMES; ++i) { ncVolume * volume = &instance->volumes[i]; if (strcmp (volume->stateName, VOL_STATE_ATTACHED) && strcmp (volume->stateName, VOL_STATE_ATTACHING)) continue; // skip the entry unless attached or attaching char attach_xml[1024]; int rc; // get credentials, decrypt them remoteDevStr = get_iscsi_target (volume->remoteDev); if (!remoteDevStr || !strstr(remoteDevStr, "/dev")) { logprintfl(EUCAERROR, "Reattach-volume: failed to get local name of host iscsi device\n"); rc = 1; } else { rc = gen_libvirt_attach_xml (volume->volumeId, instance, volume->localDevReal, remoteDevStr, attach_xml, sizeof(attach_xml)); } if (remoteDevStr) free (remoteDevStr); if (!rc) { int err; sem_p (hyp_sem); err = virDomainAttachDevice (dom, attach_xml); sem_v (hyp_sem); if (err) { logprintfl (EUCAERROR, "virDomainAttachDevice() failed (err=%d) XML=%s\n", err, attach_xml); } else { logprintfl (EUCAINFO, "reattached '%s' to '%s' in domain %s\n", volume->remoteDev, volume->localDevReal, instance->instanceId); } } } #endif int ret=restore_and_volume_instance(instance->instanceId); //20130122-th if (ret==1) { logprintfl (EUCAERROR, "Failed to REBOOT instance %s\n", instance->instanceId); change_state (instance, SHUTOFF); sem_p(inst_sem); change_task_state (instance, FAILED_REBOOT); sem_v(inst_sem); return NULL; } sem_p(inst_sem); change_task_state (instance, SUCCESS_REBOOT); save_instance_struct (instance); copy_instances(); sem_v (inst_sem); return NULL; }
//! //! //! //! @param[in] arg //! //! @return Always returns NULL //! static void *startup_thread(void *arg) { int fd = 0; int iter = 0; long long tid = (*(long long *)arg); virDomainPtr dom = NULL; char file_name[1024] = { 0 }; char xml[4096] = { 0 }; char *xml_template = "<?xml version='1.0' encoding='UTF-8'?>" "<domain type='kvm'>" " <name>tortura-%04lld</name>" " <description>Eucalyptus instance i-XXX</description>" " <os>" " <type>hvm</type>" " </os>" " <features>" " <acpi/>" " </features>" " <clock offset='localtime'/>" " <on_poweroff>destroy</on_poweroff>" " <on_reboot>restart</on_reboot>" " <on_crash>destroy</on_crash>" " <vcpu>1</vcpu>" " <memory>52428</memory>" " <devices>" " <disk device='disk'>" " <source file='%s'/>" " <target bus='virtio' dev='vda'/>" " </disk>" " </devices>" "</domain>"; snprintf(file_name, sizeof(file_name), "%s/%s-%lld", get_current_dir_name(), DUMMY_DISK_FILE, tid); umask(0000); if ((fd = open(file_name, O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0) { printf("failed to create %s\n", DUMMY_DISK_FILE); perror("libvirt_tortura"); exit(1); } if (lseek(fd, DUMMY_DISK_SIZE_BYTES, SEEK_SET) == ((off_t) - 1)) { printf("failed to seek in %s\n", DUMMY_DISK_FILE); perror("libvirt_tortura"); exit(1); } if (write(fd, "x", 1) != 1) { printf("failed to write to %s\n", DUMMY_DISK_FILE); perror("libvirt_tortura"); exit(1); } close(fd); sync(); check_hypervisor_conn(); for (iter = 0; iter < SITERS; iter++) { printf("startup thread %lld starting iteration %d\n", tid, iter); snprintf(xml, sizeof(xml), xml_template, tid, file_name); pthread_mutex_lock(&check_mutex); { dom = virDomainCreateLinux(conn, xml, 0); } pthread_mutex_unlock(&check_mutex); sleep(3); if (dom == NULL) { printf("ERROR: failed to start domain\n"); continue; } pthread_mutex_lock(&check_mutex); { virDomainDestroy(dom); virDomainFree(dom); dom = NULL; } pthread_mutex_unlock(&check_mutex); } unlink(file_name); return (NULL); }
int main(int argc, char *argv[]) { virConnectPtr conn; virDomainPtr vdp; int i=-1,ch; char *host; conn = virConnectOpen("xen:///"); if (conn == NULL) { fprintf(stderr, "Failed to open connection to xen:///\n"); return 1; } //host = virConnectGetHostname(conn); vdp=virDomainLookupByName(conn,"ubuntu_connection"); printf("\nMenu\n----\n1.Connect\n2.Suspend\n3.Resume\n 4.Shutdown\n"); printf("Enter your choice:\n"); scanf("%d",&ch); switch(ch) { case 1: i=virDomainCreate(vdp); if(i==0) { printf("Success\n"); }else{ printf("Failed\n"); } break; case 2: /* suspend*/ i=virDomainSuspend(vdp); if(i==0) { printf("Success\n"); }else{ printf("Failed\n"); } break; case 3: /*resume*/ i=virDomainResume(vdp); if(i==0) { printf("Success\n"); }else{ printf("Failed\n"); } break; case 4: /*shutdown*/ i=virDomainDestroy(vdp); if(i==0) { printf("Success\n"); }else{ printf("Failed\n"); } break; default: printf("INVALID"); virConnectClose(conn); return 0; } }
static void refresh_instance_info( struct nc_state_t *nc, ncInstance *instance) { int now = instance->state; if (! check_hypervisor_conn ()) return; /* no need to bug for domains without state on Hypervisor */ if (now==TEARDOWN || now==STAGING) return; sem_p(hyp_sem); virDomainPtr dom = virDomainLookupByName (nc_state.conn, instance->instanceId); sem_v(hyp_sem); if (dom == NULL) { /* hypervisor doesn't know about it */ if (now==RUNNING || now==BLOCKED || now==PAUSED || now==SHUTDOWN) { /* Most likely the user has shut it down from the inside */ if (instance->retries) { instance->retries--; logprintfl (EUCAWARN, "warning: hypervisor failed to find domain %s, will retry %d more times\n", instance->instanceId, instance->retries); } else { logprintfl (EUCAWARN, "warning: hypervisor failed to find domain %s, assuming it was shut off\n", instance->instanceId); change_state (instance, SHUTOFF); } } /* else 'now' stays in SHUTFOFF, BOOTING, CANCELED, or CRASHED */ return; } virDomainInfo info; sem_p(hyp_sem); int error = virDomainGetInfo(dom, &info); sem_v(hyp_sem); if (error < 0 || info.state == VIR_DOMAIN_NOSTATE) { logprintfl (EUCAWARN, "warning: failed to get informations for domain %s\n", instance->instanceId); /* what to do? hopefully we'll find out more later */ sem_p(hyp_sem); virDomainFree (dom); sem_v(hyp_sem); return; } int xen = info.state; switch (now) { case BOOTING: case RUNNING: case BLOCKED: case PAUSED: /* change to state, whatever it happens to be */ change_state (instance, xen); break; case SHUTDOWN: case SHUTOFF: case CRASHED: if (xen==RUNNING || xen==BLOCKED || xen==PAUSED) { /* cannot go back! */ logprintfl (EUCAWARN, "warning: detected prodigal domain %s, terminating it\n", instance->instanceId); sem_p (hyp_sem); virDomainDestroy (dom); sem_v (hyp_sem); } else { change_state (instance, xen); } break; default: logprintfl (EUCAERROR, "error: refresh...(): unexpected state (%d) for instance %s\n", now, instance->instanceId); return; } sem_p(hyp_sem); virDomainFree(dom); sem_v(hyp_sem); /* if instance is running, try to find out its IP address */ if (instance->state==RUNNING || instance->state==BLOCKED || instance->state==PAUSED) { char *ip=NULL; int rc; if (!strncmp(instance->ncnet.publicIp, "0.0.0.0", 24)) { if (!strcmp(nc_state.vnetconfig->mode, "SYSTEM") || !strcmp(nc_state.vnetconfig->mode, "STATIC")) { rc = mac2ip(nc_state.vnetconfig, instance->ncnet.privateMac, &ip); if (!rc) { if(ip) { logprintfl (EUCAINFO, "discovered public IP %s for instance %s\n", ip, instance->instanceId); strncpy(instance->ncnet.publicIp, ip, 24); free(ip); } } } } if (!strncmp(instance->ncnet.privateIp, "0.0.0.0", 24)) { rc = mac2ip(nc_state.vnetconfig, instance->ncnet.privateMac, &ip); if (!rc) { if(ip) { logprintfl (EUCAINFO, "discovered private IP %s for instance %s\n", ip, instance->instanceId); strncpy(instance->ncnet.privateIp, ip, 24); free(ip); } } } } }
int main(int argc, char *argv[]) { virConnectPtr conn; virDomainPtr vdp; int val=-1; int choice; char *host; conn = virConnectOpen("xen:///"); if (conn == NULL) { fprintf(stderr, "Failed to open connection to xen:///\n"); return 1; } printf("1.Suspend\n2.Resume\n3.Stop\n4.Start\n4.Exit"); scanf("%d",&choice); while(1) { vdp=virDomainLookupById(conn,1); if(choice==1) { /* suspend*/ val=virDomainSuspend(vdp); if(val==0) { printf("Success"); }else{ printf("Failed"); } } else if(choice==2) { /*resume*/ val=virDomainResume(vdp); if(val==0) { printf("Success"); }else{ printf("Failed"); } } else if(choice==3) { /*shutdown*/ val=virDomainDestroy(vdp); if(val==0) { printf("Success"); }else{ printf("Failed"); } } else if(choice==4) { /*start*/ val=virDomainCreate(vdp); if(val==0) { printf("Success"); }else{ printf("Failed"); } } else if(choice==5) { virConnectClose(conn); break; } } return 0; }
/** * @brief forceful shutdown of domain * @return true if the domain was shut down without error, otherwise false * * The domain is sent a sigterm signal followed by a sigkill signal after * timeout period without success */ bool Domain::destroy() { // TODO(txwikinger): check if it can be stopped return (virDomainDestroy(m_domain) == 0); }
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, nvdp; virDomainInfo vdi; char *domain_desc; int ret; //uuid_unparse(vm_uuid, uu_string); 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, "[libvirt:REBOOT] Nothing to " "do - domain does not exist\n"); return 1; } if (((virDomainGetInfo(vdp, &vdi) == 0) && (vdi.state == VIR_DOMAIN_SHUTOFF))) { dbg_printf(2, "[libvirt:REBOOT] Nothing to " "do - domain is off\n"); virDomainFree(vdp); return 0; } syslog(LOG_NOTICE, "Rebooting domain %s\n", vm_name); printf("Rebooting domain %s...\n", vm_name); domain_desc = virDomainGetXMLDesc(vdp, 0); if (!domain_desc) { printf("Failed getting domain description from " "libvirt\n"); } dbg_printf(2, "[REBOOT] Calling virDomainDestroy(%p)\n", vdp); ret = virDomainDestroy(vdp); if (ret < 0) { printf("virDomainDestroy() failed: %d/%d\n", ret, errno); free(domain_desc); virDomainFree(vdp); return 1; } ret = wait_domain(vm_name, info->vp, 15); if (ret) { syslog(LOG_NOTICE, "Domain %s still exists; fencing failed\n", vm_name); printf("Domain %s still exists; fencing failed\n", vm_name); if (domain_desc) free(domain_desc); 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, "Calling virDomainCreateLinux()...\n"); nvdp = virDomainCreateLinux(info->vp, 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, "Failed; Trying virDomainCreate()...\n"); if (virDomainCreate(vdp) < 0) { syslog(LOG_NOTICE, "Could not restart %s\n", vm_name); dbg_printf(1, "Failed to recreate guest" " %s!\n", vm_name); } } free(domain_desc); return ret; }
static int testDomainStartStopEvent(const void *data) { const objecteventTest *test = data; lifecycleEventCounter counter; int eventId = VIR_DOMAIN_EVENT_ID_LIFECYCLE; int id; int ret = -1; virDomainPtr dom; virConnectPtr conn2 = NULL; virDomainPtr dom2 = NULL; lifecycleEventCounter_reset(&counter); dom = virDomainLookupByName(test->conn, "test"); if (dom == NULL) return -1; id = virConnectDomainEventRegisterAny(test->conn, dom, eventId, VIR_DOMAIN_EVENT_CALLBACK(&domainLifecycleCb), &counter, NULL); /* Test domain is started */ virDomainDestroy(dom); virDomainCreate(dom); if (virEventRunDefaultImpl() < 0) goto cleanup; if (counter.startEvents != 1 || counter.stopEvents != 1 || counter.unexpectedEvents > 0) goto cleanup; /* Repeat the test, but this time, trigger the events via an * alternate connection. */ if (!(conn2 = virConnectOpen("test:///default"))) goto cleanup; if (!(dom2 = virDomainLookupByName(conn2, "test"))) goto cleanup; if (virDomainDestroy(dom2) < 0) goto cleanup; if (virDomainCreate(dom2) < 0) goto cleanup; if (virEventRunDefaultImpl() < 0) goto cleanup; if (counter.startEvents != 2 || counter.stopEvents != 2 || counter.unexpectedEvents > 0) goto cleanup; ret = 0; cleanup: virConnectDomainEventDeregisterAny(test->conn, id); virDomainFree(dom); if (dom2) virDomainFree(dom2); if (conn2) virConnectClose(conn2); return ret; }
static int testDomainCreateXMLMixed(const void *data) { const objecteventTest *test = data; lifecycleEventCounter counter; virDomainPtr dom; int ret = -1; int id1 = -1; int id2 = -1; bool registered = false; lifecycleEventCounter_reset(&counter); /* Fun with mixing old and new API, also with global and * per-domain. Handler should be fired three times, once for each * registration. */ dom = virDomainDefineXML(test->conn, domainDef); if (dom == NULL) goto cleanup; id1 = virConnectDomainEventRegisterAny(test->conn, dom, VIR_DOMAIN_EVENT_ID_LIFECYCLE, VIR_DOMAIN_EVENT_CALLBACK(&domainLifecycleCb), &counter, NULL); if (id1 < 0) goto cleanup; if (virConnectDomainEventRegister(test->conn, domainLifecycleCb, &counter, NULL) != 0) goto cleanup; registered = true; id2 = virConnectDomainEventRegisterAny(test->conn, NULL, VIR_DOMAIN_EVENT_ID_LIFECYCLE, VIR_DOMAIN_EVENT_CALLBACK(&domainLifecycleCb), &counter, NULL); if (id2 < 0) goto cleanup; dom = virDomainCreateXML(test->conn, domainDef, 0); if (dom == NULL || virEventRunDefaultImpl() < 0) goto cleanup; if (counter.startEvents != 3 || counter.unexpectedEvents > 0) goto cleanup; if (virConnectDomainEventDeregister(test->conn, domainLifecycleCb) != 0) goto cleanup; registered = false; if (virConnectDomainEventDeregisterAny(test->conn, id1) != 0) goto cleanup; id1 = -1; if (virConnectDomainEventDeregisterAny(test->conn, id2) != 0) goto cleanup; id2 = -1; ret = 0; cleanup: if (id1 >= 0) virConnectDomainEventDeregisterAny(test->conn, id1); if (id2 >= 0) virConnectDomainEventDeregisterAny(test->conn, id2); if (registered) virConnectDomainEventDeregister(test->conn, domainLifecycleCb); if (dom != NULL) { virDomainUndefine(dom); virDomainDestroy(dom); virDomainFree(dom); } return ret; }