[PATCH] convert vmware machines to virt-image xml format

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



These patches provide the virt-unpack command which converts vmware format machines into virt-image xml format hvm/paravirt runnable instances. Next revision will contain libvirt format as well. As also with the virt-pack command all required vmware/xen/hvm kernel modules must be in place prior to conversion to boot machine.
diff -Naur virtinst--devel.orig/virt-unpack virtinst--devel/virt-unpack
--- virtinst--devel.orig/virt-unpack	1969-12-31 19:00:00.000000000 -0500
+++ virtinst--devel/virt-unpack	2008-06-24 14:37:54.000000000 -0400
@@ -0,0 +1,251 @@
+#!/usr/bin/python 
+#
+# Convert a VMware(tm) virtual machine into an XML image description
+#
+# Copyright 2008  Red Hat, Inc.
+# Joey Boggs <jboggs@xxxxxxxxxx>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+# MA 02110-1301 USA.
+
+import sys
+from string import ascii_letters
+import virtinst.cli as cli
+import os
+import random
+import pdb
+import shutil
+import logging
+from optparse import OptionParser, OptionValueError
+
+def parse_args():
+    parser = OptionParser()
+    parser.set_usage("%prog [options] image.vmx")
+    parser.add_option("-a", "--arch", type="string", dest="arch",
+                      help=("Machine Architecture Type (i686/x86_64/ppc)"))
+    parser.add_option("-t", "--type", type="string", dest="type",
+                      help=("Output virtualization type (hvm, paravirt"))
+    parser.add_option("-d", "--debug", action="store_true", dest="debug",
+                      help=("Print debugging information"))
+    parser.add_option("-o", "--outputdir", type="string", dest="outputdir",
+                      help=("Output directory in which files will be created"))
+    (options,args) = parser.parse_args()
+    
+    if len(args) < 1:
+         parser.error(("You need to provide an image XML descriptor"))
+    options.file  = args[0]
+    
+    if (options.arch is None) or (options.type is None):
+        logging.error("\nYou need to provide all input options\n")
+        logging.error("\n Architecture: " + str(options.arch) + "\n Output Virt Type: " + str(options.type))
+        sys.exit(1)
+    return options
+
+
+# begin xml template creation
+def create_xml_template(disks_list,record,options):   
+
+    pv_disk_list = []
+    fv_disk_list = []
+    storage_disk_list = []
+
+    name = record["displayName"]
+    memory =  record["memsize"]
+    memory = int(memory) * 1024
+
+# can't guarantee annotation or vcpus are set in vmware config, requires evaluation
+    if record.has_key("annotation"):
+       annotation = record["annotation"]
+    else:
+        annotation = ""
+
+    if record.has_key("numvcpus"):
+        vcpus = record["numvcpus"]
+    else:  
+        vcpus = "1"
+   
+# create disk filename lists for xml template
+	for (number, file) in enumerate(disks_list):
+            file = str(file.replace(".vmdk","")).strip()
+            pv_disk_list.append("""<drive disk="%s.img" target="xvd%s"/>""" % \
+                                   (file, ascii_letters[number % 26]))
+            fv_disk_list.append("""<drive disk="%s.img" target="hd%s"/>""" % \
+                                   (file, ascii_letters[number % 26]))
+            storage_disk_list.append("""<disk file="%s.img" use="system" format="raw"/>""" % (file))
+
+# determine virtualization type for image.boot section
+    if options.type == "paravirt":
+        virt_boot_template = """<boot type="xen">
+          <guest>
+            <arch>%(vm_arch)s</arch>
+            <features>
+              <pae/>
+            </features>
+          </guest>
+          <os>
+            <loader>pygrub</loader>
+          </os>
+         %(vm_pv_disks)s
+         </boot>"""
+    elif options.type == "fullvirt":
+
+        virt_boot_template = """<boot type="hvm">
+          <guest>
+            <arch>%(vm_arch)s</arch>
+          </guest>
+          <os>
+            <loader dev="hd"/>
+          </os>
+          %(vm_fv_disks)s
+        </boot>"""
+    else:
+        print "Invalid virtualization type specified"
+        sys.exit(1)
+
+
+# xml replacements dictionaries
+    virt_boot_xml_dict = {
+        "vm_pv_disks" : "".join(pv_disk_list),
+        "vm_fv_disks" : "".join(fv_disk_list),
+        "vm_arch" : options.arch,
+         }
+
+    virt_boot_template = virt_boot_template % virt_boot_xml_dict
+
+    virt_image_xml_dict = {
+        "virt_boot_template" : virt_boot_template,
+        "vm_displayName": name.replace(" ","_"),
+        "vm_annotation" : annotation,
+        "vm_vcpus" : vcpus,
+        "vm_mem"  : memory,
+        "vm_storage" : "".join(storage_disk_list),
+         }
+    
+    virt_image_xml_template = """<image>
+ <name>%(vm_displayName)s</name>
+  <label>%(vm_displayName)s</label>
+    <description>
+        %(vm_annotation)s
+    </description>
+      <domain>
+       %(virt_boot_template)s
+        <devices>
+         <vcpu>%(vm_vcpus)s</vcpu>
+         <memory>%(vm_mem)s</memory>
+          <interface/>
+          <graphics/>
+        </devices>
+      </domain>
+  <storage>
+  %(vm_storage)s
+  </storage>
+</image>"""
+    
+    virt_image_xml_template = virt_image_xml_template % virt_image_xml_dict
+
+# output directory, default is ./$name unless specified otherwise
+    if options.outputdir is None:
+        try:
+            os.mkdir(name.replace(" ","-"))
+        except OSError,e:
+            if e.errno == 17:
+                logging.error("Could not create directory %s or directory already exists", name.replace(" ","-"))
+                sys.exit(1)
+    else:
+        try:
+            os.mkdir(options.outputdir)
+        except OSError,e:
+            if e.errno == 17:
+                logging.error("Could not create directory %s or directory already exists", options.outputdir)
+                sys.exit(1)
+
+    name = name.replace(" ","-")
+
+    if options.outputdir is None:
+        virt_image_xml_config_file = open(name + "/" + name + ".virtimage.xml","w")
+    else:
+        virt_image_xml_config_file = open(options.outputdir + "/" + name + ".virtimage.xml","w")
+   
+    virt_image_xml_config_file.writelines(virt_image_xml_template)
+    virt_image_xml_config_file.close()
+    return name
+
+# parse input vmware configuration
+def parse_vmware_config(options):
+    if not os.access(options.file,os.R_OK):
+        raise ValueError, "Could not read file: %s" % options.file
+    input = open(options.file,"r")
+    contents = input.readlines()
+    input.close()
+    record = {}
+    vm_config = []
+    disks_list = []
+
+    for line in contents:
+        if not line.strip() or line.startswith("#"): # strip comments/blank lines out
+            continue
+        else:
+            vm_config.append(line)
+    
+    for line in vm_config:
+        logging.debug(line)
+        beforeEq, afterEq = line.split("=", 1)
+        key = beforeEq.replace(" ","")
+        value = afterEq.replace('"',"")
+        record[key] = value.strip()
+        if value.endswith("vmdk\n"): # separate disks from config
+            disks_list.append(value)
+    return vm_config,record,disks_list,options
+
+
+def convert_disks(disks_list,name,options):
+    for disk in disks_list:
+        file = disk.replace(".vmdk","")
+        if options.outputdir is None:
+            convert_cmd="qemu-img convert %s -O raw %s/%s.img" % (disk.strip(),name.replace(" ","-"),file.strip())
+        else:
+            convert_cmd="qemu-img convert %s -O raw %s/%s.img" % (disk.strip(),options.outputdir,file.strip())
+        logging.debug("Converting " + disk.strip())
+        print "\nConverting %s to %s/%s.img" % (disk.strip(),options.outputdir,file.strip())
+        os.system(convert_cmd)
+        
+
+
+def main():
+    options = parse_args()
+    cli.setupLogging("virt-unpack", options.debug)
+    
+    vm_config = parse_vmware_config(options)
+    config, record, disks_list, options = vm_config
+    name = create_xml_template(disks_list,record,options)
+    convert_disks(disks_list,name,options)
+
+    if options.outputdir is None: 
+        print "\n\nConversion completed and placed in: ./%s" % name
+    else:
+        print "\n\nConversion completed and placed in: %s" % options.outputdir
+
+    
+if __name__ == "__main__":
+    try:
+        main()
+    except SystemExit, e:
+        sys.exit(e.code)
+    except KeyboardInterrupt, e:
+        print >> sys.stderr, _("Aborted at user request")
+    except Exception, e:
+        logging.exception(e)
+        sys.exit(1)
+
diff -Naur virtinst--devel.orig/man/en/virt-unpack.pod virtinst--devel/man/en/virt-unpack.pod
--- virtinst--devel.orig/man/en/virt-unpack.pod	1969-12-31 19:00:00.000000000 -0500
+++ virtinst--devel/man/en/virt-unpack.pod	2008-06-24 14:59:27.000000000 -0400
@@ -0,0 +1,84 @@
+=pod
+
+=head1 NAME
+
+virt-unpack - convert virtual machines from VMware(tm) format into an xml image descriptor
+
+=head1 SYNOPSIS
+
+B<virt-unpack> [OPTION]... IMAGE.VMX
+
+=head1 DESCRIPTION
+
+B<virt-unpack> is a command line tool for converting virtual machines from an
+VMware(tm) format machine into an XML image descriptor C<IMAGE.XML> (L<virt-image(5)>). 
+The basic configuration of the virtual machine are taken from the VMware configuration file (e.g., 
+disk image files, memory, name, vcpus) and a new XML image descriptor file is created using
+these values. The conversion process requires that all necessary kernel modules and configuration 
+to boot using Xen or KVM are completed prior to running this tool. 
+
+
+=head1 OPTIONS
+
+Any of the options can be omitted, in which case B<virt-unpack> will use defaults when required.
+
+=over 4
+
+=item -h, --help
+
+Show the help message and exit
+
+=item -a ARCH, --arch=ARCH
+
+Architecture of the virtual machine (i686/x86_64,ppc)
+
+=item  -t TYPE, --type=TYPE
+
+Virtualization type (fullvirt / paravirt)
+
+=item  -o OUTPUTDIR, --outputdir=NAME  
+
+Directory in which files will be placed
+
+=item -d, --debug
+
+Print debugging information
+
+=back
+
+=head1 EXAMPLES
+
+Convert a guest from C<image.vmx>:
+
+  # virt-unpack image.vmx --arch=i686 --outputtype=fullvirt
+
+Convert a guest and output the created file to /tmp
+
+  # virt-unpack image.vmx --arch=x86_64 --outputdir /tmp
+
+=head1 AUTHOR
+
+Written by Joey Boggs
+
+See the AUTHORS file in the source distribution for the complete list of credits.
+
+=head1 BUGS
+
+Report bugs to the mailing list C<http://www.redhat.com/mailman/listinfo/et-mgmt-tools>
+or directly to BugZilla C<http://bugzilla.redhat.com/bugzilla/> against the
+C<Fedora> product, and the C<python-virtinst> component.
+
+=head1 COPYRIGHT
+
+Copyright (C) 2006-2008 Red Hat, Inc, and various contributors. 
+This is free software. You may redistribute copies of it under the terms of the GNU General 
+Public License C<http://www.gnu.org/licenses/gpl.html>. There is NO WARRANTY, to the extent 
+permitted by law.
+
+=head1 SEE ALSO
+
+L<virt-pack(1)>, L<virt-image(5)>, the project website
+C<http://virt-manager.org>
+
+=cut
+
_______________________________________________
et-mgmt-tools mailing list
et-mgmt-tools@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/et-mgmt-tools

[Index of Archives]     [Fedora Users]     [Fedora Legacy List]     [Fedora Maintainers]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [KDE Users]     [Fedora Tools]

  Powered by Linux