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

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

 



Updated version based on comments. Cole, check the record validation section to see if that's fine. I just integrated it with the 2 checks that were already in place rather than creating another function.


Cole Robinson wrote:
Joey Boggs wrote:
I integrated the common cli options and all the other modifications, but wasn't sure the best way to approach the para/full virt check removal from the comments

"If you use the above --paravirt/--hvm option change, you won't need
this check." Both before and after code snips below.

I changed the if/else to evaluate the options for True on either para/full, if there's something else you'd want to see please let me know


-------------------------------------------------------------------------------
    parser.add_option("-v", "--hvm", action="store_true", dest="fullvirt",
help=("This guest should be a fully virtualized guest")) parser.add_option("-p", "--paravirt", action="store_true", dest="paravirt",
                      help=("This guest should be a paravirtualized guest"))




    if options.paravirt is True:
        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.fullvirt is True:

        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)

Sorry, I wasn't very clear. The unnecessary check I was talking about
was the last sanity check, the "Invalid virtualization type". Since this
is basically a boolean option (hvm or not), i'd do something like

if options.paravirt:
  hvm = False
else:
  hvm = True

In main() and pass hvm explictly to the above function.

- Cole

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-27 13:59:47.000000000 -0400
@@ -0,0 +1,245 @@
+#!/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"))
+    parser.add_option("-v", "--hvm", action="store_true", dest="fullvirt",
+                      help=("This guest should be a fully virtualized guest"))
+    parser.add_option("-p", "--paravirt", action="store_true", dest="paravirt",
+                      help=("This guest should be a paravirtualized guest"))
+
+
+    (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):
+        parser.error(("Missing option value \n\nArchitecture: " + str(options.arch)))
+    return options
+
+# Begin creation of xml template from parsed vmx config file
+def vmx_to_image_xml(disks_list,record,options,hvm):   
+    pv_disk_list = []
+    fv_disk_list = []
+    storage_disk_list = []
+
+    # validate required values for conversion are in the input vmx file
+    if record.has_key("displayName"):
+        name = record["displayName"]
+    else:
+        logging.error("displayName key not parsed from %s" % options.file)
+        sys.exit(1)
+
+    if record.has_key("memsize"):
+        memory = int(record["memsize"]) * 1024
+    else:
+        logging.error("memsize key not parsed from %s" % options.file)
+        sys.exit(1)
+
+    if record.has_key("annotation"):
+       annotation = record["annotation"]
+    else:
+        logging.error("annotation key not parsed from %s, creating blank comment" % options.file)
+        annotation = ""
+     
+    if record.has_key("numvcpus"):
+        vcpus = record["numvcpus"]
+    else:  
+        logging.error("numvcpus key not parsed from %s, defaulting to 1 virtual cpu" % options.file)
+        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 hvm is False:
+        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 hvm is True:
+        virt_boot_template = """<boot type="hvm">
+          <guest>
+            <arch>%(vm_arch)s</arch>
+          </guest>
+          <os>
+            <loader dev="hd"/>
+          </os>
+          %(vm_fv_disks)s
+        </boot>"""
+
+
+# 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>"""
+    
+    virtimage_xml_template = virt_image_xml_template % virt_image_xml_dict
+    return virtimage_xml_template
+
+# 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 = []
+
+# strip out comment and blank lines for easy splitting of values
+    for line in contents:
+        if not line.strip() or line.startswith("#"):
+            continue
+        else:
+            vm_config.append(line)
+    
+    for line in vm_config:
+        beforeEq, afterEq = line.split("=", 1)
+        key = beforeEq.replace(" ","")
+        value = afterEq.replace('"',"")
+        record[key] = value.strip()
+        logging.debug("Key: %s      Value: %s" % (key,value))
+        if value.endswith("vmdk\n"): # separate disks from config
+            disks_list.append(value)
+    return record,disks_list
+
+
+def convert_disks(disks_list,dirname):
+    for disk in disks_list:
+        file = disk.replace(".vmdk","").strip()
+        convert_cmd="qemu-img convert %s -O raw %s/%s.img" % (disk.strip(),dirname,file)
+        logging.debug("Converting %s" % disk.strip())
+        print "\nConverting %s to %s/%s.img" % (disk.strip(),dirname,file)
+        os.system(convert_cmd)
+
+
+def main():
+    options = parse_args()
+    cli.setupLogging("virt-unpack", options.debug)
+    vm_config = parse_vmware_config(options)
+    record, disks_list = vm_config
+
+    if options.paravirt:
+      hvm = False
+    else:
+      hvm = True
+    virtimage_xml = vmx_to_image_xml(disks_list,record,options,hvm)
+
+    name = record["displayName"].replace(" ","-")
+    dirname = options.outputdir
+    if not dirname:
+        dirname = name
+    try:
+         logging.debug ("Creating directory %s" % dirname)
+         os.mkdir(dirname)
+    except OSError,e:
+        logging.error("Could not create directory %s: %s" % (dirname, str(e)))
+        sys.exit(1)
+
+    # configuration completed, ready to write config file and convert disks
+    virtimage_xml_file = open(dirname + "/" + name + ".virtimage.xml","w")
+    virtimage_xml_file.writelines(virtimage_xml)
+    virtimage_xml_file.close()
+    convert_disks(disks_list,dirname)
+
+    print "\n\nConversion completed and placed in: %s" % dirname
+
+    
+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/virt-unpack.pod virtinst--devel/virt-unpack.pod
--- virtinst--devel.orig/virt-unpack.pod	1969-12-31 19:00:00.000000000 -0500
+++ virtinst--devel/virt-unpack.pod	2008-06-27 14:07:52.000000000 -0400
@@ -0,0 +1,88 @@
+=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  -v, --hvm      Create  a fully virtualized guest image
+
+Convert machine to a hvm/qemu based image (this is the default if paravirt is not specified)
+
+=item  -p, --paravirt      Create  a paravirtualized guest image
+
+Convert machine to a paravirt xen based image
+
+=item  -o OUTPUTDIR, --outputdir=NAME  
+
+Directory in which files will be placed
+
+=item -d, --debug
+
+Print debugging information
+
+=back
+
+=head1 EXAMPLES
+
+Convert a paravirt guest from C<image.vmx>:
+
+  # virt-unpack image.vmx --arch=i686 --paravirt
+
+Convert a hvm guest and output the created file to /tmp
+
+  # virt-unpack image.vmx --arch=x86_64 --hvm --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