示例#1
0
static int
mymain(void)
{
    struct metadataTest test;
    int ret = EXIT_SUCCESS;

    if (!(test.conn = virConnectOpen("test:///default")))
        return EXIT_FAILURE;

    if (!(test.dom = virDomainLookupByName(test.conn, "test"))) {
        virConnectClose(test.conn);
        return EXIT_FAILURE;
    }

    virtTestQuiesceLibvirtErrors(false);

    if (virtTestRun("Assign metadata ", testAssignMetadata, &test) < 0)
        ret = EXIT_FAILURE;
    if (virtTestRun("Rewrite Metadata ", testRewriteMetadata, &test) < 0)
        ret = EXIT_FAILURE;
    if (virtTestRun("Erase metadata ", testEraseMetadata, &test) < 0)
        ret = EXIT_FAILURE;

    virDomainFree(test.dom);
    virConnectClose(test.conn);

    return ret;
}
示例#2
0
void main(int argc, char *argv[]) {
	char *myIP;
	if (argc<2)
		printf("arg1=myip\n"),exit(-128);
	myIP = argv[1];

	if (fork() == 0) {
		// Child
		virConnectPtr localhost = virConnectOpen("qemu:///system");
		while(1) {
			int alive = virConnectIsAlive(localhost);
			if (alive == 0) {
				printf("Connection lost, reopening.\n");
				virConnectClose(localhost);
				localhost = virConnectOpen("qemu:///system");
			} else if (alive == -1) {
				printf("Connection dead.\n");
				virConnectClose(localhost);
				localhost = virConnectOpen("qemu:///system");
				sleep(3);
				continue;
			}
			printf("*** connected\n");
			run(myIP, localhost);
			sleep(1);
		}
		virConnectClose(localhost);
	}
	exit(0);
}
示例#3
0
static int
mymain(void)
{
    int id = 0;
    int ro = 0;
    virConnectPtr conn;
    virDomainPtr dom;
    int status;
    virCommandPtr cmd;
    struct utsname ut;

    /* Skip test if xend is not running.  Calling xend on a non-xen
       kernel causes some versions of xend to issue a crash report, so
       we first probe uname results.  */
    uname(&ut);
    if (strstr(ut.release, "xen") == NULL)
        return EXIT_AM_SKIP;
    cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
    if (virCommandRun(cmd, &status) != 0 || status != 0) {
        virCommandFree(cmd);
        return EXIT_AM_SKIP;
    }
    virCommandFree(cmd);

    virSetErrorFunc(NULL, errorHandler);

    conn = virConnectOpen(NULL);
    if (conn == NULL) {
        ro = 1;
        conn = virConnectOpenReadOnly(NULL);
    }
    if (conn == NULL) {
        fprintf(stderr, "First virConnectOpen() failed\n");
        return EXIT_FAILURE;
    }
    dom = virDomainLookupByID(conn, id);
    if (dom == NULL) {
        fprintf(stderr, "First lookup for domain %d failed\n", id);
        return EXIT_FAILURE;
    }
    virDomainFree(dom);
    virConnectClose(conn);
    if (ro == 1)
        conn = virConnectOpenReadOnly(NULL);
    else
        conn = virConnectOpen(NULL);
    if (conn == NULL) {
        fprintf(stderr, "Second virConnectOpen() failed\n");
        return EXIT_FAILURE;
    }
    dom = virDomainLookupByID(conn, id);
    if (dom == NULL) {
        fprintf(stderr, "Second lookup for domain %d failed\n", id);
        return EXIT_FAILURE;
    }
    virDomainFree(dom);
    virConnectClose(conn);

    return EXIT_SUCCESS;
}
示例#4
0
static int network_op(char * name, int op)
{
	virNetworkPtr net;
	virConnectPtr conn;
	int ret;
	
	conn = virConnectOpen("qemu:///system");
	if (conn == NULL) 
	{
		fprintf(stderr, "Failed to open connection to qemu:///system\n");
		return -1;
	}
	
	net = virNetworkLookupByName(conn, name);
	if (net == NULL) 
	{
		printf("network is not found\n");
		virConnectClose(conn);
		return -1;
	}

	if (op == NETWORK_DESTROY)
		ret = virNetworkDestroy(net);
	else if (op == NETWORK_SET_AUTOSTART)
		ret = virNetworkSetAutostart(net, 1);
	else if (op == NETWORK_UNSET_AUTOSTART)
		ret = virNetworkSetAutostart(net, 0);
	else
		ret = -1;
		
	virNetworkFree(net);
	virConnectClose(conn);
	
	return ret;
}
示例#5
0
static void
cpg_virt_init_libvirt(struct cpg_info *info) {
	config_object_t *config = info->config;
	int i = 0;

	if (info->vp) {
		dbg_printf(2, "Lost libvirtd connection. Reinitializing.\n");
		for (i = 0 ; i < info->vp_count ; i++)
			virConnectClose(info->vp[i]);
		free(info->vp);
		info->vp = NULL;
	}
	info->vp_count = 0;

	do {
		virConnectPtr vp;
		virConnectPtr *vpl = NULL;
		char conf_attr[256];
		char value[1024];
		char *uri;

		if (i != 0) {
			snprintf(conf_attr, sizeof(conf_attr),
				"backends/cpg/@uri%d", i);
		} else
			snprintf(conf_attr, sizeof(conf_attr), "backends/cpg/@uri");
		++i;

		if (sc_get(config, conf_attr, value, sizeof(value)) != 0)
			break;

		uri = value;
		vp = virConnectOpen(uri);
		if (!vp) {
			dbg_printf(1, "[cpg-virt:INIT] Failed to connect to URI: %s\n", uri);
			continue;
		}

		vpl = realloc(info->vp, sizeof(*info->vp) * (info->vp_count + 1));
		if (!vpl) {
			dbg_printf(1, "[cpg-virt:INIT] Out of memory allocating URI: %s\n",
				uri);
			virConnectClose(vp);
			continue;
		}

		info->vp = vpl;
		info->vp[info->vp_count++] = vp;

		if (i > 1)
			dbg_printf(1, "[cpg-virt:INIT] Added URI%d %s\n", i - 1, uri);
		else
			dbg_printf(1, "[cpg_virt:INIT] Added URI %s\n", uri);
	} while (1);
}
示例#6
0
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;*/
}
示例#7
0
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;

}
示例#8
0
int libvirt_check(int driver)
{
    virSetErrorFunc(NULL, __customErrorFunc);

    const char * URI;
    if (driver == HYPERVISOR_IS_KVM)
        URI = HYPERVISOR_URI_KVM;
    else if (driver == HYPERVISOR_IS_XEN)
        URI = HYPERVISOR_URI_XEN;
    else {
        logerror(_("unrecognized hypervisor driver(%d).\n"), driver);
        return -1;
    }

    virConnectPtr conn = virConnectOpen(URI);
    if (conn == NULL) {
        logerror(_("Connect to %s error.\n"), URI);
        return -1;
    }

    int numDomains = virConnectNumOfDomains(conn);
    if (numDomains < 0) {
        logerror(_("Connect to %s error.\n"), URI);
        return -1;
    }

    virConnectClose(conn);

    return 0;
}
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);
}
示例#10
0
int main(int argc, char **argv) {
    int id = 0;
    conn = virConnectOpenReadOnly(NULL);
    if (conn == NULL) {
        fprintf(stderr, "Failed to connect to hypervisor\n");
        goto error;
    }

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

error:
    if (conn != NULL)
        virConnectClose(conn);
    return(0);
}
示例#11
0
void spice_graphHlpThread::run()
{
    if ( NULL==ptr_ConnPtr || NULL==*ptr_ConnPtr ) {
        emit ptrIsNull();
        return;
    };
    if ( virConnectRef(*ptr_ConnPtr)<0 ) {
        sendConnErrors();
        return;
    };
    QStringList nets;
    virNetworkPtr *networks = NULL;
    unsigned int flags = VIR_CONNECT_LIST_NETWORKS_ACTIVE |
                         VIR_CONNECT_LIST_NETWORKS_INACTIVE;
    int ret = virConnectListAllNetworks(*ptr_ConnPtr, &networks, flags);
    if ( ret<0 ) {
        sendConnErrors();
    } else {
        // therefore correctly to use for() command, because networks[0] can not exist.
        for (int i = 0; i < ret; i++) {
            nets.append( virNetworkGetName(networks[i]) );
            virNetworkFree(networks[i]);
        };
        if (networks) free(networks);
    };
    //int devs = virNodeNumOfDevices(ptr_ConnPtr, NULL, 0);
    if ( virConnectClose(*ptr_ConnPtr)<0 ) {
        sendConnErrors();
    };
    emit result(nets);
}
void libvirt_disconnect() {
    free(activeDomains);
    virConnectClose(conn);

    // directly exit from here
    exit(0);
}
void ConnAliveThread::closeConnection()
{
    //qDebug()<<"closeConnection0"<<*ptr_ConnPtr<<URI;
    if ( keep_alive ) {
        keep_alive = false;
        return;
    };
    //qDebug()<<"closeConnection1"<<*ptr_ConnPtr<<URI;
    CONN_STATE state;
    if ( *ptr_ConnPtr!=NULL ) {
        //qDebug()<<"closeConnection2"<<*ptr_ConnPtr<<URI;
        unregisterConnEvents();
        //qDebug()<<"closeConnection3"<<*ptr_ConnPtr<<URI;
        int ret = virConnectClose(*ptr_ConnPtr);
        //qDebug()<<"virConnectRef -1"<<"ConnAliveThread"<<URI<<(ret+1>0);
        if ( ret<0 ) {
            state = FAILED;
            sendConnErrors();
        } else {
            emit connMsg( QString("close exit code: %1").arg(ret) );
            state = CLOSED;
            emit connClosed(onView);
        };
        *ptr_ConnPtr = NULL;
    } else {
        emit connMsg( QString("connect is NULL") );
        state = FAILED;
    };
    emit changeConnState(state);
}
示例#14
0
int main(int argc, char *argv[])
{
	virConnectPtr conn;
	int id;
	char *vm_name;

	if (argc < 2){
		printf("Usage\n%s <virtual machine name\n", argv[0]);
		exit(1);
	} else {
		vm_name = argv[1];
	}

	conn = connect_to_hypervisor();
	id = find_a_domain(conn, vm_name);
	virConnectClose(conn);

	if (id > 0){
		printf("Domain %s is running\n", vm_name);
	} else if (id < 0){
		printf("Domain %s is NOT running\n", vm_name);
	} else { 
		// If ID is 0, it means that the virtual machine does not exist
		// on the hypervisor
		printf("Domain %s not found on this hypervisor\n", vm_name);
	}

	return 0;
}
示例#15
0
static int dominfo_from_dom(const char *uri,
                            const char *domain,
                            struct domain **d)
{
        virConnectPtr conn = NULL;
        virDomainPtr dom = NULL;
        int ret = 0;

