def migrate(source_addr, domain_id, dest_addr): #Connect to hypervisor uri = "xen+ssh://root@" + str(source_addr) print 'Source URI :', uri conn_s = libvirt.open(uri) if conn_s == None : print 'Failed to open connection to the Source hypervisor' return -1 uri = "xen+ssh://root@" + str(dest_addr) conn_d = libvirt.open(uri) if conn_d== None : print 'Failed to open connection to the Destination hypervisor' return -1 print "Connection to Hypervisors Built Successfully" #Verify if domain is active dom = conn_s.lookupByID(domain_id) if dom == None : print ' No running domain with domain-id ', domain_id return -1 uri = "xenmigr://"+str(dest_addr) result = dom.migrateToURI(uri, 1|16, None, 0) if result == -1 : print "Domain Migration Failed" return -1 return 1
def start_net(self, name): logger.info("Start network " + name) if name in self.networks: conn = libvirt.open(self.urls[self.networks[name].htype]) else: conn = libvirt.open(self.def_connection) try: net = conn.networkLookupByName(name) if not net.isActive(): logger.debug("Network registered in libvirt - start it") net.create() else: logger.debug("Network already active") except libvirt.libvirtError: try: logger.debug("No such network in libvirt") net = self.networks[name] except KeyError: msg = "Can't found network {0!r}".format(name) logger.error(msg) raise CloudError(msg) xml = xmlbuilder.XMLBuilder('network') xml.name(name) xml.bridge(name=net.bridge) with xml.ip(address=net.ip, netmask=net.netmask): xml.dhcp.range(start=net.ip1, end=net.ip2) logger.debug("Create network") conn.networkCreateXML(str(xml))
def ping_libvirt(uri): try: libvirt.open(uri) return [(status_ok, 'libvirt {0} is up and runnning'.format(uri))] except: return [(status_ko, 'libvirt {0} is down'.format(uri))] return
def getConnection(sliver_type): """ returns a connection to the underlying libvirt service a single connection is created and shared among slivers this call ensures the connection is alive and will reconnect if it appears to be necessary """ # sliver_type comes from rec['type'] and is of the form sliver.{LXC,QEMU} # so we need to lower case to lxc/qemu vtype = sliver_type.split('.')[1].lower() uri = vtype + ':///' if uri not in connections: # create connection conn = libvirt.open(uri) connections[uri] = conn return conn else: # connection already available : check for health conn = connections[uri] # see if a reconnection is needed try: numDomains = conn.numOfDomains() except: logger.log("libvirt connection to {} looks broken - reconnecting".format(uri)) conn = libvirt.open(uri) # if this fails then an expection is thrown outside of this function numDomains = conn.numOfDomains() return conn
def connection_allocPages(params): """ test API for allocPages in class virConnect """ logger = params['logger'] fail = 0 if 'flags' in params: if params['flags'] == 'pageset': flags = libvirt.VIR_NODE_ALLOC_PAGES_SET else: logger.error("Unknown flags name: %s" % params['flags']) return 1 else: flags = 0 try: if 'conn' in params: conn = libvirt.open(params['conn']) else: conn = libvirt.open(optional_params['conn']) logger.info("get connection to libvirtd") list1 = get_host_pagesize(conn) except libvirtError as e: logger.error("API error message: %s" % e.message) return 1 for i in list1: logger.info("test hugepage size %d" % i) if get_host_pagecount(i) == -1: logger.info("Skip system page size %d" % i) continue try: cur_count = get_host_pagecount(i) if flags == libvirt.VIR_NODE_ALLOC_PAGES_SET: conn.allocPages({i: cur_count + 1}, 0, 1, flags) else: conn.allocPages({i: 1}, 0, 1, flags) if get_host_pagecount(i) != cur_count + 1: logger.error( "libvirt set a wrong page count to %dKiB hugepage" % i) fail = 1 except libvirtError as e: if "Allocated only" in e.message: tmp_count = int(e.message.split()[-1]) if tmp_count != get_host_pagecount(i): logger.error( "libvirt output %dKiB hugepage count is not right" % i) fail = 1 else: logger.error("API error message: %s" % e.message) return 1 return fail
def list_virtual_machines(): conn=libvirt.open("qemu:///system") domain_dict_1 = [] for id in conn.listDomainsID(): dom = conn.lookupByID(id) info = dom.info() domain_dict_1.append({ 'name' : dom.name(), 'info' : dom.info() }) domain_dict_2 = [] conn=libvirt.open("qemu:///system") for dom in conn.listAllDomains(): info = dom.info() domain_dict_2.append({ 'name' : dom.name(), 'info' : dom.info() }) domain_dict = { 'dict_1' : domain_dict_1, 'dict_2' : domain_dict_2 } return domain_dict
def setGraphicConsolePasswd(self,passwd): """ Ustawia hasło do konsoli VNC @param Hasło @return void """ connection = libvirt.open(self.getUri()) domain = connection.lookupByName(self.getName()) try: domain.destroy() started = 1 except: pass started = 0 xmldesc = domain.XMLDesc(0) domain.undefine() xmltree = minidom.parseString(xmldesc) graphicstag = xmltree.getElementsByTagName("graphics")[0] graphicstag.setAttribute('passwd',passwd) connection.defineXML(xmltree.toxml()) if started == 1: connection = libvirt.open(self.getUri()) domain = connection.lookupByName(self.getName()) domain.create() return 0
def set_user_passwd(params): """ test API for setUserPassword in class virDomain """ logger = params["logger"] guest = params["guestname"] username = params["username"] userpasswd = params["userpassword"] if "flags" in params: if params["flags"] == "encrypted": flags = libvirt.VIR_DOMAIN_PASSWORD_ENCRYPTED else: flags = 0 else: flags = 0 try: if "conn" in params: conn = libvirt.open(params["conn"]) else: conn = libvirt.open(optional_params["conn"]) logger.info("get connection to libvirtd") vm = conn.lookupByName(guest) logger.info("test guest name: %s" % guest) if not check_agent_status(vm): logger.error("guest agent is not connected") return 1 mac = get_guest_mac(vm) if not mac: logger.error("cannot get guest interface mac") return 1 ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.error("cannot get guest IP") return 1 if flags > 0: passwd = crypt.crypt("123456", crypt.mksalt(crypt.METHOD_SHA512)) else: passwd = "123456" if create_new_user(ipaddr, "usertestapi", username, userpasswd, logger) != 0: return 1 vm.setUserPassword("usertestapi", passwd, flags) if verify_cur_user(ipaddr, "usertestapi", "123456") != 0: logger.error("cannot login guest via new user") return 1 except libvirtError, e: logger.error("API error message: %s" % e.message) return 1
def libvirt_connect(self, force_tcp=False): # Allows only one connection for each different host if force_tcp is False and self.__class__.libvirt_connections.has_key(self.id) and isinstance(self.__class__.libvirt_connections[self.id], libvirt.virConnect): #logger.debug("Connections found: " + str(self.__class__.libvirt_connections)) return self.__class__.libvirt_connections[self.id] driver = self.driver path = "" if self.transport == "local": transport = "" path = "/system" hostname = username = port = "" else: if self.transport == 'tls' and force_tcp: transport = "+tcp" else: transport = "+" + self.transport # Hostname, username and port are only required if # connection is NOT local if self.hostname == "": hostname = "" else: hostname = self.hostname if self.port == None: port = "" else: port = ":" + str(self.port) if not self.path.startswith("/"): if self.path == "": path = "" else: path = "/" + str(self.path) if self.extraparameters == "": extraparameters = "" else: extraparameters = "?" + str(self.extraparameters) # Format: driver[+transport]://[username@][hostname][:port]/[path][?extraparameters] host_path = driver + transport + "://" + hostname + port + path + extraparameters try: if force_tcp: return libvirt.open(host_path) # If SASL authentication is needed if self.username and self.password: self.__class__.libvirt_connections[self.id] = self.open_auth(host_path) else: self.__class__.libvirt_connections[self.id] = libvirt.open(host_path) #logger.debug("New connection: " + str(self.__class__.libvirt_connections)) return self.__class__.libvirt_connections[self.id] except libvirtError as e: logger.error('Failed to open connection to the hypervisor: ' + host_path + ' ' + str(e)) raise self.HostException('Failed to open connection to the hypervisor: ' + host_path + ' ' + str(e))
def open(type): if type in ['qemu', 'kvm']: return libvirt.open('qemu:///system') elif type == 'xen': return libvirt.open('xen:///') else: # This assumes you have setup libvirt aliases # http://libvirt.org/uri.html#URI_config return libvirt.open(type)
def test(self): virt_con = self.mox.CreateMock(libvirt.virConnect) self.mox.StubOutWithMock(libvirt, 'open') libvirt.open('qemu:///system').AndReturn(virt_con) self.mox.ReplayAll() self.assertEquals(qemu.QEMU.open(), virt_con)
def qemu_start_conn(self): try: if self.vm_host is None: conn = libvirt.open("qemu:///system") else: conn = libvirt.open("qemu+ssh://root@%s/system" % self.vm_host.hostname) except Exception, e: logging.error("Failed to start con:\n %s \n %s" % (str(e), traceback.format_exc())) raise error.TestError("Failed to connnect to qemu...")
def define_domain(xml, host=[]): if len(host) > 0: for h in host: conn = libvirt.open("qemu+ssh://" + h + "/system") conn.defineXML(xml) conn.close() else: conn = libvirt.open(None) conn.defineXML(xml) conn.close()
def vmOnList(hostName, vType): vOnList = [] if vType == 'xen': conn = libvirt.open('xen://' + hostName + '/') else: conn = libvirt.open('qemu://' + hostName + '/system') for id in conn.listDomainsID(): vOnList.append(conn.lookupByID(id)) return vOnList
def vmOffList(hostName, vType): vOffList = [] if vType == 'xen': conn = libvirt.open('xen://' + hostName + '/') else: conn = libvirt.open('qemu://' + hostName + '/system') for name in conn.listDefinedDomains(): vOffList.append(conn.lookupByName(name)) return vOffList
def migrate_domain(domain_name): try: #auth_domain() conn = libvirt.open(URI) dest_conn = libvirt.open(DEST_URI) dest_vm = conn.lookupByName(domain_name) dest_vm.migrate(dest_conn, 1, domain_name, None, 0) #dest_domain.migrate(dest_conn, 1, domain_name, 'tcp://192.168.2.110', 0) except Exception,e: print e return 1
def testNoConnection(self): """_validateNetwork is able to open its own libvirt connection.""" self.mox.StubOutWithMock(libvirt, 'open') libvirt.open(mox.IgnoreArg()).AndReturn(self.virt_con) self.mox.StubOutWithMock(utils, 'getCaller') utils.getCaller().MultipleTimes().AndReturn(500) self.mox.ReplayAll() domains._validateNetwork('debmarshal-0')
def cloneVm(vmName, vType): if vType == "xen": conn = libvirt.open('xen://') else: conn = libvirt.open('qemu:///system') vm = conn.lookupByName(vmName) newVmXml = prepareXml(vm.XMLDesc(libvirt.VIR_DOMAIN_XML_SECURE)) #define the new VM in libvirt vm = conn.defineXML(newVmXml.toxml()) if autostart: vm.create()
def create_virConnect(): global _hostname con = None try: path = 'qemu+tls://g4hv.exp.ci.i.u-tokyo.ac.jp/system' con = libvirt.open(path) _hostname = path except: path = 'qemu:///system' con = libvirt.open(path) _hostname = path return con
def setUp(self): """The only two interesting conditions to test here are whether storeState raises an exception or not, so let's commonize everything else""" super(TestCreateNetwork, self).setUp() self.networks = {'debmarshal-0': 500, 'debmarshal-3': 500, 'debmarshal-4': 500, 'debmarshal-4': 500} self.name = 'debmarshal-1' self.gateway = '169.254.3.1' self.hosts = ['wiki.company.com', 'login.company.com'] self.host_dict = {'wiki.company.com': ('169.254.3.2', '00:00:00:00:00:00'), 'login.company.com': ('169.254.3.3', '00:00:00:00:00:00')} self.mox.StubOutWithMock(utils, 'getCaller') utils.getCaller().AndReturn(1000) self.mox.StubOutWithMock(debmarshal.utils, 'acquireLock') debmarshal.utils.acquireLock('debmarshal-netlist', fcntl.LOCK_EX) self.mox.StubOutWithMock(networks, '_validateHostname') networks._validateHostname(mox.IgnoreArg()).MultipleTimes() self.mox.StubOutWithMock(libvirt, 'open') self.virt_con = self.mox.CreateMock(libvirt.virConnect) libvirt.open(mox.IgnoreArg()).AndReturn(self.virt_con) self.mox.StubOutWithMock(networks, '_findUnusedName') networks._findUnusedName().AndReturn(self.name) self.mox.StubOutWithMock(networks, '_findUnusedNetwork') networks._findUnusedNetwork(len(self.hosts)).\ AndReturn((self.gateway, '255.255.255.0')) self.mox.StubOutWithMock(networks, 'loadNetworkState') networks.loadNetworkState(self.virt_con).AndReturn(dict(self.networks)) self.mox.StubOutWithMock(virtinst.util, 'randomMAC') virtinst.util.randomMAC().MultipleTimes().AndReturn('00:00:00:00:00:00') self.mox.StubOutWithMock(networks, '_genNetworkXML') networks._genNetworkXML(self.name, self.gateway, '255.255.255.0', self.host_dict).AndReturn('<fake_xml />') self.virt_net = self.mox.CreateMock(libvirt.virNetwork) self.virt_con.networkDefineXML('<fake_xml />').AndReturn(self.virt_net) self.virt_net.create()
def connect(self): try: if self.node == 'localhost' or self.node == 'ip6-localhost': self.conn = l.open('lxc:///') else: # enable to specify user account is belong to libvirt group print(self.conn) exit(1) if not self.user: self.user = '******' self.conn = l.open('lxc+ssh://' + self.user + '@' + self.node + '/') except l.libvirtError as e: sys.stderr.write("ERROR: %s\n" % e)
def __init__(self): cmd = sub_process.Popen("uname -r", shell=True, stdout=sub_process.PIPE) output = cmd.communicate()[0] if output.find("xen") != -1: conn = libvirt.open(None) else: conn = libvirt.open("qemu:///system") if not conn: raise codes.FuncException("hypervisor connection failure") self.conn = conn
def setUp(self): """Setup some mocks common to all tests of destroyNetwork""" super(TestDestroyNetwork, self).setUp() self.mox.StubOutWithMock(debmarshal.utils, 'acquireLock') debmarshal.utils.acquireLock('debmarshal-netlist', fcntl.LOCK_EX) self.mox.StubOutWithMock(libvirt, 'open') self.virt_con = self.mox.CreateMock(libvirt.virConnect) libvirt.open(mox.IgnoreArg()).AndReturn(self.virt_con) self.networks = {'debmarshal-0': 501, 'debmarshal-1': 500} self.mox.StubOutWithMock(networks, 'loadNetworkState') networks.loadNetworkState(self.virt_con).AndReturn(dict(self.networks))
def migrate(allocation, vmname, destination): source = allocation[vmname] conn = libvirt.open("qemu+ssh://"+source+"/system") conn2 = libvirt.open("qemu+ssh://"+destination+"/system") if conn == None or conn2 == None: print 'Failed to open connection to one of the hypervisors', hv return; vm = conn.lookupByName(vmname) # 1 - live migration # 8 - persistent # 64 - shared disk, full copy # bitwise OR is needed fuel = ['some coffee', 'a doughnut', 'more coffee', 'some sugar'] print 'Migrating %s from %s to %s... (get %s)' % (vmname, source, destination,random.choice(fuel)) vm.migrate(conn2, 73)
def main(args): parser = argparse.ArgumentParser() parser.add_argument('--libvirt-url', dest='libvirturl', default="qemu:///system", help='Set libvirt connection url - default is "qemu:///system"') parser.add_argument('cluster_description_file', type=argparse.FileType('r'), help='File with cluster description') args = parser.parse_args() libvirt.registerErrorHandler(suppress_some_messages, None) with action("Connecting to libvirt at {}".format(args.libvirturl)): conn = libvirt.open(args.libvirturl) with action("Load cluster description from {}".format(args.cluster_description_file.name)): cluster = load_cluster_description(args.cluster_description_file.read()) images_path = cluster.attrs['images_path'] print "Will store images to", images_path cluster.fuel_vm.boot_network = False launch_vm(conn, cluster.fuel_vm, cluster.nets, images_path) wait_fuel_installed(cluster.fuel_vm) for vm_name, vm in cluster.vms.items(): launch_vm(conn, vm, cluster.nets, images_path) return 0
def getDefaultIP(hostnet=None): """ This method determines returns the IP of the atomic host, which is used by the kickstart file to find the atomic repository. It can accept a virt network name to help determine the IP. Else, it will count the number of networks and if only one use that. Else it will look for one named default. """ conn=libvirt.open() print hostnet numnets = int(conn.numOfNetworks()) if numnets < 1: fail_msg("No libvirt networks appear to be defined. Ensure you have a network defined and re-run.") exit(1) netlist = conn.listNetworks() if hostnet is not None: netname = hostnet elif conn.numOfNetworks() == 1: netname = netlist[0] elif "default" in netlist: netname = "default" else: fail_msg("Unable to determine your libvirt network automatically. Please re-run with --virtnetwork switch and the name of the network you want to use (from virsh net-list)") interface = conn.networkLookupByName(netname) root = ET.fromstring(interface.XMLDesc()) ip = root.find("ip").get('address') return ip
def check_connect(self): # 1. generate uri uri = self.username + "@" + self.address + "/" if int(self.type_code) == HOST_XEN: self.uri = "xen+ssh://" + uri elif int(self.type_code) == HOST_KVM: self.uri = "qemu+ssh://" + uri + "system" else: errMsg = _("Not supported hypervisor type %(code)d", code = self.type_code) self.status_code = HOST_ERROR return False,errMsg # 2. connect uri and get cpu_pool/mem_pool try: import libvirt conn = libvirt.open(self.uri) infolist = conn.getInfo() self.mem_pool = infolist[1] self.cpu_pool = infolist[2] * HOST_CPU_VALUE self.status_code = HOST_OK return True, "" except Exception, ex: self.status_code = HOST_ERROR self.mem_pool = 0 self.cpu_pool = 0 return False, str(ex)
def connection_version(params): """test libvirt connection version """ logger = params['logger'] try: # get connection firstly. # If conn is not specified, use conn from sharedmod if 'conn' in params: conn = libvirt.open(params['conn']) else: conn = sharedmod.libvirtobj['conn'] # check libvirt version number if not check_libvirt_ver_num(conn, logger): logger.error("Failed to check libvirt version number") return 1 # check hypervisor version number if not check_hypervisor_ver_num(conn, logger): logger.error("Failed to check hypervisor version number") return 1 except libvirtError, e: logger.error("API error message: %s, error code is %s" % e.message) logger.error("start failed") return 1
def __init__(self, host): """ Return connection object. """ self.login = host.login self.host = host.ipaddr self.passwd = host.passwd self.type = host.conn_type self.port = host.ssh_port if self.type == 'tcp': def creds(credentials, user_data): for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = self.login if len(credential[4]) == 0: credential[4] = credential[3] elif credential[0] == libvirt.VIR_CRED_PASSPHRASE: credential[4] = self.passwd else: return -1 return 0 flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE] auth = [flags, creds, None] uri = 'qemu+tcp://%s/system' % self.host self.conn = libvirt.openAuth(uri, auth, 0) if self.type == 'ssh': uri = 'qemu+ssh://%s@%s:%s/system' % (self.login, self.host, self.port) self.conn = libvirt.open(uri)
def destroy(vid): fopen =open("virinfo","r") lines =fopen.readlines() fopen.close() cnt=0 myname=0 fopen1 =open("virinfo1","w") words1=[] for line in lines: words1=line.split(" ") if str(words1[0])!=str(vid): fopen1.write(str(words1[0])+" "+str(words1[1])+" "+str(words1[2])+" "+str(words1[3])) else: myname = words1[1] cnt=cnt+1 fopen1.close() fopen1=open("virinfo1","r") lines =fopen1.readlines() fopen1.close() fopen2=open("virinfo","w") for x in lines: fopen2.write(x) connect = libvirt.open("remote+ssh://"+create_vm.pmList[int(create_vm.pm_n)].strip('\n')+"/") req = connect.lookupByName(str(myname)) if req.isActive(): req.destroy() req.undefine() return {"status":"1"}
def reboot(self, host): conn = libvirt.open(f'qemu+ssh://{host}/system') dom = conn.lookupByName(self.name) dom.reboot() conn.close()
def create(self, host, password, ifname, ip, hostname, gw, template, path, key=''): """"path" parameter is the path where the storage pool is mounted ('mypool'). parameters are: - host > ip address (str) with prefix of the host (ex:'192.168.1.50/24') - password > password of the cloud image user - ifname > name of the public interface in cloud image (ex:eth0 in fedora, ens0p3 in centos7) - ip > public ip address (str) of the vm - hostname > hostname for the vm - gw > ip address (str) of the gateway without prefix (ex:'192.168.1.1') - template > name of the cloud image template to be used - path > the path where the storage pool is mounted ('mypool') - key > public key to be added to trusted keys of the vm (optional) """ try: p = self._createDir(host, path) except: raise CreateVmException(f'failed to create directory {path}') md = metaData(hostname, hostname, ifname, ip, gw) try: md.create(host, p) except: raise CreateVmException('failed to create meta-data') if key == '': ud = userData(password) else: ud = userData(password, key=key) try: ud.create(host, p) except: self._deleteDir(host, path) md.delete(host, p) raise CreateVmException('failed to create user-data') iso = configIso(md, ud) try: iso.create(host, p) except: self._deleteDir(host, path) ud.delete(host, p) md.delete(host, p) raise CreateVmException('failed to create config iso') strg = storage(self.name, self.disk, template, path=path, pool=self.pool) try: strg.create(host) except: iso.delete(host, p) self._deleteDir(host, path) raise CreateVmException('failed to create storage volume') net = publicIface(self.id_num, ip) try: net.create(host) except: iso.delete(host, p) self._deleteDir(host, path) strg.delete(host) raise CreateVmException('failed to create public interface') network_XML = '' if len(self.networks) > 0: try: for n in self.networks: i = privateIface(self.id_num, n) iname = i.create(host) self.ifaces.append(i) net_mac = self._genMacAddr() network_XML += f'''<interface type="ethernet"> <mac address="{net_mac}"/> <target dev="{self.id_num}-{n}"/> </interface>''' self.network_map.append({ "network": n, "mac": net_mac, "iface": iname, "host": host, "owner": self.owner }) except: iso.delete(host, p) self._deleteDir(host, path) strg.delete(host) net.delete(host) if len(self.ifaces) > 0: for i in self.ifaces: i.delete(host) raise CreateVmException('failed to create private interfaces') confISO_XML = f'''<disk type="file" device="cdrom"> <source file="{path}/{self.name}/config.iso"/> <target dev="hdb" bus="ide"/> </disk> ''' for n in self.networks: net_mac = self._genMacAddr() network_XML += f'''<interface type="ethernet"> <mac address="{net_mac}"/> <target dev="{self.id_num}-{n}"/> </interface>''' self.network_map.append({ "network": n, "mac": net_mac, "iface": f"{self.id_num}-{n}", "host": host, "owner": self.owner }) XMLConf = f''' <domain type="kvm"> <name>{self.name}</name> <uuid>{str(self.v_uuid)}</uuid> <memory>{self.ram}</memory> <currentMemory>{self.ram}</currentMemory> <vcpu>{self.cpu}</vcpu> <os> <type arch="x86_64" machine="pc">hvm</type> </os> <features> <acpi/> <apic/> <pae/> </features> <clock offset="localtime"/> <on_poweroff>destroy</on_poweroff> <on_reboot>destroy</on_reboot> <on_crash>destroy</on_crash> <devices> <disk type="file" device="disk"> <source file="{path}/{self.name}.img"/> <target dev="hda" bus="ide"/> </disk> {confISO_XML} <interface type="ethernet"> <target dev="{self.id_num}"/> </interface> {network_XML} <graphics type="vnc" port="5900" autoport="yes" listen="0.0.0.0"/> </devices> </domain> ''' conn = libvirt.open(f'qemu+ssh://root@{host}/system') if conn == None: iso.delete(host, p) self._deleteDir(host, path) strg.delete(host) net.delete(host) for i in self.ifaces: i.delete(host) raise ConnectionFailedException('failed to connect to host') try: dom = conn.defineXML(XMLConf) except Exception as e: iso.delete(host, p) self._deleteDir(host, path) strg.delete(host) net.delete(host) for i in self.ifaces: i.delete(host) conn.close() raise CreateVmException('failed to define xml for vm.') if dom == None: iso.delete(host, p) self._deleteDir(host, path) strg.delete(host) net.delete(host) for i in self.ifaces: i.delete(host) conn.close() raise CreateVmException('failed to define xml for vm') try: if dom.create() < 0: iso.delete(host, p) self._deleteDir(host, path) strg.delete(host) net.delete(host) for i in self.ifaces: i.delete(host) dom.undefine() conn.close() raise CreateVmException('failed to create vm') except Exception as e: iso.delete(host, p) self._deleteDir(host, path) strg.delete(host) net.delete(host) for i in self.ifaces: i.delete(host) conn.close() raise CreateVmException('failed to create vm') conn.close() return self.v_uuid
def shutdown(self, host): conn = libvirt.open(f'qemu+ssh://{host}/system') dom = conn.lookupByName(self.name) dom.shutdown() conn.close()
def action(networkid, sourceip, vlan, externalip): from CloudscalerLibcloud.utils.network import Network, NetworkTool import libvirt import netaddr from xml.etree import ElementTree import re target_con = libvirt.open() try: source_con = libvirt.open("qemu+ssh://%s/system" % sourceip) except: source_con = None network = Network() hrd = j.atyourservice.get(name="vfwnode", instance="main").hrd netrange = hrd.get("instance.vfw.netrange.internal") internalip = str( netaddr.IPAddress(netaddr.IPNetwork(netrange).first + int(networkid)) ) netinfo = [{"type": "vlan", "id": vlan}, {"type": "vxlan", "id": networkid}] extbridge = j.system.ovsnetconfig.getVlanBridge(vlan) name = "routeros_%04x" % networkid with NetworkTool(netinfo): if source_con: templatepath = "/var/lib/libvirt/images/routeros/template/routeros.qcow2" destination = "/var/lib/libvirt/images/routeros/{0:04x}".format(networkid) destinationfile = j.system.fs.joinPaths(destination, "routeros.qcow2") try: domain = source_con.lookupByName(name) except libvirt.libvirtError: domain = None if domain: if domain.state()[0] == libvirt.VIR_DOMAIN_RUNNING: localip = j.system.net.getReachableIpAddress(sourceip, 22) targeturl = "tcp://{}".format(localip) if not j.system.fs.exists(destination): j.system.fs.createDir(destination) if not j.system.fs.exists(destinationfile): j.system.fs.copyFile(templatepath, destinationfile) xmldom = ElementTree.fromstring(domain.XMLDesc()) seclabel = xmldom.find("seclabel") if seclabel is not None: xmldom.remove(seclabel) xml = ElementTree.tostring(xmldom) xml = re.sub( r"bridge='(public|ext-\w+)'", r"bridge='{}'".format(extbridge), xml, ) flags = ( libvirt.VIR_MIGRATE_LIVE | libvirt.VIR_MIGRATE_PERSIST_DEST | libvirt.VIR_MIGRATE_UNDEFINE_SOURCE | libvirt.VIR_MIGRATE_NON_SHARED_DISK ) try: domain.migrate2( target_con, flags=flags, dxml=xml, uri=targeturl ) except Exception as e: try: target_domain = target_con.lookupByName(name) target_domain.undefine() except: pass # vm wasn't created on target raise e domain = target_con.lookupByName(name) network.protect_external(domain, externalip) network.protect_gwmgmt(domain, internalip) return domain.XMLDesc() else: domain.undefine() return False else: return False else: # source is not available caller should probable do a restore from scratch return False
def connection_context(): conn = libvirt.open("qemu:///system") try: yield conn finally: conn.close()
def test_edit_shutdown_start(self): vm_uuid = self._setupvm() if not vm_uuid: return #修改备注测试 vmobj = Vm.objects.get(uuid=vm_uuid) hostobj = Host.objects.get(id=self.h1.id) remarks = 'test123' req = {'req_user': self.u1, 'uuid': vmobj.uuid, 'remarks': remarks} exp = {'res': True} res = edit(req) self.assertDictEqual(exp, res) self._assert_host(hostobj) vmobj.remarks = remarks self._assert_vm(vmobj) #运行状态修改 vmobj = Vm.objects.get(uuid=vm_uuid) hostobj = Host.objects.get(id=self.h1.id) vcpu = 3 mem = 3000 req1 = { 'req_user': self.u1, 'uuid': vmobj.uuid, 'vcpu': vcpu, 'mem': mem } exp1 = {'res': False} res1 = edit(req1) self.assertDictContainsSubset(exp1, res1) self._assert_host(hostobj) self._assert_vm(vmobj) #poweroff操作测试 req11 = {'req_user': self.u1, 'uuid': vmobj.uuid, 'op': 'poweroff'} exp11 = {'res': True} res11 = op(req11) self.assertDictEqual(exp11, res11) if res11['res']: #状态 req6 = {'req_user': self.u1, 'uuid': vm_uuid} conn = libvirt.open("qemu+ssh://%s/system" % self.h1.ipv4) domain = conn.lookupByUUIDString(vm_uuid) info = domain.info() exp6 = {'res': True, 'status': info[0]} res6 = status(req6) self.assertDictEqual(exp6, res6) #修改cpu测试 vmobj = Vm.objects.get(uuid=vm_uuid) hostobj = Host.objects.get(id=self.h1.id) vcpu = 4 req2 = {'req_user': self.u1, 'uuid': vmobj.uuid, 'vcpu': vcpu} exp2 = {'res': True} res2 = edit(req2) self.assertDictEqual(exp2, res2) hostobj.vcpu_allocated = hostobj.vcpu_allocated - vmobj.vcpu + vcpu self._assert_host(hostobj) vmobj.vcpu = vcpu self._assert_vm(vmobj) #修改mem测试 vmobj = Vm.objects.get(uuid=vm_uuid) hostobj = Host.objects.get(id=self.h1.id) mem = 4096 req3 = {'req_user': self.u1, 'uuid': vmobj.uuid, 'mem': mem} exp3 = {'res': True} res3 = edit(req3) self.assertDictEqual(exp3, res3) hostobj.mem_allocated = hostobj.mem_allocated - vmobj.mem + mem self._assert_host(hostobj) vmobj.mem = mem self._assert_vm(vmobj) #修改cpu和mem测试 vmobj = Vm.objects.get(uuid=vm_uuid) hostobj = Host.objects.get(id=self.h1.id) vcpu = 3 mem = 3000 req4 = { 'req_user': self.u1, 'uuid': vmobj.uuid, 'vcpu': vcpu, 'mem': mem } exp4 = {'res': True} res4 = edit(req4) self.assertDictEqual(exp4, res4) hostobj.vcpu_allocated = hostobj.vcpu_allocated - vmobj.vcpu + vcpu hostobj.mem_allocated = hostobj.mem_allocated - vmobj.mem + mem self._assert_host(hostobj) vmobj.vcpu = vcpu vmobj.mem = mem self._assert_vm(vmobj) #start操作测试 req5 = {'req_user': self.u1, 'uuid': vmobj.uuid, 'op': 'start'} exp5 = {'res': True} res5 = op(req5) self.assertDictEqual(exp5, res5) self._teardownvm(vm_uuid)
def bootImg(index, REP, img, mem, cantCpu=1, kdb=False, sriov=False, ifSRIOV=""): defUser = img["defUser"] imgOp = img["img"] # Define variables name = "vm-" + index print("NAME", name) imgPath = "{0}/{1}".format(REP, imgOp) # Define user-data y meta-data print("Construyendo cloud-config ...") os.system( "rm -rf ../Imagenes/{0}; mkdir -p ../Imagenes/{0}; rm -rf {1}/{0}/ ; mkdir -p {1}/{0}" .format(index, REP)) sshKeyArray = [] for file in os.listdir(sshPath): with open(sshPath + '/' + file, 'r') as f: sshKeyArray.append(f.read()) fileArray = [] userArray = [{"name": name, "password": "******"}] udt, mdt = lT.cloudConfig(userDataPath, metaDataPath, index, name, sshKeyArray, fileArray, userArray, defUser) f = open("../Imagenes/" + index + "/user-data", "w") f.write(udt) f.close() f = open("../Imagenes/" + index + "/meta-data", "w") f.write(mdt) f.close() # Visualizacion de user-data y meta-data print("User-data") print(udt) print("Meta-data") print(mdt) print("Ejecutando bash ../CloudInit/crearQcow.sh {0} {1} {2}...".format( imgOp, index, REP)) os.system("bash ../CloudInit/crearQcow.sh {0} {1} {2}".format( imgOp, index, REP)) #Define domainConfig.xml print("Construyendo domainConfig.xml ...") # Funciona para direct-kernel boot y boot por volumen disksArray = [{ 'device': 'disk', 'path': "{0}/{1}/boot-disk.img".format(REP, index), 'hdType': 'vda', 'driverType': 'qcow2', 'bus': 'virtio' }, { 'device': 'cdrom', 'path': '{0}/{1}/seed.iso'.format(REP, index), 'hdType': 'hda', 'driverType': 'raw', 'bus': 'ide' }] # Creacion de la interfaz tap mac = nextMac(index) # os.system("bash crearInterfazTap.sh {0} {1}".format(index, mac)) tapInt = "tap" + index ifacesArray = [{ 'name': tapInt, 'type': 'network', 'mac': mac, 'targetDev': tapInt, 'modelType': 'virtio' }] # Para el Direct Kernel Boot kernelPath = "" initrdPath = "" if kdb: os.system("cp {0}/{1} {0}/{2}/vmlinuz".format(REP, img["kernel"], index)) os.system("cp {0}/{1} {0}/{2}/initrd".format(REP, img["initrd"], index)) kernelPath = "{0}/{1}/vmlinuz".format(REP, index) initrdPath = "{0}/{1}/initrd".format(REP, index) # Para PCI PassThrough / SRIOV ifSRIOVL = {} if sriov: ifSRIOVD = ifSRIOV.split(":") domainIF = "0x" + ifSRIOVD[0] busIF = "0x" + ifSRIOVD[1] slotIF = "0x" + ifSRIOVD[2].split(".")[0] functionIF = "0x" + ifSRIOVD[2].split(".")[1] ifSRIOVL = { 'domain': domainIF, 'bus': busIF, 'slot': slotIF, 'function': functionIF } xmlConfig = lT.xmlConfig(hwTemplatePath, name, mem, cantCpu, disksArray, ifacesArray, kdb, kernelPath, initrdPath, sriov, ifSRIOVL) # Mostar toda la configuracion para una maquina virtual. print("*" * 70) print("libvirt confiuration:") print(xmlConfig) # Levantar la maquina mediante libvirt. conn = libvirt.open('qemu:///system') if conn == None: print('Failed to open connection to qemu:///system') return False dom = conn.createXML(xmlConfig.replace("\n", ""), 0) if dom == None: print('Failed to create a domain from an XML definition.') return False print('VM', dom.name(), ' ha sido booteada.') return { "name": name, "mem": mem, "cpus": cantCpu, "imagen": imgOp, "ifaces": ifacesArray, "disksArray": disksArray }
def libvirt_connect(): return libvirt.open("qemu:///system")
def migrate_domain(self, name, target): '''Migrates the specified domain to the target machine.''' target_conn = libvirt.open(target) virtmachine = self.get_domain(name) virtmachine.migrate(target_conn, libvirt.VIR_MIGRATE_LIVE, None, None, 0)
def _ros_kvm_init(**kwargs): nonlocal virtual_name virtual_name = _id_generator() mac = _mac_generator() _manage_path() if kwargs.get('is_kernel_parameters'): kernel_parameters = kwargs.get('kernel_parameters') xml_for_virtual = KERNEL_PARAMETERS_XML.format( virtual_name=virtual_name, mac_address=mac, v_name_for_source=virtual_name, kernel_parameters=kernel_parameters) else: if kwargs.get('is_second_hd'): second_drive_name = virtual_name + '_second' # Create second_drive _create_qcow2('2', second_drive_name) second_driver_gist = SECOND_DRIVE_XML_GIST.format(second_drive_name=second_drive_name) else: second_driver_gist = '' if kwargs.get('is_network_gist'): network_xml_gist = NETWORK_XML_GIST else: network_xml_gist = '' xml_for_virtual = KVM_XML.format(virtual_name=virtual_name, mac_address=mac, v_name_for_source=virtual_name, second_driver_gist=second_driver_gist, network_xml_gist=network_xml_gist) # region Create qcow2 if kwargs.get('is_b2d'): _create_b2d_qcow2('10', virtual_name) else: _create_qcow2('10', virtual_name) # endregion nonlocal conn conn = libvirt.open('qemu:///system') if not conn: raise Exception('Failed to open connection to qemu:///system') else: nonlocal dom nonlocal is_define_xml is_define_xml = kwargs.get('is_define_xml') if is_define_xml: dom = conn.defineXML(xml_for_virtual) dom.create() else: dom = conn.createXML(xml_for_virtual) ip = _get_ip(mac) if ip: if kwargs.get('is_install_to_hard_drive'): cloud_config = kwargs.get('cloud_config') client = connection(ip=ip, seconds=kwargs.get('seconds_for_install')) _install_to_hdrive(cloud_config, client, kwargs.get('extra_install_args')) time.sleep(30) ssh = connection(ip, seconds=kwargs.get('seconds_for_reconnect')) return ssh, ip, virtual_name, dom else: return None
def main(): """Check if VMs are still valid.""" parser = OptionParser(usage='Usage: %%prog [options] [uri]') parser.add_option( '-v', '--verbose', action='count', dest='verbose', default=0, help='Increase verbosity') parser.add_option( '-g', '--dot', action='store_true', dest='dot', default=False, help='Generate dot graph') parser.add_option( '-a', '--all', action='store_true', dest='show_all', default=False, help='Show all resources') parser.add_option( '-u', '--unused', action='store_true', dest='show_unused', default=False, help='Show unused resources') options, arguments = parser.parse_args() logging.basicConfig(level={ 0: logging.CRITICAL, 1: logging.ERROR, 2: logging.WARNING, 3: logging.INFO, 4: logging.DEBUG, 5: logging.NOTSET, }.get(options.verbose, logging.NOTSET)) try: url = arguments[0] except IndexError: if os.path.exists('/dev/kvm'): url = 'qemu:///system' else: parser.print_usage(sys.stderr) sys.exit(2) libvirt.registerErrorHandler(lambda f, ctx: None, None) conn = libvirt.open(url) try: # volumes first because this is more detailed check_storage_pools(conn) check_virtual_machines(conn) check_storage_volumes(conn) finally: conn.close() # Validate all resources for res in list(Resource.all.values()): res.check_valid() # Print all resources filtered = set() for res in Resource.all.values(): if options.show_all or \ options.show_unused and not res.used or \ not res.valid: filtered.add(res) text = '// %s' % (res.console(),) print(text) if options.dot: if not options.show_all: filtered = resource_closure(filtered) print_dot(filtered)
def __init__(self, con): """Initialise serving application.""" self.con = libvirt.open(con) self.logger = logging.getLogger('manageVM.server') super(ManageVM, self).__init__()
def GetKvmInfo(self): conn = libvirt.open('qemu:///system') dom = conn.listDomainsID() data_id_dict = {} for i in dom: data_dict = {} vmm_id = conn.lookupByID(i) vmm_name = vmm_id.name() vmm_id_str = str(vmm_name) data_dict["id"] = vmm_id_str vmm_xml_name = vmm_id_str + '.' + 'xml' vmm_xml_path = '/tmp/' + vmm_xml_name vmm_xml_open = ET.parse(vmm_xml_path) path_list = [] path = vmm_xml_open.findall('.//source') for i in path: file1 = i.attrib filename = file1.get('file') if filename: path_list.append(filename) interface_list = [] interface = vmm_xml_open.findall('.//target') for j in interface: interface_network = j.attrib dev1 = interface_network.get('dev') dev3 = 'vnet' dev2 = str(dev1) if dev3 in dev2: interface_list.append(dev1) #获取流量信息 totalrx_byte = 0 totaltx_byte = 0 for interfaceinfo_path in interface_list: interfaceinfo = vmm_id.interfaceStats(interfaceinfo_path) totalrx_byte = totalrx_byte + interfaceinfo[0] totaltx_byte = totaltx_byte + interfaceinfo[4] data_dict["net_input"] = float(totalrx_byte) / 1024 data_dict["net_output"] = float(totaltx_byte) / 1024 #获取cpu信息 totalcpu = 'cpu' totalcpu_usage = 0 cpu_time = vmm_id.info()[4] data_dict["cpu_time"] = cpu_time #获取内存信息 pid = (os.popen( "ps aux|grep " + vmm_id_str + " | grep -v 'grep' | awk '{print $2}'").readlines()[0]) memstatus = 0 #linux下 /proc/pid(进程ID)/smaps 下保存的是进程内存映像信息,比同一目录下的maps文件更详细些 for line in file('/proc/%d/smaps' % int(pid), 'r'): if re.findall('Private_', line): #统计Private内存信息量 memstatus += int(re.findall('(\d+)', line)[0]) memusage = float( '%.2f' % (int(memstatus) * 100.0 / int(vmm_id.info()[2]))) - 15 if memusage > 100.00: memusage = 100.00 elif memusage < 0.00: memusage = 0.00 data_dict["mem"] = memusage data_id_dict[vmm_id_str] = data_dict return data_id_dict
def setUp(self): self.conn = libvirt.open("test:///default") self.pool = self.conn.storagePoolLookupByName("default-pool")
def poweron(self, host): conn = libvirt.open(f'qemu+ssh://{host}/system') dom = conn.lookupByName(self.name) dom.create() conn.close()
def delete_virtual_network(**kargs): """ Deletes a libvirt network. Parameters ---------- kargs: dict arguments expected keys: network_name : str The name for the new virtual network Returns ------- int 0 on success, 1 otherwise. """ libvirtConn = libvirt.open(None) if libvirtConn is None: _logger.error('Cannot find network named [%s]' % kargs['network_name']) return 1 net = None try: net = libvirtConn.networkLookupByName(kargs['network_name']) except libvirt.libvirtError: _logger.error('Cannot find network named [%s]' % kargs['network_name']) return 1 root = ElementTree.fromstring(net.XMLDesc()) _interface_elem = None # we have only one element per iteration for _f in root.findall('forward'): for _i in _f.findall('interface'): _interface_elem = _i if _interface_elem is None: _logger.error('Cannot find any interface in network XML description') return 1 device_name = _interface_elem.get('dev') if device_name is None: _logger.error('Cannot find device information in interface node') return 1 bridge_name = root.findall('bridge')[0].get('name') ip_bridge = root.findall('ip')[0].get('address') ip_prefix = root.findall('ip')[0].get('prefix') device_name_splitted = device_name.split('.') # we may not have vlanTag if len(device_name_splitted) == 1: (vf_dev, vlanTag) = (device_name_splitted[0], None) else: (vf_dev, vlanTag) = (device_name_splitted[0], device_name_splitted[1]) fw_cmd = ['-t', 'nat', '-A', 'POSTROUTING', '-s'] fw_cmd.append('%s/%s' % (ip_bridge, ip_prefix)) fw_cmd.extend(['-d', '224.0.0.0/24', '-j', 'ACCEPT']) remove_firewall_rule(*fw_cmd) fw_cmd = ['-t', 'nat', '-A', 'POSTROUTING', '-s'] fw_cmd.append('%s/%s' % (ip_bridge, ip_prefix)) fw_cmd.extend(['-d', '255.255.255.255/32', '-j', 'ACCEPT']) remove_firewall_rule(*fw_cmd) fw_cmd = ['-t', 'nat', '-A', 'POSTROUTING', '-s'] fw_cmd.append('%s/%s' % (ip_bridge, ip_prefix)) fw_cmd.extend(['!', '-d', '%s/%s' % (ip_bridge, ip_prefix), '-j', 'MASQUERADE']) remove_firewall_rule(*fw_cmd) remove_static_ip_routes(bridge_name) remove_static_ip_rules(vf_dev) remove_static_ip_routes(device_name) delete_route_table(vf_dev) if net.isActive(): _logger.debug('stopping the virtual network') net.destroy() _logger.debug('unbdefining the virtual network') net.undefine() # do not needd that anymore libvirtConn.close() _logger.debug('destroying VF interfaces') destroy_networking(vf_dev, vlanTag) SystemdServiceManager('kvm_net_%s' % kargs['network_name']).stop() SystemdServiceManager('kvm_net_%s' % kargs['network_name']).remove() _logger.debug('Virtual network deleted') return 0
def update(self, host, path, new_name, ram, cpu, new_networks=[]): conn = libvirt.open(f'qemu+ssh://{host}/system') dom = conn.lookupByName(self.name) dom.destroy() dom.undefine() conn.close() for n in self.networks: privateIface(self.id_num, n).delete(host) self.ifaces = [] self.networks = [] self.network_map = [] network_XML = '' for n in new_networks: i = privateIface(self.id_num, n) iname = i.create(host) self.ifaces.append(i) self.networks.append(n) net_mac = self._genMacAddr() network_XML += f'''<interface type="ethernet"> <mac address="{net_mac}"/> <target dev="{self.id_num}-{n}"/> </interface>''' self.network_map.append({ "network": n, "mac": net_mac, "iface": iname, "host": host, "owner": self.owner }) XMLConf = f''' <domain type="kvm"> <name>{self.name}</name> <uuid>{str(self.v_uuid)}</uuid> <memory>{self.ram}</memory> <currentMemory>{self.ram}</currentMemory> <vcpu>{self.cpu}</vcpu> <os> <type arch="x86_64" machine="pc">hvm</type> </os> <features> <acpi/> <apic/> <pae/> </features> <clock offset="localtime"/> <on_poweroff>destroy</on_poweroff> <on_reboot>destroy</on_reboot> <on_crash>destroy</on_crash> <devices> <disk type="file" device="disk"> <source file="{path}/{self.name}.img"/> <target dev="hda" bus="ide"/> </disk> <interface type="ethernet"> <target dev="{self.id_num}"/> </interface> {network_XML} <graphics type="vnc" port="5900" autoport="yes" listen="0.0.0.0"/> </devices> </domain> ''' #not yest finished pass
<type arch='x86_64' machine='pc-i440fx-bionic'>hvm</type> <boot dev='hd'/> </os> <devices> <disk type='file' device='disk'> <driver name='qemu' type='qcow2'/> <source file='/home/iputra/f1les/nolsatu/reuni/images/%s'/> <target dev='vda' bus='virtio'/> </disk> <interface type='network'> <source network='%s'/> </interface> <graphics type='vnc' port='%s'/> </devices> </domain> ''' domainName = "vm-ikhsan" domainMemory = str(2 * 1024 * 1000) domainCurrentMemory = domainMemory domainVcpu = "2" domainDisk = "ik-node01.img" domainNetwork = "default" domainVncPort = "5901" domainXML = domainTemplateXML % (domainName, domainMemory, domainCurrentMemory, domainVcpu, domainDisk, domainNetwork, domainVncPort) conn = libvirt.open("qemu:///system") domain = conn.defineXML(domainXML)
import libxml2 import pdb def usage(): print 'Usage: %s DIR' % sys.argv[0] print ' Restore all the domains contained in DIR' print ' It is assumed that all files in DIR are' print ' images of domU\'s previously created with save' if len(sys.argv) != 2: usage() sys.exit(2) dir = sys.argv[1] imgs = os.listdir(dir) conn = libvirt.open(None) if conn is None: print 'Failed to open connection to the hypervisor' sys.exit(1) for img in imgs: file = os.path.join(dir, img) print "Restoring %s ... " % img, sys.stdout.flush() ret = conn.restore(file) if ret == 0: print "done" else: print "error %d" % ret
def connect(cls, url, config): return cls(libvirt.open(), config)
def destroy(name, delete_disks): """ Destroys a libvirt domain by name, and de-allocates any assigned resources. Parameters ---------- name : str The domain name. delete_disks : bool Do we also delette to storage pool based disks ? stop_it_first : boool Do we shutdown the VM if it is running ? gracefull : bool Do we force the operation ? Returns ------- int 1 if domain does not exist or is running. Return value form virsh undefine. """ libvirtConn = libvirt.open(None) if libvirtConn is None: _logger.error('Failed to open connection to qemu:///system') return 1 dom = libvirtConn.lookupByName(name) if dom == None: _logger.error('domain do not exists') return 1 # check that domains is on libvirt network or not # if so we have nothing to do about networking # interface XML is like the following . locate the network and check # if 'source' is of type network # <interface type='network'> # <mac address='...'/> # <source network='xxx' bridge='xxx'/> # ... # </interface> _use_virtual_network = False try: raw_xml = ElementTree.fromstring(dom.XMLDesc()) all_devices = raw_xml.findall('devices') # we expect only one 'devices' section net_intfs = [intf for intf in all_devices[0].findall('interface') if intf.get('type') == 'network'] if len(net_intfs) > 0: vnet = net_intfs[0].findall('source')[0].get('network') if vnet: _logger.debug('destroy: use of virtual network [%s] detected' % vnet) _use_virtual_network = True except libvirt.libvirtError as e: _logger.error('Failed to get domain information: %s' % e.get_error_message()) libvirtConn.close() return 1 if not _use_virtual_network: _logger.debug('destroy: destroying network of domain') destroy_domain_vlan(name) if delete_disks: _logger.debug('looking for used libvirt volume') for device in raw_xml.findall('devices'): for disk in device.findall('disk'): for source in disk.findall('source'): file_as_source = source.get('file') if file_as_source: _vol = virt_utils.find_storage_pool_volume_by_path(libvirtConn, file_as_source) if _vol: _logger.debug('libvirt volume found [%s]' % _vol.name()) try: _vol.wipe(0) _vol.delete(0) _logger.debug('libvirt volume deleted') except libvirt.libvirtError as e: _logger.error('Cannot delete volume [%s]: %s' % (_vol.name(), str(e))) libvirtConn.close() return subprocess.call([SUDO_CMD, VIRSH_CMD, 'undefine', name])
def open(cls): cfg = plugin.cfg() con = libvirt.open(cfg.virt.uri) return con
def create_domain(name1, instance_type1, image_id1, machine_list, image_list, Vdesc, info): global machine_id, vmid, query_list #machine_id = (machine_id+1)%len(machine_list) #print machine_id #machine=machine_list[0] #user= machine[0] #ip= machine[1] uid = str(uuid4()) #print user #print ip print uid # to index the image wimage = str(image_list[int(image_id1)]) print wimage temp = int(instance_type1) #print temp temp = temp - 1 Ram = Vdesc['types'][temp]['ram'] Ram = Ram * 1024 Ram1 = str(Ram) #print Ram1 VCPU = Vdesc['types'][temp]['cpu'] VCPU1 = str(VCPU) cpu = int(VCPU1) print cpu #print VCPU1 n_mac = len(info) ntries = 0 flag = -1 while ntries != n_mac: match = info[ntries] if (match[1] * 1024 >= Ram and match[2] >= cpu): flag = ntries break ntries = ntries + 1 user = -1 ip = -1 arch = -1 if flag != -1: machine = machine_list[flag] #vmid=vmid+1 user = machine[0] ip = machine[1] arch = info[flag][0] vmid = vmid + 1 temp_list = [] temp_list.append(vmid) temp_list.append(name1) temp_list.append(instance_type1) temp_list.append(machine_id) #print temp_list query_list.append(temp_list) os.system("scp %s %s" % ("vishalxyz/" + wimage, user + "@" + ip + ":~/")) #print query_list else: perr("could not fine suitable machine") return 0 try: conn = libvirt.open(parse.Make_Path(user, ip)) request = conn.defineXML( create_xml(conn.getType().lower(), name1, Ram1, uid, VCPU1, arch, user, wimage)) request.create() return str(vmid) except: return "0"
# Example-21.py from __future__ import print_function import sys import libvirt filename = '/var/lib/libvirt/save/demo-guest.img' conn = libvirt.open('qemu:///system') if conn == None: print('Failed to open connection to qemu:///system', \ file=sys.stderr) exit(1) if id = conn.restore(filename)) < 0: print('Unable to restore guest from '+filename, \ file=sys.stderr) exit(1) dom = conn.lookupByID(id); if dom == None: print('Cannot find guest that was restored', file=sys.stderr) exit(1) print('Guest state restored from '+filename, file=sys.stderr) conn.close() exit(0)
# Example-5.py from __future__ import print_function import sys import libvirt conn1 = libvirt.open('qemu:///system') if conn1 == None: print('Failed to open connection to qemu:///system', \ file=sys.stderr) exit(1) conn2 = libvirt.open('qemu:///system') if conn2 == None: print('Failed to open connection to qemu:///system', \ file=sys.stderr) exit(1) conn1.close() conn2.close() exit(0)
def __init__(self): self.conn = libvirt.open('qemu:///session') if self.conn is None: print(colored("[X] Could not connect to qemu:///session", 'red')) exit(1)
def set_user_passwd(params): """ test API for setUserPassword in class virDomain """ logger = params['logger'] guest = params['guestname'] username = params['username'] userpasswd = params['userpassword'] if 'flags' in params: if params['flags'] == 'encrypted': flags = libvirt.VIR_DOMAIN_PASSWORD_ENCRYPTED else: flags = 0 else: flags = 0 try: if 'conn' in params: conn = libvirt.open(params['conn']) else: conn = libvirt.open(optional_params['conn']) logger.info("get connection to libvirtd") vm = conn.lookupByName(guest) logger.info("test guest name: %s" % guest) if not check_agent_status(vm): logger.error("guest agent is not connected") return 1 mac = get_guest_mac(vm) if not mac: logger.error("cannot get guest interface mac") return 1 ipaddr = utils.mac_to_ip(mac, 180) if not ipaddr: logger.error("cannot get guest IP") return 1 if flags > 0: passwd = crypt.crypt("123456", crypt.mksalt(crypt.METHOD_SHA512)) else: passwd = "123456" if create_new_user(ipaddr, "usertestapi", username, userpasswd, logger) != 0: return 1 vm.setUserPassword("usertestapi", passwd, flags) if verify_cur_user(ipaddr, "usertestapi", "123456") != 0: logger.error("cannot login guest via new user") return 1 except libvirtError as e: logger.error("API error message: %s" % e.message) return 1 return 0
def __init__(self, uri): self.uri = uri self.connection = libvirt.open(uri)
config = True flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG if o in ("-l", "--live"): live = True flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE if len(args) < 2: usage() sys.exit(1) elif len(args) >= 3: uri = args[2] domain = args[0] count = int(args[1]) conn = libvirt.open(uri) dom = conn.lookupByName(domain) if flags == 0 or config: confvcpus = dom.vcpusFlags(libvirt.VIR_DOMAIN_AFFECT_CONFIG) if confvcpus < count: print("Persistent domain configuration has only " + str(confvcpus) + " vcpus configured") sys.exit(1) if flags == 0 or live: livevcpus = dom.vcpusFlags(libvirt.VIR_DOMAIN_AFFECT_LIVE) if livevcpus < count: print("Live domain configuration has only " + str(livevcpus) +
def start_vm(vm_xml_file, vm_name): try: conn = libvirt.open(uri) except Exception, e: print 'Faild to open connection to the hypervisor' sys.exit(1)