Explicitly pass params to deactivate_master_ip
[ganeti-local] / lib / ovf.py
index 36e3e2d..ef87ae3 100644 (file)
@@ -29,6 +29,7 @@
 # E1101 makes no sense - pylint assumes that ElementTree object is a tuple
 
 
+import ConfigParser
 import errno
 import logging
 import os
@@ -37,12 +38,18 @@ import re
 import shutil
 import tarfile
 import tempfile
+import xml.dom.minidom
 import xml.parsers.expat
 try:
   import xml.etree.ElementTree as ET
 except ImportError:
   import elementtree.ElementTree as ET
 
+try:
+  ParseError = ET.ParseError # pylint: disable=E1103
+except AttributeError:
+  ParseError = None
+
 from ganeti import constants
 from ganeti import errors
 from ganeti import utils
@@ -53,6 +60,9 @@ GANETI_SCHEMA = "http://ganeti"
 OVF_SCHEMA = "http://schemas.dmtf.org/ovf/envelope/1"
 RASD_SCHEMA = ("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/"
                "CIM_ResourceAllocationSettingData")
+VSSD_SCHEMA = ("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/"
+               "CIM_VirtualSystemSettingData")
+XML_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance"
 
 # File extensions in OVF package
 OVA_EXT = ".ova"
@@ -67,10 +77,83 @@ FILE_EXTENSIONS = [
 ]
 
 COMPRESSION_TYPE = "gzip"
+NO_COMPRESSION = [None, "identity"]
 COMPRESS = "compression"
 DECOMPRESS = "decompression"
 ALLOWED_ACTIONS = [COMPRESS, DECOMPRESS]
 
+VMDK = "vmdk"
+RAW = "raw"
+COW = "cow"
+ALLOWED_FORMATS = [RAW, COW, VMDK]
+
+# ResourceType values
+RASD_TYPE = {
+  "vcpus": "3",
+  "memory": "4",
+  "scsi-controller": "6",
+  "ethernet-adapter": "10",
+  "disk": "17",
+}
+
+SCSI_SUBTYPE = "lsilogic"
+VS_TYPE = {
+  "ganeti": "ganeti-ovf",
+  "external": "vmx-04",
+}
+
+# AllocationUnits values and conversion
+ALLOCATION_UNITS = {
+  'b': ["bytes", "b"],
+  'kb': ["kilobytes", "kb", "byte * 2^10", "kibibytes", "kib"],
+  'mb': ["megabytes", "mb", "byte * 2^20", "mebibytes", "mib"],
+  'gb': ["gigabytes", "gb", "byte * 2^30", "gibibytes", "gib"],
+}
+CONVERT_UNITS_TO_MB = {
+  'b': lambda x: x / (1024 * 1024),
+  'kb': lambda x: x / 1024,
+  'mb': lambda x: x,
+  'gb': lambda x: x * 1024,
+}
+
+# Names of the config fields
+NAME = "name"
+OS = "os"
+HYPERV = "hypervisor"
+VCPUS = "vcpus"
+MEMORY = "memory"
+AUTO_BALANCE = "auto_balance"
+DISK_TEMPLATE = "disk_template"
+TAGS = "tags"
+VERSION = "version"
+
+# Instance IDs of System and SCSI controller
+INSTANCE_ID = {
+  "system": 0,
+  "vcpus": 1,
+  "memory": 2,
+  "scsi": 3,
+}
+
+# Disk format descriptions
+DISK_FORMAT = {
+  RAW: "http://en.wikipedia.org/wiki/Byte",
+  VMDK: "http://www.vmware.com/interfaces/specifications/vmdk.html"
+          "#monolithicSparse",
+  COW: "http://www.gnome.org/~markmc/qcow-image-format.html",
+}
+
+
+def CheckQemuImg():
+  """ Make sure that qemu-img is present before performing operations.
+
+  @raise errors.OpPrereqError: when qemu-img was not found in the system
+
+  """
+  if not constants.QEMUIMG_PATH:
+    raise errors.OpPrereqError("qemu-img not found at build time, unable"
+                               " to continue")
+
 
 def LinkFile(old_path, prefix=None, suffix=None, directory=None):
   """Create link with a given prefix and suffix.
@@ -143,7 +226,7 @@ class OVFReader(object):
     self.tree = ET.ElementTree()
     try:
       self.tree.parse(input_path)
-    except xml.parsers.expat.ExpatError, err:
+    except (ParseError, xml.parsers.expat.ExpatError), err:
       raise errors.OpPrereqError("Error while reading %s file: %s" %
                                  (OVF_EXT, err))
 
@@ -208,6 +291,27 @@ class OVFReader(object):
         return elem
     return None
 
+  def _GetElementMatchingText(self, path, match_text):
+    """Searches for element on a path that matches certain text value.
+
+    Function follows the path from root node to the desired tags using path,
+    then searches for the first one matching the text value.
+
+    @type path: string
+    @param path: path of nodes to visit
+    @type match_text: tuple
+    @param match_text: pair (node, text) for which we search
+    @rtype: ET.ElementTree or None
+    @return: first element matching match_text or None if nothing matches
+
+    """
+    potential_elements = self.tree.findall(path)
+    (node, text) = match_text
+    for elem in potential_elements:
+      if elem.findtext(node) == text:
+        return elem
+    return None
+
   @staticmethod
   def _GetDictParameters(root, schema):
     """Reads text in all children and creates the dictionary from the contents.
@@ -279,6 +383,186 @@ class OVFReader(object):
                      (GANETI_SCHEMA, GANETI_SCHEMA))
     return self.tree.findtext(find_template)
 
