Exemple #1
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 = 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:ON] Domain %s does not exist\n", vm_name);
		return 1;
	}

	if (virDomainGetInfo(vdp, &vdi) == 0 && vdi.state != VIR_DOMAIN_SHUTOFF) {
		dbg_printf(2, "Nothing to do - domain %s is already running\n",
			vm_name);
		virDomainFree(vdp);
		return 0;
	}

	syslog(LOG_NOTICE, "Starting domain %s\n", vm_name);
	dbg_printf(2, "[libvirt:ON] Calling virDomainCreate for %s\n", vm_name);

	ret = virDomainCreate(vdp);
	virDomainFree(vdp);

	if (ret < 0) {
		syslog(LOG_NOTICE, "Failed to start domain %s: %d\n", vm_name, ret);
		dbg_printf(2, "[libvirt:ON] virDomainCreate() failed for %s: %d\n",
			vm_name, ret);
		return 1;
	}

	if (ret) {
		syslog(LOG_NOTICE, "Domain %s did not start\n", vm_name);
		dbg_printf(2, "[libvirt:ON] Domain %s did not start\n", vm_name);
		return 1;
	}

	syslog(LOG_NOTICE, "Domain %s started\n", vm_name);
	dbg_printf(2, "[libvirt:ON] Success for %s\n", vm_name);
	return 0;
}
Exemple #2
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;
}
Exemple #3
0
std::string VM_Controller::open_vm(std::string name){
    Json::Value j(Json::objectValue);
    j["status"] = "ok";
    
    virDomainPtr dom = virDomainLookupByName(_conn, name.c_str());
    if(dom == NULL){
        j["status"] = "no such domain";
        return j.toStyledString();
    }
    if(virDomainCreate(dom) < 0){
        j["status"] = "could not open domain";
        return j.toStyledString();
    }

    int dom_id;
    if( (dom_id = virDomainGetID(dom)) < 0){
        j["status"] = "could not get domain id";
        return j.toStyledString();
    }
    j["vm_id"] = dom_id;
    return j.toStyledString();
}
Exemple #4
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 = 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;
}
Exemple #5
0
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;
}
Exemple #6
0
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 int RunningVirt(virConnectPtr vc, char *uri, Attributes a, Promise *pp)
{
    virDomainPtr dom;
    virDomainInfo info;

    dom = virDomainLookupByName(vc, pp->promiser);

    if (dom)
    {
        if (virDomainGetInfo(dom, &info) == -1)
        {
            cfPS(cf_inform, CF_FAIL, "", pp, a, " !! Unable to probe virtual domain \"%s\"", pp->promiser);
            virDomainFree(dom);
            return false;
        }

        switch (info.state)
        {
        case VIR_DOMAIN_RUNNING:
            cfPS(cf_verbose, CF_NOP, "", pp, a, " -> Virtual domain \"%s\" running - promise kept\n", pp->promiser);
            break;

        case VIR_DOMAIN_BLOCKED:
            cfPS(cf_verbose, CF_NOP, "", pp, a,
                 " -> Virtual domain \"%s\" running but waiting for a resource - promise kept as far as possible\n",
                 pp->promiser);
            break;

        case VIR_DOMAIN_SHUTDOWN:
            cfPS(cf_verbose, CF_INTERPT, "", pp, a, " -> Virtual domain \"%s\" is shutting down\n", pp->promiser);
            CfOut(cf_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(cf_verbose, CF_INTERPT, "", pp, a, " -> Virtual domain \"%s\" failed to resume after suspension\n",
                     pp->promiser);
                virDomainFree(dom);
                return false;
            }

            cfPS(cf_verbose, CF_CHG, "", pp, a, " -> Virtual domain \"%s\" was suspended, resuming\n", pp->promiser);
            break;

        case VIR_DOMAIN_SHUTOFF:

            if (virDomainCreate(dom) == -1)
            {
                cfPS(cf_verbose, CF_INTERPT, "", pp, a, " -> Virtual domain \"%s\" failed to resume after halting\n",
                     pp->promiser);
                virDomainFree(dom);
                return false;
            }

            cfPS(cf_verbose, CF_CHG, "", pp, a, " -> Virtual domain \"%s\" was inactive, booting...\n", pp->promiser);
            break;

        case VIR_DOMAIN_CRASHED:

            if (virDomainReboot(dom, 0) == -1)
            {
                cfPS(cf_verbose, CF_INTERPT, "", pp, a, " -> Virtual domain \"%s\" has crashed and rebooting failed\n",
                     pp->promiser);
                virDomainFree(dom);
                return false;
            }

            cfPS(cf_verbose, CF_CHG, "", pp, a, " -> Virtual domain \"%s\" has crashed, rebooting...\n", pp->promiser);
            break;

        default:
            CfOut(cf_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)
            {
                CfOut(cf_inform, "", " !!! Unable to set the number of cpus to %d", a.env.cpus);
            }
            else
            {
                CfOut(cf_inform, "", " -> 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)
            {
                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
    {
        CfOut(cf_verbose, "", " -> Virtual domain \"%s\" cannot be located, attempting to recreate", pp->promiser);
        CreateVirtDom(vc, uri, a, pp);
    }

    return true;
}
Exemple #8
0
void main()
{
    virConnectPtr connection;
    virDomainPtr vdp_id, vdp_name;
    int i,ret_val=-1;
    int ch,ch_id,domainnum;
    int *domains;
    char name[25];
    const char *active_name;
    connection = virConnectOpen("xen:///");

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

        while(1)
        {
            
           

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

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

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

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

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

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

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

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

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

                case 4:
			val=virDomainShutdown(dom_ptr);
                        if(val==0)                     
                            printf("Success");
                        else
                            printf("Failed");   
                        break;
                default:exit(1);
            }
        }
        virConnectClose(con_ptr);
    }
}
Exemple #10
0
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;
}
Exemple #11
0
/**
 * @brief starts the domain
 * @return true if the domain started without error, otherwise false
 */
bool Domain::start()
{
// TODO(txwikinger): check if it can be started
    return (virDomainCreate(m_domain) == 0);
}
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;
}
Exemple #13
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;
}
Exemple #14
0
void run(char *myIP, virConnectPtr localhost) {

	printf("*** New run\n");
	virDomainPtr *domains, *domainsptr;
	virConnectListAllDomains(localhost, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE|VIR_CONNECT_LIST_DOMAINS_INACTIVE|VIR_CONNECT_LIST_DOMAINS_RUNNING|VIR_CONNECT_LIST_DOMAINS_SHUTOFF);
	domainsptr = domains;
	char **domainuuids = malloc(sizeof(char*)*1024);
	char **domainuuidsptr = domainuuids;
	*domainuuids = NULL;
	printf("Domains\n");
	while(*domainsptr != NULL) {
		char buf[VIR_UUID_STRING_BUFLEN];
		virDomainGetUUIDString(*domainsptr, buf);
		const char *name = virDomainGetName(*domainsptr);
		if (!strncmp("ignore",name,strlen("ignore"))) {
			domainsptr++;
			continue;
		}
		printf("%s\n", buf);
		*(domainuuidsptr++) = strdup(buf);
		*domainuuidsptr = NULL;
		domainsptr++;
	}
	domainuuidsptr = domainuuids;
	size_t domainuuids_count=0;
	while(*domainuuidsptr != NULL) domainuuidsptr++, domainuuids_count++;
	domainuuidsptr = domainuuids;
	domainsptr = domains;
	char **hosts = gethosts();
	char **hostsptr=hosts;
	size_t hosts_count = 0;
	while (*hostsptr != NULL) hosts_count++, hostsptr++;
	hostsptr = hosts;
	struct hostwithvmhash **cs = malloc(sizeof(struct hostwithvmhash)*1024);
	*cs = NULL;
	struct hostwithvmhash **csptr = cs;
	int sign=0;
	while(*hostsptr != NULL) {
		if (!strcmp(*hostsptr, myIP)) printf("ME! ");
		sign = !sign;
		size_t k=1;
		while(*domainuuidsptr != NULL) {
/*			char *num = "$6$hest";
			char *hash = crypt(*domainuuidsptr, num);
			char *hash2 = crypt(*hostsptr, num);*/
			struct hostwithvmhash *c=malloc(sizeof(struct hostwithvmhash));
			c->host = *hostsptr;
//			c->host_hash = strdup(hash+10);
			c->vm = *domainuuidsptr;
//			c->vm_hash = strdup(hash2+10);
			c->combined = malloc(10000);
			strcpy(c->combined, "");
			strcat(c->combined, c->host);
			strcat(c->combined, c->vm);
			//c->combined = strdup(crypt(c->combined, num));


			*(csptr++) = c;
			*csptr = NULL;

			domainuuidsptr++;
		}
		domainuuidsptr = domainuuids;
		printf("%s\n", *hostsptr);
	/*	char URL[512];
		sprintf(URL, "qemu+ssh://%s/system", *hosts);
		virConnectPtr dest = virConnectOpen(URL);
		*(destsptr++) = dest;
		*destsptr = NULL;*/
		hostsptr++;
	}
	csptr = cs;
	
	printf("\n");

	size_t count=0;
	while(*csptr != NULL) count++, csptr++;
	csptr = cs;

	qsort(csptr, count, sizeof(struct hostwithvmhash*), (__compar_fn_t)cscompare);

	struct hostwithvmhash **csptrptr = csptr;
	size_t i=0,k=0,j=0,q=1,m=0;
	char *last_host=NULL,*last_vm=NULL;
	struct hostwithvmhash **seen=malloc(sizeof(struct hostwithvmhash*)*1024);
	*seen = NULL;
	struct hostwithvmhash **seenptr=seen;
	struct hostwithvmhash **seenaddptr=seen;
	while(*csptrptr != NULL) {
		if (last_host == NULL || strcmp(last_host, (*csptrptr)->host))
			last_host = (*csptrptr)->host,k++;
		
		seenptr=seen;
		int is_seen=0;
		while(*seenptr != NULL) {
			if (!strcmp((*seenptr)->vm, (*csptrptr)->vm))
				is_seen=1;
			seenptr++;
		}
		if (!is_seen) {
			m++,*(seenaddptr++) = *csptrptr, *seenaddptr = NULL;
			(*csptrptr)->prio = 100*m+(k+m)%hosts_count;
			if (m == domainuuids_count)
				m = 0, seenaddptr=seenptr=seen,*seen=NULL;
		} else
			(*csptrptr)->prio = k;
		csptrptr++;
	}
	qsort(csptr, count, sizeof(struct hostwithvmhash*), (__compar_fn_t)cscompareprio);

	struct hostwithvmhash **cleaned = cleanlist(csptr);
	struct hostwithvmhash **cleanedstart = cleaned;

	while(*cleaned != NULL) {
		virDomainPtr d = virDomainLookupByUUIDString(localhost, (*cleaned)->vm);
		const char *name = virDomainGetName(d);
		int state, reason;
		virDomainGetState(d, &state, &reason, 0);
		if (!strcmp((*cleaned)->host, myIP)) {
			printf("I should be running %s (%s)\n", name, (*cleaned)->vm);
			if (state == VIR_DOMAIN_RUNNING)
				printf("...and it's running.\n");
			else
				virDomainCreate(d);
		} else {
			printf("I should NOT be running %s (%s)\n", name, (*cleaned)->vm);
			if (state == VIR_DOMAIN_RUNNING) {
				printf("Destroying.\n");
				virDomainDestroy(d);
			} else
				printf("...and it's not running.\n");
		}
		if (d) {
			virDomainFree(d);
		}
		//printf("prio:%d host:%s, vm:%s combined:%s\n", (*cleaned)->prio, (*cleaned)->host, (*cleaned)->vm, (*cleaned)->combined);
		cleaned++;
	}
	domainuuidsptr = domainuuids;
	while(*domainuuidsptr != NULL) {
		free(*domainuuidsptr);
		domainuuidsptr++;
	}
	free(domainuuids);
	free(cleanedstart);
	csptr = cs;
	while(*csptr != NULL) {
		free((*csptr)->combined);
		free(*csptr);
		csptr++;
	}
	free(cs);
	free(seen);
	hostsptr = hosts;
	while(*hostsptr != NULL) {
		free(*hostsptr);
		hostsptr++;
	}
	free(hosts);
	domainsptr = domains;
	while(*domainsptr != NULL) {
		virDomainFree(*domainsptr);
		domainsptr++;
	}
	free(domains);
/*
	virDomainPtr *domains;
	virConnectListAllDomains(src, &domains, VIR_CONNECT_LIST_DOMAINS_ACTIVE);
	while(*domains != NULL) {
		char *config = virDomainGetXMLDesc(*domains, 0);
		char uuid[VIR_UUID_BUFLEN];
		char uuidstr[VIR_UUID_STRING_BUFLEN];
		virDomainGetUUIDString(*domains, uuidstr);
		virDomainGetUUID(*domains, uuid);
		destsptr = dests;
		while (*destsptr != NULL) {
			virConnectPtr dest = *destsptr;
			virDomainPtr d = virDomainLookupByUUID(dest, uuid);
			if (d)
				printf("%s already in dest\n", uuidstr);
			if (!d) {
				printf("%s\n", config);
				printf("Injecting domain on dest\n");
				virDomainPtr new = virDomainDefineXML(dest, config);
			}
			fflush(stdout);
			destsptr++;
		}
		domains++;
	}*/
}
Exemple #15
0
void main()
{

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

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

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

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

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

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

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

                case 4: /* stop */
			val=virDomainStop(vdp);
                        if(val==0)                     
                            printf("Success");
                        else
                            printf("Failed");   
                        break;
                default:exit(1);
            }
        }
        virConnectClose(conn);
    }
}
Exemple #16
0
int
main(int argc, char **argv)
{
    virConfPtr conf = NULL;
    const char *login_shell_path = conf_file;
    pid_t cpid = -1;
    int ret = EXIT_CANCELED;
    int status;
    uid_t uid = getuid();
    gid_t gid = getgid();
    char *name = NULL;
    char **shargv = NULL;
    virSecurityModelPtr secmodel = NULL;
    virSecurityLabelPtr seclabel = NULL;
    virDomainPtr dom = NULL;
    virConnectPtr conn = NULL;
    char *homedir = NULL;
    int arg;
    int longindex = -1;
    int ngroups;
    gid_t *groups = NULL;
    ssize_t nfdlist = 0;
    int *fdlist = NULL;
    int openmax;
    size_t i;

    struct option opt[] = {
        {"help", no_argument, NULL, 'h'},
        {"version", optional_argument, NULL, 'V'},
        {NULL, 0, NULL, 0}
    };
    if (virInitialize() < 0) {
        fprintf(stderr, _("Failed to initialize libvirt error handling"));
        return EXIT_CANCELED;
    }

    setenv("PATH", "/bin:/usr/bin", 1);

    virSetErrorFunc(NULL, NULL);
    virSetErrorLogPriorityFunc(NULL);

    progname = argv[0];
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
        /* failure to setup locale is not fatal */
    }
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
        perror("bindtextdomain");
        return ret;
    }
    if (!textdomain(PACKAGE)) {
        perror("textdomain");
        return ret;
    }

    while ((arg = getopt_long(argc, argv, "hV", opt, &longindex)) != -1) {
        switch (arg) {
        case 'h':
            usage();
            exit(EXIT_SUCCESS);

        case 'V':
            show_version();
            exit(EXIT_SUCCESS);

        case '?':
        default:
            usage();
            exit(EXIT_CANCELED);
        }
    }

    if (argc > optind) {
        virReportSystemError(EINVAL, _("%s takes no options"), progname);
        goto cleanup;
    }

    if (uid == 0) {
        virReportSystemError(EPERM, _("%s must be run by non root users"),
                             progname);
        goto cleanup;
    }

    name = virGetUserName(uid);
    if (!name)
        goto cleanup;

    homedir = virGetUserDirectoryByUID(uid);
    if (!homedir)
        goto cleanup;

    if (!(conf = virConfReadFile(login_shell_path, 0)))
        goto cleanup;

    if ((ngroups = virGetGroupList(uid, gid, &groups)) < 0)
        goto cleanup;

    if (virLoginShellAllowedUser(conf, name, groups) < 0)
        goto cleanup;

    if (!(shargv = virLoginShellGetShellArgv(conf)))
        goto cleanup;

    conn = virConnectOpen("lxc:///");
    if (!conn)
        goto cleanup;

    dom = virDomainLookupByName(conn, name);
    if (!dom)
        goto cleanup;

    if (!virDomainIsActive(dom) && virDomainCreate(dom)) {
        virErrorPtr last_error;
        last_error = virGetLastError();
        if (last_error->code != VIR_ERR_OPERATION_INVALID) {
            virReportSystemError(last_error->code,
                                 _("Can't create %s container: %s"),
                                 name, last_error->message);
            goto cleanup;
        }
    }

    openmax = sysconf(_SC_OPEN_MAX);
    if (openmax < 0) {
        virReportSystemError(errno,  "%s",
                             _("sysconf(_SC_OPEN_MAX) failed"));
        goto cleanup;
    }

    if ((nfdlist = virDomainLxcOpenNamespace(dom, &fdlist, 0)) < 0)
        goto cleanup;
    if (VIR_ALLOC(secmodel) < 0)
        goto cleanup;
    if (VIR_ALLOC(seclabel) < 0)
        goto cleanup;
    if (virNodeGetSecurityModel(conn, secmodel) < 0)
        goto cleanup;
    if (virDomainGetSecurityLabel(dom, seclabel) < 0)
        goto cleanup;
    if (virSetUIDGID(0, 0, NULL, 0) < 0)
        goto cleanup;
    if (virDomainLxcEnterSecurityLabel(secmodel, seclabel, NULL, 0) < 0)
        goto cleanup;
    if (nfdlist > 0 &&
        virDomainLxcEnterNamespace(dom, nfdlist, fdlist, NULL, NULL, 0) < 0)
        goto cleanup;
    if (virSetUIDGID(uid, gid, groups, ngroups) < 0)
        goto cleanup;
    if (chdir(homedir) < 0) {
        virReportSystemError(errno, _("Unable to chdir(%s)"), homedir);
        goto cleanup;
    }

    /* A fork is required to create new process in correct pid namespace.  */
    if ((cpid = virFork()) < 0)
        goto cleanup;

    if (cpid == 0) {
        int tmpfd;

        for (i = 3; i < openmax; i++) {
            tmpfd = i;
            VIR_MASS_CLOSE(tmpfd);
        }
        if (execv(shargv[0], (char *const*) shargv) < 0) {
            virReportSystemError(errno, _("Unable to exec shell %s"),
                                 shargv[0]);
            virDispatchError(NULL);
            return errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
        }
    }

    /* At this point, the parent is now waiting for the child to exit,
     * but as that may take a long time, we release resources now.  */
 cleanup:
    if (nfdlist > 0)
        for (i = 0; i < nfdlist; i++)
            VIR_FORCE_CLOSE(fdlist[i]);
    VIR_FREE(fdlist);
    virConfFree(conf);
    if (dom)
        virDomainFree(dom);
    if (conn)
        virConnectClose(conn);
    virStringFreeList(shargv);
    VIR_FREE(name);
    VIR_FREE(homedir);
    VIR_FREE(seclabel);
    VIR_FREE(secmodel);
    VIR_FREE(groups);

    if (virProcessWait(cpid, &status, true) == 0)
        virProcessExitWithStatus(status);

    if (virGetLastError())
        virDispatchError(NULL);
    return ret;
}