        conn = virConnectOpen(uri);
        if (conn == NULL) {
                printf("Unable to connect to libvirt\n");
                goto out;
        }

        dom = virDomainLookupByName(conn, domain);
        if (dom == NULL) {
                printf("Unable to find domain `%s'\n", domain);
                goto out;
        }

        ret = get_dominfo(dom, d);

 out:
        virDomainFree(dom);
        virConnectClose(conn);

        return ret;
}
示例#16
0
 //qDebug()<<URIs;
 foreach (QString uri, URIs) {
     virConnect *connPtr =
             virConnectOpenReadOnly(uri.toUtf8().data());
     if ( Q_NULLPTR!=connPtr ) {
         // don't work for VBox
         // int num = virConnectNumOfDefinedDomains(connPtr);
         virDomainPtr *domains;
         int ret = virConnectListAllDomains(
                     connPtr, &domains, 0);
         if ( ret+1 ) {
             for (int i = 0; i < ret; i++) {
                  if ( virDomainFree(domains[i]) <0 )
                      sendConnErrors();
             };
             if (domains) free(domains);
         } else {
             sendConnErrors();
         };
         virConnectClose(connPtr);
         if ( ret ) {
             emit localConnFound(uri);
         };
     } else {
         sendConnErrors();
     };
     //msleep(333);
 };