+  def GetHypervisorData(self):
+    """Provides hypervisor information - hypervisor name and options.
+
+    @rtype: dict
+    @return: dictionary containing name of the used hypervisor and all the
+      specified options
+
+    """
+    hypervisor_search = ("{%s}GanetiSection/{%s}Hypervisor" %
+                         (GANETI_SCHEMA, GANETI_SCHEMA))
+    hypervisor_data = self.tree.find(hypervisor_search)
+    if not hypervisor_data:
+      return {"hypervisor_name": constants.VALUE_AUTO}
+    results = {
+      "hypervisor_name": hypervisor_data.findtext("{%s}Name" % GANETI_SCHEMA,
+                           default=constants.VALUE_AUTO),
+    }
+    parameters = hypervisor_data.find("{%s}Parameters" % GANETI_SCHEMA)
+    results.update(self._GetDictParameters(parameters, GANETI_SCHEMA))
+    return results
+
+  def GetOSData(self):
+    """ Provides operating system information - os name and options.
+
+    @rtype: dict
+    @return: dictionary containing name and options for the chosen OS
+
+    """
+    results = {}
+    os_search = ("{%s}GanetiSection/{%s}OperatingSystem" %
+                 (GANETI_SCHEMA, GANETI_SCHEMA))
+    os_data = self.tree.find(os_search)
+    if os_data:
+      results["os_name"] = os_data.findtext("{%s}Name" % GANETI_SCHEMA)
+      parameters = os_data.find("{%s}Parameters" % GANETI_SCHEMA)
+      results.update(self._GetDictParameters(parameters, GANETI_SCHEMA))
+    return results
+
+  def GetBackendData(self):
+    """ Provides backend information - vcpus, memory, auto balancing options.
+
+    @rtype: dict
+    @return: dictionary containing options for vcpus, memory and auto balance
+      settings
+
+    """
+    results = {}
+
+    find_vcpus = ("{%s}VirtualSystem/{%s}VirtualHardwareSection/{%s}Item" %
+                   (OVF_SCHEMA, OVF_SCHEMA, OVF_SCHEMA))
+    match_vcpus = ("{%s}ResourceType" % RASD_SCHEMA, RASD_TYPE["vcpus"])
+    vcpus = self._GetElementMatchingText(find_vcpus, match_vcpus)
+    if vcpus:
+      vcpus_count = vcpus.findtext("{%s}VirtualQuantity" % RASD_SCHEMA,
+        default=constants.VALUE_AUTO)
+    else:
+      vcpus_count = constants.VALUE_AUTO
+    results["vcpus"] = str(vcpus_count)
+
+    find_memory = find_vcpus
+    match_memory = ("{%s}ResourceType" % RASD_SCHEMA, RASD_TYPE["memory"])
+    memory = self._GetElementMatchingText(find_memory, match_memory)
+    memory_raw = None
+    if memory:
+      alloc_units = memory.findtext("{%s}AllocationUnits" % RASD_SCHEMA)
+      matching_units = [units for units, variants in
+        ALLOCATION_UNITS.iteritems() if alloc_units.lower() in variants]
+      if matching_units == []:
+        raise errors.OpPrereqError("Unit %s for RAM memory unknown",
+          alloc_units)
+      units = matching_units[0]
+      memory_raw = int(memory.findtext("{%s}VirtualQuantity" % RASD_SCHEMA,
+            default=constants.VALUE_AUTO))
+      memory_count = CONVERT_UNITS_TO_MB[units](memory_raw)
+    else:
+      memory_count = constants.VALUE_AUTO
+    results["memory"] = str(memory_count)
+
+    find_balance = ("{%s}GanetiSection/{%s}AutoBalance" %
+                   (GANETI_SCHEMA, GANETI_SCHEMA))
+    balance = self.tree.findtext(find_balance, default=constants.VALUE_AUTO)
+    results["auto_balance"] = balance
+
+    return results
+
+  def GetTagsData(self):
+    """Provides tags information for instance.
+
+    @rtype: string or None
+    @return: string of comma-separated tags for the instance
+
+    """
+    find_tags = "{%s}GanetiSection/{%s}Tags" % (GANETI_SCHEMA, GANETI_SCHEMA)
+    results = self.tree.findtext(find_tags)
+    if results:
+      return results
+    else:
+      return None
+
+  def GetVersionData(self):
+    """Provides version number read from .ovf file
+
+    @rtype: string
+    @return: string containing the version number
+
+    """
+    find_version = ("{%s}GanetiSection/{%s}Version" %
+                    (GANETI_SCHEMA, GANETI_SCHEMA))
+    return self.tree.findtext(find_version)
+
+  def GetNetworkData(self):
+    """Provides data about the network in the OVF instance.
+
+    The method gathers the data about networks used by OVF instance. It assumes
+    that 'name' tag means something - in essence, if it contains one of the
+    words 'bridged' or 'routed' then that will be the mode of this network in
+    Ganeti. The information about the network can be either in GanetiSection or
+    VirtualHardwareSection.
+
+    @rtype: dict
+    @return: dictionary containing all the network information
+
+    """
+    results = {}
+    networks_search = ("{%s}NetworkSection/{%s}Network" %
+                       (OVF_SCHEMA, OVF_SCHEMA))
+    network_names = self._GetAttributes(networks_search,
+      "{%s}name" % OVF_SCHEMA)
+    required = ["ip", "mac", "link", "mode"]
+    for (counter, network_name) in enumerate(network_names):
+      network_search = ("{%s}VirtualSystem/{%s}VirtualHardwareSection/{%s}Item"
+                        % (OVF_SCHEMA, OVF_SCHEMA, OVF_SCHEMA))
+      ganeti_search = ("{%s}GanetiSection/{%s}Network/{%s}Nic" %
+                       (GANETI_SCHEMA, GANETI_SCHEMA, GANETI_SCHEMA))
+      network_match = ("{%s}Connection" % RASD_SCHEMA, network_name)
+      ganeti_match = ("{%s}name" % OVF_SCHEMA, network_name)
+      network_data = self._GetElementMatchingText(network_search, network_match)
+      network_ganeti_data = self._GetElementMatchingAttr(ganeti_search,
+        ganeti_match)
+
+      ganeti_data = {}
+      if network_ganeti_data:
+        ganeti_data["mode"] = network_ganeti_data.findtext("{%s}Mode" %
+                                                           GANETI_SCHEMA)
+        ganeti_data["mac"] = network_ganeti_data.findtext("{%s}MACAddress" %
+                                                          GANETI_SCHEMA)
+        ganeti_data["ip"] = network_ganeti_data.findtext("{%s}IPAddress" %
+                                                         GANETI_SCHEMA)
+        ganeti_data["link"] = network_ganeti_data.findtext("{%s}Link" %
+                                                           GANETI_SCHEMA)
+      mac_data = None
+      if network_data:
+        mac_data = network_data.findtext("{%s}Address" % RASD_SCHEMA)
+
+      network_name = network_name.lower()
+
+      # First, some not Ganeti-specific information is collected
+      if constants.NIC_MODE_BRIDGED in network_name:
+        results["nic%s_mode" % counter] = "bridged"
+      elif constants.NIC_MODE_ROUTED in network_name:
+        results["nic%s_mode" % counter] = "routed"
+      results["nic%s_mac" % counter] = mac_data
+
+      # GanetiSection data overrides 'manually' collected data
+      for name, value in ganeti_data.iteritems():
+        results["nic%s_%s" % (counter, name)] = value
+
+      # Bridged network has no IP - unless specifically stated otherwise
+      if (results.get("nic%s_mode" % counter) == "bridged" and
+          not results.get("nic%s_ip" % counter)):
+        results["nic%s_ip" % counter] = constants.VALUE_NONE
+
+      for option in required:
+        if not results.get("nic%s_%s" % (counter, option)):
+          results["nic%s_%s" % (counter, option)] = constants.VALUE_AUTO
+
+    if network_names:
+      results["nic_count"] = str(len(network_names))
+    return results
+
   def GetDisksNames(self):
     """Provides list of file names for the disks used by the instance.
 
@@ -302,6 +586,249 @@ class OVFReader(object):
     return results
 
 
+def SubElementText(parent, tag, text, attrib={}, **extra):
+# pylint: disable=W0102
+  """This is just a wrapper on ET.SubElement that always has text content.
+
+  """
+  if text is None:
+    return None
+  elem = ET.SubElement(parent, tag, attrib=attrib, **extra)
+  elem.text = str(text)
+  return elem
+
+
+class OVFWriter(object):
+  """Writer class for OVF files.
+
+  @type tree: ET.ElementTree
+  @ivar tree: XML tree that we are constructing
+  @type virtual_system_type: string
+  @ivar virtual_system_type: value of vssd:VirtualSystemType, for external usage
+    in VMWare this requires to be vmx
+  @type hardware_list: list
+  @ivar hardware_list: list of items prepared for VirtualHardwareSection
+  @type next_instance_id: int
+  @ivar next_instance_id: next instance id to be used when creating elements on
+    hardware_list
+
+  """
+  def __init__(self, has_gnt_section):
+    """Initialize the writer - set the top element.
+
+    @type has_gnt_section: bool
+    @param has_gnt_section: if the Ganeti schema should be added - i.e. this
+      means that Ganeti section will be present
+
+    """
+    env_attribs = {
+      "xmlns:xsi": XML_SCHEMA,
+      "xmlns:vssd": VSSD_SCHEMA,
+      "xmlns:rasd": RASD_SCHEMA,
+      "xmlns:ovf": OVF_SCHEMA,
+      "xmlns": OVF_SCHEMA,
+      "xml:lang": "en-US",
+    }
+    if has_gnt_section:
+      env_attribs["xmlns:gnt"] = GANETI_SCHEMA
+      self.virtual_system_type = VS_TYPE["ganeti"]
+    else:
+      self.virtual_system_type = VS_TYPE["external"]
+    self.tree = ET.Element("Envelope", attrib=env_attribs)
+    self.hardware_list = []
+    # INSTANCE_ID contains statically assigned IDs, starting from 0
+    self.next_instance_id = len(INSTANCE_ID) # FIXME: hackish
+
+  def SaveDisksData(self, disks):
+    """Convert disk information to certain OVF sections.
+
+    @type disks: list
+    @param disks: list of dictionaries of disk options from config.ini
+
+    """
+    references = ET.SubElement(self.tree, "References")
+    disk_section = ET.SubElement(self.tree, "DiskSection")
+    SubElementText(disk_section, "Info", "Virtual disk information")
+    for counter, disk in enumerate(disks):
+      file_id = "file%s" % counter
+      disk_id = "disk%s" % counter
+      file_attribs = {
+        "ovf:href": disk["path"],
+        "ovf:size": str(disk["real-size"]),
+        "ovf:id": file_id,
+      }
+      disk_attribs = {
+        "ovf:capacity": str(disk["virt-size"]),
+        "ovf:diskId": disk_id,
+        "ovf:fileRef": file_id,
+        "ovf:format": DISK_FORMAT.get(disk["format"], disk["format"]),
+      }
+      if "compression" in disk:
+        file_attribs["ovf:compression"] = disk["compression"]
+      ET.SubElement(references, "File", attrib=file_attribs)
+      ET.SubElement(disk_section, "Disk", attrib=disk_attribs)
+
+      # Item in VirtualHardwareSection creation
+      disk_item = ET.Element("Item")
+      SubElementText(disk_item, "rasd:ElementName", disk_id)
+      SubElementText(disk_item, "rasd:HostResource", "ovf:/disk/%s" % disk_id)
+      SubElementText(disk_item, "rasd:InstanceID", self.next_instance_id)
+      SubElementText(disk_item, "rasd:Parent", INSTANCE_ID["scsi"])
+      SubElementText(disk_item, "rasd:ResourceType", RASD_TYPE["disk"])
+      self.hardware_list.append(disk_item)
+      self.next_instance_id += 1
+
+  def SaveNetworksData(self, networks):
+    """Convert network information to NetworkSection.
+
+    @type networks: list
+    @param networks: list of dictionaries of network options form config.ini
+
+    """
+    network_section = ET.SubElement(self.tree, "NetworkSection")
+    SubElementText(network_section, "Info", "List of logical networks")
+    for counter, network in enumerate(networks):
+      network_name = "%s%s" % (network["mode"], counter)
+      network_attrib = {"ovf:name": network_name}
+      ET.SubElement(network_section, "Network", attrib=network_attrib)
+
+      # Item in VirtualHardwareSection creation
+      network_item = ET.Element("Item")
+      SubElementText(network_item, "rasd:Address", network["mac"])
+      SubElementText(network_item, "rasd:Connection", network_name)
+      SubElementText(network_item, "rasd:ElementName", network_name)
+      SubElementText(network_item, "rasd:InstanceID", self.next_instance_id)
+      SubElementText(network_item, "rasd:ResourceType",
+        RASD_TYPE["ethernet-adapter"])
+      self.hardware_list.append(network_item)
+      self.next_instance_id += 1
+
+  @staticmethod
+  def _SaveNameAndParams(root, data):
+    """Save name and parameters information under root using data.
+
+    @type root: ET.Element
+    @param root: root element for the Name and Parameters
+    @type data: dict
+    @param data: data from which we gather the values
+
+    """
+    assert(data.get("name"))
+    name = SubElementText(root, "gnt:Name", data["name"])
+    params = ET.SubElement(root, "gnt:Parameters")
+    for name, value in data.iteritems():
+      if name != "name":
+        SubElementText(params, "gnt:%s" % name, value)
+
+  def SaveGanetiData(self, ganeti, networks):
+    """Convert Ganeti-specific information to GanetiSection.
+
+    @type ganeti: dict
+    @param ganeti: dictionary of Ganeti-specific options from config.ini
+    @type networks: list
+    @param networks: list of dictionaries of network options form config.ini
+
+    """
+    ganeti_section = ET.SubElement(self.tree, "gnt:GanetiSection")
+
+    SubElementText(ganeti_section, "gnt:Version", ganeti.get("version"))
+    SubElementText(ganeti_section, "gnt:DiskTemplate",
+      ganeti.get("disk_template"))
+    SubElementText(ganeti_section, "gnt:AutoBalance",
+      ganeti.get("auto_balance"))
+    SubElementText(ganeti_section, "gnt:Tags", ganeti.get("tags"))
+
+    osys = ET.SubElement(ganeti_section, "gnt:OperatingSystem")
+    self._SaveNameAndParams(osys, ganeti["os"])
+
+    hypervisor = ET.SubElement(ganeti_section, "gnt:Hypervisor")
+    self._SaveNameAndParams(hypervisor, ganeti["hypervisor"])
+
+    network_section = ET.SubElement(ganeti_section, "gnt:Network")
+    for counter, network in enumerate(networks):
+      network_name = "%s%s" % (network["mode"], counter)
+      nic_attrib = {"ovf:name": network_name}
+      nic = ET.SubElement(network_section, "gnt:Nic", attrib=nic_attrib)
+      SubElementText(nic, "gnt:Mode", network["mode"])
+      SubElementText(nic, "gnt:MACAddress", network["mac"])
+      SubElementText(nic, "gnt:IPAddress", network["ip"])
+      SubElementText(nic, "gnt:Link", network["link"])
+
+  def SaveVirtualSystemData(self, name, vcpus, memory):
+    """Convert virtual system information to OVF sections.
+
+    @type name: string
+    @param name: name of the instance
+    @type vcpus: int
+    @param vcpus: number of VCPUs
+    @type memory: int
+    @param memory: RAM memory in MB
+
+    """
+    assert(vcpus > 0)
+    assert(memory > 0)
+    vs_attrib = {"ovf:id": name}
+    virtual_system = ET.SubElement(self.tree, "VirtualSystem", attrib=vs_attrib)
+    SubElementText(virtual_system, "Info", "A virtual machine")
+
+    name_section = ET.SubElement(virtual_system, "Name")
+    name_section.text = name
+    os_attrib = {"ovf:id": "0"}
+    os_section = ET.SubElement(virtual_system, "OperatingSystemSection",
+      attrib=os_attrib)
+    SubElementText(os_section, "Info", "Installed guest operating system")
+    hardware_section = ET.SubElement(virtual_system, "VirtualHardwareSection")
+    SubElementText(hardware_section, "Info", "Virtual hardware requirements")
+
+    # System description
+    system = ET.SubElement(hardware_section, "System")
+    SubElementText(system, "vssd:ElementName", "Virtual Hardware Family")
+    SubElementText(system, "vssd:InstanceID", INSTANCE_ID["system"])
+    SubElementText(system, "vssd:VirtualSystemIdentifier", name)
+    SubElementText(system, "vssd:VirtualSystemType", self.virtual_system_type)
+
+    # Item for vcpus
+    vcpus_item = ET.SubElement(hardware_section, "Item")
+    SubElementText(vcpus_item, "rasd:ElementName",
+      "%s virtual CPU(s)" % vcpus)
+    SubElementText(vcpus_item, "rasd:InstanceID", INSTANCE_ID["vcpus"])
+    SubElementText(vcpus_item, "rasd:ResourceType", RASD_TYPE["vcpus"])
+    SubElementText(vcpus_item, "rasd:VirtualQuantity", vcpus)
+
+    # Item for memory
+    memory_item = ET.SubElement(hardware_section, "Item")
+    SubElementText(memory_item, "rasd:AllocationUnits", "byte * 2^20")
+    SubElementText(memory_item, "rasd:ElementName", "%sMB of memory" % memory)
+    SubElementText(memory_item, "rasd:InstanceID", INSTANCE_ID["memory"])
+    SubElementText(memory_item, "rasd:ResourceType", RASD_TYPE["memory"])
+    SubElementText(memory_item, "rasd:VirtualQuantity", memory)
+
+    # Item for scsi controller
+    scsi_item = ET.SubElement(hardware_section, "Item")
+    SubElementText(scsi_item, "rasd:Address", INSTANCE_ID["system"])
+    SubElementText(scsi_item, "rasd:ElementName", "scsi_controller0")
+    SubElementText(scsi_item, "rasd:InstanceID", INSTANCE_ID["scsi"])
+    SubElementText(scsi_item, "rasd:ResourceSubType", SCSI_SUBTYPE)
+    SubElementText(scsi_item, "rasd:ResourceType", RASD_TYPE["scsi-controller"])
+
+    # Other items - from self.hardware_list
+    for item in self.hardware_list:
+      hardware_section.append(item)
+
+  def PrettyXmlDump(self):
+    """Formatter of the XML file.
+
+    @rtype: string
+    @return: XML tree in the form of nicely-formatted string
+
+    """
+    raw_string = ET.tostring(self.tree)
+    parsed_xml = xml.dom.minidom.parseString(raw_string)
+    xml_string = parsed_xml.toprettyxml(indent="  ")
+    text_re = re.compile(">\n\s+([^<>\s].*?)\n\s+</", re.DOTALL)
+    return text_re.sub(">\g<1></", xml_string)
+
+
 class Converter(object):
   """Converter class for OVF packages.
 
