Virtualization cloud and automated self-built KVM templates

Source: Internet
Author: User
Tags exception handling uuid python script

Later on the internet also found two to achieve similar functions of the script, one is the shell version, one is the Python version. Eventually I combine some of the characteristics between the two to do a little integration and optimization between the two, out of an enhanced version, here to share, back to have time to upload github up.

One, Python script content
As follows:

The code is as follows Copy Code

#!/usr/bin/env python
###########################################
#Version 2.0
#order by Www.111cn.net

#Function Description:
#Batch automatically generated/delete VM
#1. Generated VM
# #1.1.Copy VM img File
# #1.2.Create VM XML File
# # #1.2.1.Update UUID
# # #1.2.2.Update MAC
# # #1.2.3.Update img Path
# # #1.2.4.Update VM Name
#2. Start VM
#3. Delete VM
####################################################################
#import module
Import Shutil
Import Os,sys
From virtinst.util Import *
Import Libvirt
Import re
If Sys.version_info < (2,5):
Import Lxml.etree as ET
Else
Try
Import Xml.etree.cElementTree as ET
Except Importerror:
Import Xml.etree.ElementTree as ET
#Define variables
Template_img_path= "/template/img"
Template_xml_path= "/template/xml"
Vm_img_path= "/file"
Vm_xml_path= "/etc/libvirt/qemu"
Vm_file= "/template/conf/newvm.ini"
Uri= "Qemu:///system"
def file_exists (file):
If os.path.exists (file):
Return 1
Else
return 0
def copy_vm_img_file (src_img_file,dst_img_file):
Print "Start Copy", Src_img_file, "to", Dst_img_file
If File_exists (dst_img_file):
print ' File%s exists, abort '% dst_img_file
Sys.exit (1)
Shutil.copyfile (Src_img_file,dst_img_file)
Print "done!"
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)
Create = True
If create:
Xmlfile=open (Vm_xml_file)
Xmldesc=xmlfile.read ()
Xmlfile.close ()
Try
Vmname = Conn.definexml (XMLDESC)
Except Exception,e:
Print "Failed to define%s:%s"% (vm_name,e)
Sys.exit (1)
If Vmname is None:
print ' Whoops this shouldnt happen! '
Try
Vmname.create ()
Except Exception,e:
Print "Failed to create%s:%s"% (vm_name,e)
Sys.exit (1)
Try
Print "Domain 0:id%d running%s"% (Vmname.id (), Vmname.name ())
Except Exception,e:
Print E
Try
Conn.close ()
Except
Print "Faild to close" connection!
Sys.exit (1)
Print "done!"
print "=" *100
def create_vm_xml_file (src_xml_file,vm_name,dst_img_file):
Config = et.parse (src_xml_file)
Name = Config.find (' name ')
Name.text = Vm_name.strip ()
UUID = Config.find (' uuid ')
Uuid.text = UuidToString (Randomuuid ())
MEM = config.find (' memory ')
MEMKB = str (int (1024) *int (Vm_mem.strip ()))
Mem.text = MEMKB
Currentmemory = Config.find (' currentmemory ')
Currentmemory.text = MEMKB
VCPU = Config.find (' vcpu ')
Vcpu.text = Vm_vcpu.strip ()
Mac = Config.find (' Devices/interface/mac ')
mac.attrib[' address ' = Randommac (type= ' qemu ')
Disk = Config.find (' Devices/disk/source ')
disk.attrib[' file ']=dst_img_file
Vm_xml_name=vm_name.strip () + '. Xml '
Vm_xml_file=os.path.join (Vm_xml_path,vm_xml_name)
If File_exists (vm_xml_file):
print ' File%s exists, abort '% vm_xml_file
Sys.exit (1)
Config.write (Vm_xml_file)
Print "Created VM config file%s"% Vm_xml_file
#print "Use disk image%s, must create it from the template disk:%s"% (Disk_image, disk_old)
Print "done!"
#Function 2 Start VM
Print "Start VM"
START_VM (Vm_xml_file,vm_name)
def delete_file (file_name):
If File_exists (file_name):
Os.unlink (file_name)
def DELETE_VM (vm_name):
Vmimg=vm_name+ ". IMG"
vmxml=vm_name+ ". xml"
Img_file=os.path.join (VM_IMG_PATH,VMIMG)
Xml_file=os.path.join (Vm_xml_path,vmxml)
Try
conn = Libvirt.open (URI)
Except Exception,e:
print ' Faild to open connection to the hypervisor '
Sys.exit (1)
Try
Server=conn.lookupbyname (Vm_name)
Except Exception,e:
Print E
Sys.exit (1)
If Server.isactive ():
Print "VM%s would be shutdown!"%vm_name
Try
#server. Shutdown () #VM need install Acpid
Server.destroy ()
Except Exception,e:
Print E
Sys.exit (1)
Print "VM%s would be delete!"%vm_name
Try
Server.undefine ()
Except Exception,e:
Print E
Sys.exit (1)
Delete_file (Img_file)
Delete_file (Xml_file)
Try
Conn.close ()
Except
Print "Faild to close" connection!
Sys.exit (1)
Else
Print "VM%s would be delete!"%vm_name
Try
Server.undefine ()
Except Exception,e:
Print E
Sys.exit (1)
Delete_file (Img_file)
Delete_file (Xml_file)
print "Done"
print "=" *100
#Open config file
Fh=open (Vm_file)
Vm_config=fh.readlines ()
Fh.close ()
For line in Vm_config:
Passline=re.compile ("#.*")
If Re.search (passline,line)!=none:
Continue
(ACTION,VM_NAME,SRC_FILE,XML_FILE,VM_MEM,VM_VCPU) =line.strip (). Split (",")
If action== ' Add ':
Src_img_file=os.path.join (Template_img_path,src_file)
Dst_img_file=os.path.join (Vm_img_path,vm_name.strip () + ". IMG")
Src_xml_file=os.path.join (Template_xml_path,xml_file)
If not (File_exists (src_img_file) and file_exists (Src_xml_file)):
print ' File%s or%s not exists,abort! '% (src_img_file,src_xml_file)
Sys.exit (1)
#Function1.1 Copy VM img File
Print "Copy Template VM image File"
Copy_vm_img_file (Src_img_file,dst_img_file)
#Function1.2 Create VM XML file
Print "Create VM Xml file"
Create_vm_xml_file (Src_xml_file,vm_name,dst_img_file)
elif action== "Delete":
#Function3 Delete VM
Print "Delete VM"
DELETE_VM (Vm_name)

Most of the code in the script above is from the bad boy's Python script, and I made a major two-point change based on it:

1, using Celementtree to replace the ElementTree in the original code, this is more efficient than the latter, and included in the original Python standard library, in the current popular Linux distribution source with the Python also support.

2, added the configuration file parameters on the memory and VCPU configuration options. However, there is a little bug written here, that is, there is no prompt information when the following arguments do not exist, and no default parameters or exception handling are set.

Second, the directory structure and use
The directory structure of the specific script is as follows:

The code is as follows Copy Code
[Root@localhost/]# Tree/template
/template
├──conf
│├──newvm.ini
│├──newvm.ini.bak
│└──vm.ini
├──img
│└──template.qcow2
├──template1.py
├──template2.py
└──xml
├──template_qcow2.xml
└──template.xml

Among them, template1.py is the original of the bad boy is no longer posted here, template2.py is my revised version, the code has been posted on the top. An img image file stored in an IMG directory that stores an XML file that corresponds to an IMG. Python scripts are added or deleted in batches by reading the INI file, comparing the new and old two versions of the configuration file:

  code is as follows copy code
[root@loca Lhost conf]# cat Newvm.ini
#Action, vm_name,template_img_file,template_xml_file,vm_mem,vm_vcpu
delete,test03 , template.qcow2,template_qcow2.xml,0,0
[root@localhost conf]# cat Vm.ini
#Action, Vm_name,template_img_file, Template_xml_file
Add,test02,template.qcow2,template_qcow2.xml
[root@localhost conf]# cat Newvm_add.ini
#Action, Vm_name,template_img_file,template_xml_file,vm_mem,vm_vcpu
Add,test03,template.qcow2,template_ qcow2.xml,2048,2
add,test04,template.qcow2,template_qcow2.xml,512,1

Delete virtual machine due to the use of mem and vcpu value, so you can directly supplement 0, if not to participate in the words, will be an error. Adding or deleting multiple virtual machines, you can write multiple lines.

Iii. about IP, host name, GUID, etc.
The script here is similar to the cold migration, and there are some things need to be done, such as IP address, host name, GUID many values and the same as the original host, in some scenarios the same values will have some problems. There are also two ways to deal with these problems, one is through the Libguestfs-tools tool, directly in the above script enhancements, after the replication of IMG, directly modify the contents of the IMG file, It also provides a sample page for the following Libguestfs-tools official Python operations.

However, with the Libguestfs-tools tool, the Windows operating system may have some trouble, such as modifying the IP address, change the GUID through the LIBGUESTFS implementation will be cumbersome. So here you can choose a second scenario that uses a script or batch to implement the guest host start, which, of course, can be manual or automatic (in the boot option, and then delete itself after the call completes). This late-thinking thing on the web also went to a similar functional code cloning VMs with KVM.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.