示例#17
0
/**
 * virNWFilterReload:
 *
 * Function to restart the nwfilter driver, it will recheck the configuration
 * files and update its state
 */
static int
nwfilterDriverReload(void) {
    virConnectPtr conn;

    if (!driverState) {
        return -1;
    }

    conn = virConnectOpen("qemu:///system");

    if (conn) {
        /* shut down all threads -- they will be restarted if necessary */
        virNWFilterLearnThreadsTerminate(true);

        nwfilterDriverLock(driverState);
        virNWFilterCallbackDriversLock();

        virNWFilterLoadAllConfigs(conn,
                                  &driverState->nwfilters,
                                  driverState->configDir);

        virNWFilterCallbackDriversUnlock();
        nwfilterDriverUnlock(driverState);

        virConnectClose(conn);
    }

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

if (conn != NULL)
virConnectClose(conn);
return 0;
}
示例#19
0
int main (int argc, char **argv) {
    /* Local Vars */
    virConnectPtr   conn;
    const char      *hvType;
    unsigned long libVer, libMajor, libMinor, libRelease;
    unsigned long hvVer, hvMajor, hvMinor, hvRelease;

    /* Set signal handling and alarm */
    if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR)
        critical("Setup SIGALRM trap failed!");

    /* Process check arguments */
    if (process_arguments(argc, argv) != OK)
        unknown("Parsing arguments failed!");

    /* Start plugin timeout */
    alarm(mp_timeout);

    // PLUGIN CODE
    conn = virt_connect();

    hvType = virConnectGetType(conn);
    if (hvType == NULL) {
        if (mp_verbose > 0) {
            virt_showError(conn);
        }
        critical("Failed to get hypervisor type.");
    }

    if (virConnectGetVersion(conn, &hvVer) != 0) {
        if (mp_verbose > 0) {
            virt_showError(conn);
        }
        critical("Failed to get hypervisor version.");
    }

    if (virConnectGetLibVersion(conn, &libVer) != 0) {
        if (mp_verbose > 0) {
            virt_showError(conn);
        }
        critical("Failed to get library version.");
    }

    virConnectClose(conn);

    hvMajor = hvVer / 1000000;
    hvVer %= 1000000;
    hvMinor = hvVer / 1000;
    hvRelease = hvVer % 1000;

    libMajor = libVer / 1000000;
    libVer %= 1000000;
    libMinor = libVer / 1000;
    libRelease = libVer % 1000;

    /* Output and return */
    ok("libvirtd: v.%lu.%lu.%lu Hypervisor: %s (v.%lu.%lu.%lu)", 
            libMajor, libMinor, libRelease,
            hvType, hvMajor, hvMinor, hvRelease);
}
CMPIStatus enum_profiles(const CMPIBroker *broker,
                         const CMPIObjectPath *reference,
                         const char **properties,
                         struct inst_list *list)
{
        CMPIStatus s = {CMPI_RC_OK, NULL};
        virConnectPtr conn = NULL;
        int i;