@@ -400,6 +927,7 @@ class Converter(object):
     @raise errors.OpPrereqError: convertion of the disk failed
 
     """
+    CheckQemuImg()
     disk_file = os.path.basename(disk_path)
     (disk_name, disk_extension) = os.path.splitext(disk_file)
     if disk_extension != disk_format:
@@ -410,7 +938,7 @@ class Converter(object):
       prefix=disk_name, dir=self.output_dir)
     self.temp_file_manager.Add(new_disk_path)
     args = [
-      "qemu-img",
+      constants.QEMUIMG_PATH,
       "convert",
       "-O",
       disk_format,
@@ -437,7 +965,8 @@ class Converter(object):
     @raise errors.OpPrereqError: format information cannot be retrieved
 
     """
-    args = ["qemu-img", "info", disk_path]
+    CheckQemuImg()
+    args = [constants.QEMUIMG_PATH, "info", disk_path]
     run_result = utils.RunCmd(args, cwd=os.getcwd())
     if run_result.failed:
       raise errors.OpPrereqError("Gathering info about the disk using qemu-img"
@@ -491,6 +1020,22 @@ class OVFImporter(Converter):
   @type results_template: string
   @ivar results_template: disk template read from .ovf file or command line
     arguments
+  @type results_hypervisor: dict
+  @ivar results_hypervisor: hypervisor information gathered from .ovf file or
+    command line arguments
+  @type results_os: dict
+  @ivar results_os: operating system information gathered from .ovf file or
+    command line arguments
+  @type results_backend: dict
+  @ivar results_backend: backend information gathered from .ovf file or
+    command line arguments
+  @type results_tags: string
+  @ivar results_tags: string containing instance-specific tags
+  @type results_version: string
+  @ivar results_version: version as required by Ganeti import
+  @type results_network: dict
+  @ivar results_network: network information gathered from .ovf file or command
+    line arguments
   @type results_disk: dict
   @ivar results_disk: disk information gathered from .ovf file or command line
     arguments
@@ -612,10 +1157,45 @@ class OVFImporter(Converter):
     if not self.results_template:
       logging.info("Disk template not given")
 
+    self.results_hypervisor = self._GetInfo("hypervisor",
+      self.options.hypervisor, self._ParseHypervisorOptions,
+      self.ovf_reader.GetHypervisorData)
+    assert self.results_hypervisor["hypervisor_name"]
+    if self.results_hypervisor["hypervisor_name"] == constants.VALUE_AUTO:
+      logging.debug("Default hypervisor settings from the cluster will be used")
+
+    self.results_os = self._GetInfo("OS", self.options.os,
+      self._ParseOSOptions, self.ovf_reader.GetOSData)
+    if not self.results_os.get("os_name"):
+      raise errors.OpPrereqError("OS name must be provided")
+
+    self.results_backend = self._GetInfo("backend", self.options.beparams,
+      self._ParseBackendOptions, self.ovf_reader.GetBackendData)
+    assert self.results_backend.get("vcpus")
+    assert self.results_backend.get("memory")
+    assert self.results_backend.get("auto_balance") is not None
+
+    self.results_tags = self._GetInfo("tags", self.options.tags,
+      self._ParseTags, self.ovf_reader.GetTagsData)
+
+    ovf_version = self.ovf_reader.GetVersionData()
+    if ovf_version:
+      self.results_version = ovf_version
+    else:
+      self.results_version = constants.EXPORT_VERSION
+
+    self.results_network = self._GetInfo("network", self.options.nics,
+      self._ParseNicOptions, self.ovf_reader.GetNetworkData,
+      ignore_test=self.options.no_nics)
+
     self.results_disk = self._GetInfo("disk", self.options.disks,
       self._ParseDiskOptions, self._GetDiskInfo,
       ignore_test=self.results_template == constants.DT_DISKLESS)
 
+    if not self.results_disk and not self.results_network:
+      raise errors.OpPrereqError("Either disk specification or network"
+                                 " description must be present")
+
   @staticmethod
   def _GetInfo(name, cmd_arg, cmd_function, nocmd_function,
     ignore_test=False):
@@ -662,6 +1242,84 @@ class OVFImporter(Converter):
     """
     return self.options.disk_template
 
+  def _ParseHypervisorOptions(self):
+    """Parses hypervisor options given in a command line.
+
+    @rtype: dict
+    @return: dictionary containing name of the chosen hypervisor and all the
+      options
+
+    """
+    assert type(self.options.hypervisor) is tuple
+    assert len(self.options.hypervisor) == 2
+    results = {}
+    if self.options.hypervisor[0]:
+      results["hypervisor_name"] = self.options.hypervisor[0]
+    else:
+      results["hypervisor_name"] = constants.VALUE_AUTO
+    results.update(self.options.hypervisor[1])
+    return results
+
+  def _ParseOSOptions(self):
+    """Parses OS options given in command line.
+
+    @rtype: dict
+    @return: dictionary containing name of chosen OS and all its options
+
+    """
+    assert self.options.os
+    results = {}
+    results["os_name"] = self.options.os
+    results.update(self.options.osparams)
+    return results
+
+  def _ParseBackendOptions(self):
+    """Parses backend options given in command line.
+
+    @rtype: dict
+    @return: dictionary containing vcpus, memory and auto-balance options
+
+    """
+    assert self.options.beparams
+    backend = {}
+    backend.update(self.options.beparams)
+    must_contain = ["vcpus", "memory", "auto_balance"]
+    for element in must_contain:
+      if backend.get(element) is None:
+        backend[element] = constants.VALUE_AUTO
+    return backend
+
+  def _ParseTags(self):
+    """Returns tags list given in command line.
+
+    @rtype: string
+    @return: string containing comma-separated tags
+
+    """
+    return self.options.tags
+
+  def _ParseNicOptions(self):
+    """Parses network options given in a command line or as a dictionary.
+
+    @rtype: dict
+    @return: dictionary of network-related options
+
+    """
+    assert self.options.nics
+    results = {}
+    for (nic_id, nic_desc) in self.options.nics:
+      results["nic%s_mode" % nic_id] = \
+        nic_desc.get("mode", constants.VALUE_AUTO)
+      results["nic%s_mac" % nic_id] = nic_desc.get("mac", constants.VALUE_AUTO)
+      results["nic%s_link" % nic_id] = \
+        nic_desc.get("link", constants.VALUE_AUTO)
+      if nic_desc.get("mode") == "bridged":
+        results["nic%s_ip" % nic_id] = constants.VALUE_NONE
+      else:
+        results["nic%s_ip" % nic_id] = constants.VALUE_AUTO
+    results["nic_count"] = str(len(self.options.nics))
+    return results
+
   def _ParseDiskOptions(self):
     """Parses disk options given in a command line.
 
@@ -672,6 +1330,7 @@ class OVFImporter(Converter):
       information or size information is invalid or creation failed
 
     """
+    CheckQemuImg()
     assert self.options.disks
     results = {}
     for (disk_id, disk_desc) in self.options.disks:
@@ -684,7 +1343,7 @@ class OVFImporter(Converter):
                                      (disk_id, disk_desc["size"]))
         new_path = utils.PathJoin(self.output_dir, str(disk_id))
         args = [
-          "qemu-img",
+          constants.QEMUIMG_PATH,
           "create",
           "-f",
           "raw",
@@ -720,7 +1379,7 @@ class OVFImporter(Converter):
                                    " paths or paths outside main OVF directory")
       disk, _ = os.path.splitext(disk_name)
       disk_path = utils.PathJoin(self.input_dir, disk_name)
-      if disk_compression:
+      if disk_compression not in NO_COMPRESSION:
         _, disk_path = self._CompressDisk(disk_path, disk_compression,
           DECOMPRESS)
         disk, _ = os.path.splitext(disk)
@@ -756,9 +1415,25 @@ class OVFImporter(Converter):
     }
 
     results[constants.INISECT_INS].update(self.results_disk)
+    results[constants.INISECT_INS].update(self.results_network)
+    results[constants.INISECT_INS]["hypervisor"] = \
+      self.results_hypervisor["hypervisor_name"]
     results[constants.INISECT_INS]["name"] = self.results_name
     if self.results_template:
       results[constants.INISECT_INS]["disk_template"] = self.results_template
+    if self.results_tags:
+      results[constants.INISECT_INS]["tags"] = self.results_tags
+
+    results[constants.INISECT_BEP].update(self.results_backend)
+
+    results[constants.INISECT_EXP]["os"] = self.results_os["os_name"]
+    results[constants.INISECT_EXP]["version"] = self.results_version
+
+    del self.results_os["os_name"]
+    results[constants.INISECT_OSP].update(self.results_os)
+
+    del self.results_hypervisor["hypervisor_name"]
+    results[constants.INISECT_HYP].update(self.results_hypervisor)
 
     output_file_name = utils.PathJoin(self.output_dir,
       constants.EXPORT_CONF_FILE)
@@ -781,12 +1456,359 @@ class OVFImporter(Converter):
     self.Cleanup()
 
 
+class ConfigParserWithDefaults(ConfigParser.SafeConfigParser):
+  """This is just a wrapper on SafeConfigParser, that uses default values
+
+  """
+  def get(self, section, options, raw=None, vars=None): # pylint: disable=W0622
+    try:
+      result = ConfigParser.SafeConfigParser.get(self, section, options, \
+        raw=raw, vars=vars)
+    except ConfigParser.NoOptionError:
+      result = None
+    return result
+
+  def getint(self, section, options):
+    try:
+      result = ConfigParser.SafeConfigParser.get(self, section, options)
+    except ConfigParser.NoOptionError:
+      result = 0
+    return int(result)
+
+
 class OVFExporter(Converter):
+  """Converter from Ganeti config file to OVF
+
+  @type input_dir: string
+  @ivar input_dir: directory in which the config.ini file resides
+  @type output_dir: string
+  @ivar output_dir: directory to which the results of conversion shall be
+    written
+  @type packed_dir: string
+  @ivar packed_dir: if we want OVA package, this points to the real (i.e. not
+    temp) output directory
+  @type input_path: string
+  @ivar input_path: complete path to the config.ini file
+  @type output_path: string
+  @ivar output_path: complete path to .ovf file
+  @type config_parser: L{ConfigParserWithDefaults}
+  @ivar config_parser: parser for the config.ini file
+  @type reference_files: list
+  @ivar reference_files: files referenced in the ovf file
+  @type results_disk: list
+  @ivar results_disk: list of dictionaries of disk options from config.ini
+  @type results_network: list
+  @ivar results_network: list of dictionaries of network options form config.ini
+  @type results_name: string
+  @ivar results_name: name of the instance
+  @type results_vcpus: string
+  @ivar results_vcpus: number of VCPUs
+  @type results_memory: string
+  @ivar results_memory: RAM memory in MB
+  @type results_ganeti: dict
+  @ivar results_ganeti: dictionary of Ganeti-specific options from config.ini
+
+  """
   def _ReadInputData(self, input_path):
-    pass
+    """Reads the data on which the conversion will take place.
+
+    @type input_path: string
+    @param input_path: absolute path to the config.ini input file
+
+    @raise errors.OpPrereqError: error when reading the config file
+
+    """
+    input_dir = os.path.dirname(input_path)
+    self.input_path = input_path
+    self.input_dir = input_dir
+    if self.options.output_dir:
+      self.output_dir = os.path.abspath(self.options.output_dir)
+    else:
+      self.output_dir = input_dir
+    self.config_parser = ConfigParserWithDefaults()
+    logging.info("Reading configuration from %s file", input_path)
+    try:
+      self.config_parser.read(input_path)
+    except ConfigParser.MissingSectionHeaderError, err:
+      raise errors.OpPrereqError("Error when trying to read %s: %s" %
+                                 (input_path, err))
+    if self.options.ova_package:
+      self.temp_dir = tempfile.mkdtemp()
+      self.packed_dir = self.output_dir
+      self.output_dir = self.temp_dir
+
+    self.ovf_writer = OVFWriter(not self.options.ext_usage)
+
+  def _ParseName(self):
+    """Parses name from command line options or config file.
+
+    @rtype: string
+    @return: name of Ganeti instance
+
+    @raise errors.OpPrereqError: if name of the instance is not provided
+
+    """
+    if self.options.name:
+      name = self.options.name
+    else:
+      name = self.config_parser.get(constants.INISECT_INS, NAME)
+    if name is None:
+      raise errors.OpPrereqError("No instance name found")
+    return name
+
+  def _ParseVCPUs(self):
+    """Parses vcpus number from config file.
+
+    @rtype: int
+    @return: number of virtual CPUs
+
+    @raise errors.OpPrereqError: if number of VCPUs equals 0
+
+    """
+    vcpus = self.config_parser.getint(constants.INISECT_BEP, VCPUS)
+    if vcpus == 0:
+      raise errors.OpPrereqError("No CPU information found")
+    return vcpus
+
+  def _ParseMemory(self):
+    """Parses vcpus number from config file.
+
+    @rtype: int
+    @return: amount of memory in MB
+
+    @raise errors.OpPrereqError: if amount of memory equals 0
+
+    """
+    memory = self.config_parser.getint(constants.INISECT_BEP, MEMORY)
+    if memory == 0:
+      raise errors.OpPrereqError("No memory information found")
+    return memory
+
+  def _ParseGaneti(self):
+    """Parses Ganeti data from config file.
+
+    @rtype: dictionary
+    @return: dictionary of Ganeti-specific options
+
+    """
+    results = {}
+    # hypervisor
+    results["hypervisor"] = {}
+    hyp_name = self.config_parser.get(constants.INISECT_INS, HYPERV)
+    if hyp_name is None:
+      raise errors.OpPrereqError("No hypervisor information found")
+    results["hypervisor"]["name"] = hyp_name
+    pairs = self.config_parser.items(constants.INISECT_HYP)
+    for (name, value) in pairs:
+      results["hypervisor"][name] = value
+    # os
+    results["os"] = {}
+    os_name = self.config_parser.get(constants.INISECT_EXP, OS)
+    if os_name is None:
+      raise errors.OpPrereqError("No operating system information found")
+    results["os"]["name"] = os_name
+    pairs = self.config_parser.items(constants.INISECT_OSP)
+    for (name, value) in pairs:
+      results["os"][name] = value
+    # other
+    others = [
+      (constants.INISECT_INS, DISK_TEMPLATE, "disk_template"),
+      (constants.INISECT_BEP, AUTO_BALANCE, "auto_balance"),
+      (constants.INISECT_INS, TAGS, "tags"),
+      (constants.INISECT_EXP, VERSION, "version"),
+    ]
+    for (section, element, name) in others:
+      results[name] = self.config_parser.get(section, element)
+    return results
+
+  def _ParseNetworks(self):
+    """Parses network data from config file.
+
+    @rtype: list
+    @return: list of dictionaries of network options
+
+    @raise errors.OpPrereqError: then network mode is not recognized
+
+    """
+    results = []
+    counter = 0
+    while True:
+      data_link = \
+        self.config_parser.get(constants.INISECT_INS, "nic%s_link" % counter)
+      if data_link is None:
+        break
+      results.append({
+        "mode": self.config_parser.get(constants.INISECT_INS,
+           "nic%s_mode" % counter),
+        "mac": self.config_parser.get(constants.INISECT_INS,
+           "nic%s_mac" % counter),
+        "ip": self.config_parser.get(constants.INISECT_INS,
+           "nic%s_ip" % counter),
+        "link": data_link,
+      })
+      if results[counter]["mode"] not in constants.NIC_VALID_MODES:
+        raise errors.OpPrereqError("Network mode %s not recognized"
+                                   % results[counter]["mode"])
+      counter += 1
+    return results
+
+  def _GetDiskOptions(self, disk_file, compression):
+    """Convert the disk and gather disk info for .ovf file.
+
+    @type disk_file: string
+    @param disk_file: name of the disk (without the full path)
+    @type compression: bool
+    @param compression: whether the disk should be compressed or not
+
+    @raise errors.OpPrereqError: when disk image does not exist
+
+    """
+    disk_path = utils.PathJoin(self.input_dir, disk_file)
+    results = {}
+    if not os.path.isfile(disk_path):
+      raise errors.OpPrereqError("Disk image does not exist: %s" % disk_path)
+    if os.path.dirname(disk_file):
+      raise errors.OpPrereqError("Path for the disk: %s contains a directory"
+                                 " name" % disk_path)
+    disk_name, _ = os.path.splitext(disk_file)
+    ext, new_disk_path = self._ConvertDisk(self.options.disk_format, disk_path)
+    results["format"] = self.options.disk_format
+    results["virt-size"] = self._GetDiskQemuInfo(new_disk_path,
+      "virtual size: \S+ \((\d+) bytes\)")
+    if compression:
+      ext2, new_disk_path = self._CompressDisk(new_disk_path, "gzip",
+        COMPRESS)
+      disk_name, _ = os.path.splitext(disk_name)
+      results["compression"] = "gzip"
+      ext += ext2
+    final_disk_path = LinkFile(new_disk_path, prefix=disk_name, suffix=ext,
+      directory=self.output_dir)
+    final_disk_name = os.path.basename(final_disk_path)
+    results["real-size"] = os.path.getsize(final_disk_path)
+    results["path"] = final_disk_name
+    self.references_files.append(final_disk_path)
+    return results
+
+  def _ParseDisks(self):
+    """Parses disk data from config file.
+
+    @rtype: list
+    @return: list of dictionaries of disk options
+
+    """
+    results = []
+    counter = 0
+    while True:
+      disk_file = \
+        self.config_parser.get(constants.INISECT_INS, "disk%s_dump" % counter)
+      if disk_file is None:
+        break
+      results.append(self._GetDiskOptions(disk_file, self.options.compression))
+      counter += 1
+    return results
 
   def Parse(self):
-    pass
+    """Parses the data and creates a structure containing all required info.
+
+    """
+    try:
+      utils.Makedirs(self.output_dir)
+    except OSError, err:
+      raise errors.OpPrereqError("Failed to create directory %s: %s" %
+                                 (self.output_dir, err))
+
+    self.references_files = []
+    self.results_name = self._ParseName()
+    self.results_vcpus = self._ParseVCPUs()
+    self.results_memory = self._ParseMemory()
+    if not self.options.ext_usage:
+      self.results_ganeti = self._ParseGaneti()
+    self.results_network = self._ParseNetworks()
+    self.results_disk = self._ParseDisks()
+
+  def _PrepareManifest(self, path):
+    """Creates manifest for all the files in OVF package.
+
+    @type path: string
+    @param path: path to manifesto file
+
+    @raise errors.OpPrereqError: if error occurs when writing file
+
+    """
+    logging.info("Preparing manifest for the OVF package")
+    lines = []
+    files_list = [self.output_path]
+    files_list.extend(self.references_files)
+    logging.warning("Calculating SHA1 checksums, this may take a while")
+    sha1_sums = utils.FingerprintFiles(files_list)
+    for file_path, value in sha1_sums.iteritems():
+      file_name = os.path.basename(file_path)
+      lines.append("SHA1(%s)= %s" % (file_name, value))
+    lines.append("")
+    data = "\n".join(lines)
+    try:
+      utils.WriteFile(path, data=data)
+    except errors.ProgrammerError, err:
+      raise errors.OpPrereqError("Saving the manifest file failed: %s" % err)
+
+  @staticmethod
+  def _PrepareTarFile(tar_path, files_list):
+    """Creates tarfile from the files in OVF package.
+
+    @type tar_path: string
+    @param tar_path: path to the resulting file
+    @type files_list: list
+    @param files_list: list of files in the OVF package
+
+    """
+    logging.info("Preparing tarball for the OVF package")
+    open(tar_path, mode="w").close()
+    ova_package = tarfile.open(name=tar_path, mode="w")
+    for file_path in files_list:
+      file_name = os.path.basename(file_path)
+      ova_package.add(file_path, arcname=file_name)
+    ova_package.close()
 
   def Save(self):
-    pass
+    """Saves the gathered configuration in an apropriate format.
+
+    @raise errors.OpPrereqError: if unable to create output directory
+
+    """
+    output_file = "%s%s" % (self.results_name, OVF_EXT)
+    output_path = utils.PathJoin(self.output_dir, output_file)
+    self.ovf_writer = OVFWriter(not self.options.ext_usage)
+    logging.info("Saving read data to %s", output_path)
+
+    self.output_path = utils.PathJoin(self.output_dir, output_file)
+    files_list = [self.output_path]
+
+    self.ovf_writer.SaveDisksData(self.results_disk)
+    self.ovf_writer.SaveNetworksData(self.results_network)
+    if not self.options.ext_usage:
+      self.ovf_writer.SaveGanetiData(self.results_ganeti, self.results_network)
+
+    self.ovf_writer.SaveVirtualSystemData(self.results_name, self.results_vcpus,
+      self.results_memory)
+
+    data = self.ovf_writer.PrettyXmlDump()
+    utils.WriteFile(self.output_path, data=data)
+
+    manifest_file = "%s%s" % (self.results_name, MF_EXT)
+    manifest_path = utils.PathJoin(self.output_dir, manifest_file)
+    self._PrepareManifest(manifest_path)
+    files_list.append(manifest_path)
+
+    files_list.extend(self.references_files)
+
+    if self.options.ova_package:
+      ova_file = "%s%s" % (self.results_name, OVA_EXT)
+      packed_path = utils.PathJoin(self.packed_dir, ova_file)
+      try:
+        utils.Makedirs(self.packed_dir)
+      except OSError, err:
+        raise errors.OpPrereqError("Failed to create directory %s: %s" %
+                                   (self.packed_dir, err))
+      self._PrepareTarFile(packed_path, files_list)
+    logging.info("Creation of the OVF package was successfull")
+    self.Cleanup()