/usr/share/virt-manager/virtconv/vmx.py is in virtinst 1:1.5.1-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | # Copyright (C) 2013 Red Hat, Inc.
#
# Copyright 2008 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# 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 collections
import logging
import os
import re
import shlex
import virtinst
from virtinst import util
from .formats import parser_class
class _VMXLine(object):
"""
Class tracking an individual line in a VMX/VMDK file
"""
def __init__(self, content):
self.content = content
self.pair = None
self.is_blank = False
self.is_comment = False
self.is_disk = False
self._parse()
def _parse(self):
line = self.content.strip()
if not line:
self.is_blank = True
elif line.startswith("#"):
self.is_comment = True
elif line.startswith("RW ") or line.startswith("RDONLY "):
self.is_disk = True
else:
# Expected that this will raise an error for unknown format
before_eq, after_eq = line.split("=", 1)
key = before_eq.strip().lower()
value = after_eq.strip().strip('"')
self.pair = (key, value)
def parse_disk_path(self):
# format:
# RW 16777216 VMFS "test-flat.vmdk"
# RDONLY 156296322 V2I "virtual-pc-diskformat.v2i"
content = self.content.split(" ", 3)[3]
if not content.startswith("\""):
raise ValueError("Path was not fourth entry in VMDK storage line")
return shlex.split(content, " ", 1)[0]
class _VMXFile(object):
"""
Class tracking a parsed VMX/VMDK format file
"""
def __init__(self, content):
self.content = content
self.lines = []
self._parse()
def _parse(self):
for line in self.content:
try:
lineobj = _VMXLine(line)
self.lines.append(lineobj)
except Exception as e:
raise Exception(_("Syntax error at line %d: %s\n%s") %
(len(self.lines) + 1, line.strip(), e))
def pairs(self):
ret = collections.OrderedDict()
for line in self.lines:
if line.pair:
ret[line.pair[0]] = line.pair[1]
return ret
def parse_vmdk(filename):
"""
Parse a VMDK descriptor file
Reference: http://sanbarrow.com/vmdk-basics.html
"""
# Detect if passed file is a descriptor file
# Assume descriptor isn't larger than 10K
if not os.path.exists(filename):
logging.debug("VMDK file '%s' doesn't exist", filename)
return
if os.path.getsize(filename) > (10 * 1024):
logging.debug("VMDK file '%s' too big to be a descriptor", filename)
return
f = open(filename, "r")
content = f.readlines()
f.close()
try:
vmdkfile = _VMXFile(content)
except Exception:
logging.exception("%s looked like a vmdk file, but parsing failed",
filename)
return
disklines = [l for l in vmdkfile.lines if l.is_disk]
if len(disklines) == 0:
raise RuntimeError(_("Didn't detect a storage line in the VMDK "
"descriptor file"))
if len(disklines) > 1:
raise RuntimeError(_("Don't know how to handle multistorage VMDK "
"descriptors"))
return disklines[0].parse_disk_path()
def parse_netdev_entry(conn, ifaces, fullkey, value):
"""
Parse a particular key/value for a network. Throws ValueError.
"""
ignore, ignore, inst, key = re.split("^(ethernet)([0-9]+).", fullkey)
lvalue = value.lower()
if key == "present" and lvalue == "false":
return
net = None
for checkiface in ifaces:
if getattr(checkiface, "vmx_inst") == inst:
net = checkiface
break
if not net:
net = virtinst.VirtualNetworkInterface(conn)
setattr(net, "vmx_inst", inst)
net.set_default_source()
ifaces.append(net)
if key == "virtualdev":
# "vlance", "vmxnet", "e1000"
if lvalue in ["e1000"]:
net.model = lvalue
if key == "addresstype" and lvalue == "generated":
# Autogenerate a MAC address, the default
pass
if key == "address":
# we ignore .generatedAddress for auto mode
net.macaddr = lvalue
return net, inst
def parse_disk_entry(conn, disks, fullkey, value):
"""
Parse a particular key/value for a disk. FIXME: this should be a
lot smarter.
"""
# skip bus values, e.g. 'scsi0.present = "TRUE"'
if re.match(r"^(scsi|ide)[0-9]+[^:]", fullkey):
return
ignore, bus, bus_nr, inst, key = re.split(
r"^(scsi|ide)([0-9]+):([0-9]+)\.", fullkey)
lvalue = value.lower()
if key == "present" and lvalue == "false":
return
# Does anyone else think it's scary that we're still doing things
# like this?
if bus == "ide":
inst = int(bus_nr) * 2 + (int(inst) % 2)
elif bus == "scsi":
inst = int(bus_nr) * 16 + (int(inst) % 16)
disk = None
for checkdisk in disks:
if checkdisk.bus == bus and getattr(checkdisk, "vmx_inst") == inst:
disk = checkdisk
break
if not disk:
disk = virtinst.VirtualDisk(conn)
disk.bus = bus
setattr(disk, "vmx_inst", inst)
disks.append(disk)
if key == "devicetype":
if (lvalue == "atapi-cdrom" or
lvalue == "cdrom-raw" or
lvalue == "cdrom-image"):
disk.device = "cdrom"
if key == "filename":
disk.path = value
fmt = "raw"
if lvalue.endswith(".vmdk"):
fmt = "vmdk"
# See if the filename is actually a VMDK descriptor file
newpath = parse_vmdk(disk.path)
if newpath:
logging.debug("VMDK file parsed path %s->%s",
disk.path, newpath)
disk.path = newpath
disk.driver_type = fmt
class vmx_parser(parser_class):
"""
Support for VMWare .vmx files. Note that documentation is
particularly sparse on this format, with pretty much the best
resource being http://sanbarrow.com/vmx.html
"""
name = "vmx"
suffix = ".vmx"
@staticmethod
def identify_file(input_file):
"""
Return True if the given file is of this format.
"""
if os.path.getsize(input_file) > (1024 * 1024 * 2):
return
infile = open(input_file, "r")
content = infile.readlines()
infile.close()
for line in content:
# some .vmx files don't bother with the header
if (re.match(r'^config.version\s+=', line) or
re.match(r'^#!\s*/usr/bin/vm(ware|player)', line)):
return True
return False
@staticmethod
def export_libvirt(conn, input_file):
infile = open(input_file, "r")
contents = infile.readlines()
infile.close()
logging.debug("Importing VMX file:\n%s", "".join(contents))
vmxfile = _VMXFile(contents)
config = vmxfile.pairs()
if not config.get("displayname"):
raise ValueError(_("No displayName defined in '%s'") %
input_file)
name = config.get("displayname")
mem = config.get("memsize")
desc = config.get("annotation")
vcpus = config.get("numvcpus")
def _find_keys(prefixes):
ret = []
for key, value in config.items():
for p in util.listify(prefixes):
if key.startswith(p):
ret.append((key, value))
break
return ret
disks = []
for key, value in _find_keys(["scsi", "ide"]):
parse_disk_entry(conn, disks, key, value)
ifaces = []
for key, value in _find_keys("ethernet"):
parse_netdev_entry(conn, ifaces, key, value)
for disk in disks:
if disk.device == "disk":
continue
# vmx files often have dross left in path for CD entries
if (disk.path is None or
disk.path.lower() == "auto detect" or
not os.path.exists(disk.path)):
disk.path = None
guest = conn.caps.lookup_virtinst_guest()
guest.installer = virtinst.ImportInstaller(conn)
guest.name = name.replace(" ", "_")
guest.description = desc or None
if vcpus:
guest.vcpus = int(vcpus)
if mem:
guest.memory = int(mem) * 1024
for dev in ifaces + disks:
guest.add_device(dev)
return guest
|