        conn = connect_by_classname(broker, CLASSNAME(reference), &s);
        if (conn == NULL)
                goto out;

        for (i = 0; profiles[i] != NULL; i++) {
                CMPIInstance *inst = NULL;

                s = get_profile(broker,
                                reference, 
                                properties,
                                pfx_from_conn(conn),
                                profiles[i],
                                &inst);

                if (s.rc != CMPI_RC_OK)
                        continue;

                inst_list_add(list, inst);
        }

 out:
        virConnectClose(conn);

        return s;
}
void pci_hostHlpThread::run()
{
    if ( NULL==ptr_ConnPtr || NULL==*ptr_ConnPtr ) {
        emit ptrIsNull();
        return;
    };
    if ( virConnectRef(*ptr_ConnPtr)<0 ) {
        sendConnErrors();
        return;
    };
    QStringList      devices;
    virNodeDevice  **nodeDevices = NULL;
    unsigned int flags =
            VIR_CONNECT_LIST_NODE_DEVICES_CAP_PCI_DEV;
    int ret = virConnectListAllNodeDevices(*ptr_ConnPtr, &nodeDevices, flags);
    if ( ret<0 ) {
        sendConnErrors();
    } else {
        // therefore correctly to use for() command, because networks[0] can not exist.
        for (int i = 0; i < ret; i++) {
            devices.append( QString("%1\n")
                            // flags: extra flags; not used yet,
                            // so callers should always pass 0
                            .arg(virNodeDeviceGetXMLDesc(nodeDevices[i], 0)));
            virNodeDeviceFree(nodeDevices[i]);
        };
        if (nodeDevices) free(nodeDevices);
    };
    //int devs = virNodeNumOfDevices(ptr_ConnPtr, NULL, 0);
    if ( virConnectClose(*ptr_ConnPtr)<0 )
        sendConnErrors();
    emit result(devices);
}
示例#22
0
int libvirt_close(void) {
	free_block_devices();
	free_interface_devices();
	free_domains();
	if(conn != NULL)
		virConnectClose(conn);
	conn = NULL;
}
示例#23
0
int main(int argc, char *argv[])
{
	virConnectPtr conn;
	virDomainPtr dom;
	char *xmlconfig = NULL;

	if(argc != 2)
	{	
		printf("usage: ./define_domain domain.xml\n");
		return -1;
	}	

	if ((xmlconfig = GetXml(argv[1])) == NULL)
	{
		fprintf(stderr, "Failed to get xml\n");
		return -1;
	}
	
	conn = virConnectOpen("qemu:///system");
	if (conn == NULL) 
	{
		fprintf(stderr, "Failed to open connection to qemu:///system\n");
		free(xmlconfig);
		return -1;
	}
	
	
	dom = virDomainDefineXML(conn, xmlconfig);
	if (!dom) 
	{
		printf("Domain is not found\n");
		free(xmlconfig);
		virConnectClose(conn);
		return -1;
	}

	fprintf(stderr, "Guest %s is defined\n", virDomainGetName(dom));

	free(xmlconfig);
	virDomainFree(dom);
	virConnectClose(conn);
	
	return 0;
}
示例#24
0
int main(int argc, char *argv[])
{
	virConnectPtr conn;
	int i;
	int numDomains;
	int *activeDomains;
	char **inactiveDomains;
	
	conn = virConnectOpen("qemu:///system");
	if (conn == NULL) 
	{
		fprintf(stderr, "Failed to open connection to qemu:///system\n");
		return -1;
	}

	numDomains = virConnectNumOfDomains(conn);
	if (numDomains == -1) 
	{
		fprintf(stderr, "Failed to get domian num of qemu\n");
		return -1;
	}
	
	activeDomains = malloc(sizeof(int) * numDomains);
	numDomains = virConnectListDomains(conn, activeDomains, numDomains);
	
	printf("%d Active domain list:\n", numDomains);
	for (i = 0 ; i < numDomains ; i++) 
	{
		printf("ID = %d, Name = %s\n", activeDomains[i], virDomainGetName(virDomainLookupByID(conn, activeDomains[i])));
	}
	free(activeDomains);
	
	printf("----------------------------\n");
	numDomains = virConnectNumOfDefinedDomains(conn);
	
	if (numDomains == -1) 
	{
		fprintf(stderr, "Failed to get defined domian num of qemu\n");
		return -1;
	}
	
	inactiveDomains = malloc(sizeof(char *) * numDomains);
	numDomains = virConnectListDefinedDomains(conn, inactiveDomains, numDomains);
	printf("%d Inactive domain list:\n", numDomains);
	for (i = 0 ; i < numDomains ; i++) 
	{
		/*All inactive domains's id should be 0*/
		printf("ID = %d, Name = %s\n", virDomainGetID(virDomainLookupByName(conn, inactiveDomains[i])), inactiveDomains[i]);
		free(inactiveDomains[i]);
	}
	free(inactiveDomains);
	
	virConnectClose(conn);
	return 0;
}
示例#25
0
int
main(int argc, char *argv[])
{
    int ret = 0;
    virConnectPtr conn;
    char *uri;

    printf("Attempting to connect to hypervisor\n");

    uri = (argc > 0 ? argv[1] : NULL);

    /* virConnectOpenAuth is called here with all default parameters,
     * except, possibly, the URI of the hypervisor. */
    conn = virConnectOpenAuth(uri, virConnectAuthPtrDefault, 0);

    if (!conn) {
        ret = 1;
        printf("No connection to hypervisor\n");
        showError(conn);
        goto out;
    }

    uri = virConnectGetURI(conn);
    if (!uri) {
        ret = 1;
        printf("Failed to get URI for hypervisor connection\n");
        showError(conn);
        goto disconnect;
    }

    printf("Connected to hypervisor at \"%s\"\n", uri);
    free(uri);

    if (0 != showHypervisorInfo(conn)) {
        ret = 1;
        goto disconnect;
    }

    if (0 != showDomains(conn)) {
        ret = 1;
        goto disconnect;
    }

disconnect:
    if (0 != virConnectClose(conn)) {
        printf("Failed to disconnect from hypervisor\n");
        showError(conn);
        ret = 1;
    } else {
        printf("Disconnected from hypervisor\n");
    }

out:
    return ret;
}
示例#26
0
static int
mymain(void)
{
    struct metadataTest test;
    int ret = EXIT_SUCCESS;

    if (!(test.conn = virConnectOpen("test:///default")))
        return EXIT_FAILURE;

    if (!(test.dom = virDomainLookupByName(test.conn, "test"))) {
        virConnectClose(test.conn);
        return EXIT_FAILURE;
    }

    virtTestQuiesceLibvirtErrors(false);

    if (virtTestRun("Assign metadata ", testAssignMetadata, &test) < 0)
        ret = EXIT_FAILURE;
    if (virtTestRun("Rewrite Metadata ", testRewriteMetadata, &test) < 0)
        ret = EXIT_FAILURE;
    if (virtTestRun("Erase metadata ", testEraseMetadata, &test) < 0)
        ret = EXIT_FAILURE;

    TEST_TITLE("1", "qwert");
    TEST_TITLE("2", NULL);
    TEST_TITLE("3", "blah");
    TEST_TITLE_FAIL("4", "qwe\nrt");
    TEST_TITLE("5", "");
    TEST_TITLE_FAIL("6", "qwert\n");
    TEST_TITLE_FAIL("7", "\n");

    TEST_DESCR("1", "qwert\nqwert");
    TEST_DESCR("2", NULL);
    TEST_DESCR("3", "qwert");
    TEST_DESCR("4", "\n");
    TEST_DESCR("5", "");

    virDomainFree(test.dom);
    virConnectClose(test.conn);

    return ret;
}
示例#27
0
文件: virsh.c 项目: libvirt/libvirt
/*
 * virshReconnect:
 *
 * Reconnect after a disconnect from libvirtd
 *
 */
static int
virshReconnect(vshControl *ctl, const char *name, bool readonly, bool force)
{
    bool connected = false;
    virshControlPtr priv = ctl->privData;

    /* If the flag was not specified, then it depends on whether we are
     * reconnecting to the current URI (in which case we want to keep the
     * readonly flag as it was) or to a specified URI in which case it
     * should stay false */
    if (!readonly && !name)
        readonly = priv->readonly;

    if (priv->conn) {
        int ret;
        connected = true;

        virConnectUnregisterCloseCallback(priv->conn, virshCatchDisconnect);
        ret = virConnectClose(priv->conn);
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
    }

    priv->conn = virshConnect(ctl, name ? name : ctl->connname, readonly);

    if (!priv->conn) {
        if (disconnected)
            vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
        else
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
        return -1;
    } else {
        if (name) {
            VIR_FREE(ctl->connname);
            ctl->connname = vshStrdup(ctl, name);
        }

        priv->readonly = readonly;

        if (virConnectRegisterCloseCallback(priv->conn, virshCatchDisconnect,
                                            ctl, NULL) < 0)
            vshError(ctl, "%s", _("Unable to register disconnect callback"));
        if (connected && !force)
            vshError(ctl, "%s", _("Reconnected to the hypervisor"));
    }
    disconnected = 0;
    priv->useGetInfo = false;
    priv->useSnapshotOld = false;
    priv->blockJobNoBytes = false;
    return 0;
}
示例#28
0
void libvirt_close(void)
{
    if (g_conn == NULL)
        return;

    virConnectClose(g_conn);
    __this_lock();
    g_conn = NULL;
    __this_unlock();
    return;
}
int main(int argc, char **argv)
{
	if(argc < 4)
	{
		exit(1); 	//error
	}
	
	user_id=atoi(argv[1]);
	clust_id=atoi(argv[2]);
	node_id=atoi(argv[3]);
	
	clusterCfgRead();
	
	
	//virSetErrorFunc(NULL, customGlobalErrorFunc);
	
	virConnectPtr conn;
	
	if (virInitialize() < 0) {
         fprintf(stderr, "Failed to initialize libvirt");
         return 12;
     }

	//virEventRegisterDefaultImpl();
	
    conn = virConnectOpen("qemu:///system"); //xen+unix:///
    if (!conn) {
        printf("error opening\n");
        return 13;
    }

			
	/* coming here we have to  restore the snapshot of the vm  */
	
	// Build the path to restore the  saved snapshot snap$.img [$=node_id]
	char path[512];
	memset(path,0,512);
	sprintf(path,"%s/%d/%d/snap%d.img",clusterHomeDir,user_id,clust_id,node_id);
	
	if( virDomainRestore(conn,path)!=0)
	{
		exit(21);
	}
	
	
	
	/*----------------------------------------------------------	*/
	if (conn && virConnectClose(conn) < 0){
        printf("error closing\n");
        return 16;
    }
    return 0;
}
示例#30
0
int main(int argc, char *argv[])
{
	virConnectPtr conn;
	virNetworkPtr net;
	
	if(argc != 2)
	{	
		printf("usage: ./start_network domain_network\n");
		return -1;
	}
	conn = virConnectOpen("qemu:///system");
	if (conn == NULL) 
	{
		fprintf(stderr, "Failed to open connection to qemu:///system\n");
		return -1;
	}
	
	net = virNetworkLookupByName(conn, argv[1]);
	if (!net) 
	{
		fprintf(stderr, "Network is not found\n");
		virConnectClose(conn);
		return -1;
	}
	
	if (virNetworkCreate(net) < 0) 
	{
		virNetworkFree(net);
		virConnectClose(conn);
		fprintf(stderr, "Cannot start network\n");
		return -1;
	}
	
	fprintf(stderr, "Network %s has started\n", argv[1]);
	
	virNetworkFree(net);
	virConnectClose(conn);
	
	return 0;
}