diff options
Diffstat (limited to 'src/main/java/org/openslx/util')
20 files changed, 555 insertions, 2969 deletions
diff --git a/src/main/java/org/openslx/util/AppUtil.java b/src/main/java/org/openslx/util/AppUtil.java new file mode 100644 index 0000000..340dc21 --- /dev/null +++ b/src/main/java/org/openslx/util/AppUtil.java @@ -0,0 +1,166 @@ +package org.openslx.util; + +import java.io.InputStream; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.jar.Attributes; +import java.util.jar.JarInputStream; +import java.util.jar.Manifest; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class AppUtil +{ + + private final static Logger LOGGER = LogManager.getLogger( AppUtil.class ); + + private static final int PROPERTY_MAX_WIDTH = 30; + + private static final String MANIFEST_REVISION_VERSION = "Revision-Version"; + private static final String MANIFEST_REVISION_BRANCH = "Revision-Branch"; + private static final String MANIFEST_BUILD_TIMESTAMP = "Build-Timestamp"; + private static final String MANIFEST_BUILD_JDK = "Build-Jdk"; + + private static final String PROPERTY_APP_NAME = "app.name"; + private static final String PROPERTY_APP_VERSION = "app.version"; + private static final String PROPERTY_APP_REVISION_VERSION = "app.revision.version"; + private static final String PROPERTY_APP_REVISION_BRANCH = "app.revision.branch"; + private static final String PROPERTY_APP_BUILD_DATE = "app.build.date"; + private static final String PROPERTY_APP_BUILD_JDK = "app.build.jdk"; + + private static final String PROPERTY_JAVA_OS_NAME = "os.name"; + private static final String PROPERTY_JAVA_OS_ARCH = "os.arch"; + + private static final String PROPERTY_JAVA_SPEC_VENDOR = "java.specification.vendor"; + private static final String PROPERTY_JAVA_SPEC_NAME = "java.specification.name"; + private static final String PROPERTY_JAVA_SPEC_VERSION = "java.specification.version"; + + private static final String PROPERTY_JAVA_VERSION = "java.version"; + private static final String PROPERTY_JAVA_VERSION_VM = "java.vm.version"; + private static final String PROPERTY_JAVA_VERSION_RUNTIME = "java.runtime.version"; + + private static final String PROPERTY_JAVA_MEMORY_LIMIT = "java.runtime.memory"; + + private static final String PROPERTY_JAVA_BITNESS = "sun.arch.data.model"; + + private static Attributes manifestAttributes = null; + + private static String getManifestValue( final String entry ) + { + if ( manifestAttributes == null ) { + InputStream jarFileStream = null; + JarInputStream jarStream = null; + // Do this so in case of failure, we won't open the jar again and again and spam exceptions to the log + manifestAttributes = new Attributes(); + + try { + jarFileStream = AppUtil.class.getProtectionDomain().getCodeSource().getLocation().openStream(); + jarStream = new JarInputStream( jarFileStream ); + final Manifest mf = jarStream.getManifest(); + manifestAttributes = mf.getMainAttributes(); + } catch ( Exception e ) { + LOGGER.warn( "Cannot read jar/manifest attributes", e ); + } finally { + Util.safeClose( jarStream, jarFileStream ); + } + } + + return manifestAttributes.getValue( entry ); + } + + public static String getRevisionVersion() + { + return AppUtil.getManifestValue( AppUtil.MANIFEST_REVISION_VERSION ); + } + + public static String getRevisionBranch() + { + return AppUtil.getManifestValue( AppUtil.MANIFEST_REVISION_BRANCH ); + } + + public static long getBuildTimestamp() + { + final String timestampRaw = AppUtil.getManifestValue( AppUtil.MANIFEST_BUILD_TIMESTAMP ); + long timestamp = 0; + + try { + timestamp = Long.valueOf( timestampRaw ); + timestamp /= 1000L; + } catch ( NumberFormatException e ) { + timestamp = 0; + } + + return timestamp; + } + + public static String getBuildTime() + { + final long timestamp = AppUtil.getBuildTimestamp(); + final String buildTime; + + if ( timestamp > 0 ) { + final Instant time = Instant.ofEpochSecond( timestamp ); + buildTime = DateTimeFormatter.RFC_1123_DATE_TIME.withZone( ZoneId.systemDefault() ).format( time ); + } else { + buildTime = null; + } + + return buildTime; + } + + public static String getBuildJdk() + { + return AppUtil.getManifestValue( AppUtil.MANIFEST_BUILD_JDK ); + } + + private static String formatProperty( final String property ) + { + return String.format( "%-" + AppUtil.PROPERTY_MAX_WIDTH + "s", property ); + } + + public static void logProperty( final Logger logger, final String propertyName, final String propertyValue ) + { + logger.info( AppUtil.formatProperty( propertyName ) + propertyValue ); + } + + public static void logJavaProperty( Logger logger, final String javaProperty ) + { + AppUtil.logProperty( logger, javaProperty, System.getProperty( javaProperty ) ); + } + + public static void logHeader( final Logger logger, final String appName, final String appVersion ) + { + // Format maximum VM memory + final String mem; + long limit = Runtime.getRuntime().maxMemory() / ( 1024l * 1024 ); + if ( limit > 99999999 ) { + mem = "-"; + } else if ( limit >= 2048 ) { + mem = String.format( "%.1fG", limit / 1024f ); + } else { + mem = limit + "M"; + } + logger.info( "-------------------------------------------------------------------------------" ); + logger.info( appName ); + logger.info( "-------------------------------------------------------------------------------" ); + logProperty( logger, AppUtil.PROPERTY_APP_NAME, appName ); + logProperty( logger, AppUtil.PROPERTY_APP_VERSION, appVersion ); + logProperty( logger, AppUtil.PROPERTY_APP_REVISION_VERSION, AppUtil.getRevisionVersion() ); + logProperty( logger, AppUtil.PROPERTY_APP_REVISION_BRANCH, AppUtil.getRevisionBranch() ); + logProperty( logger, AppUtil.PROPERTY_APP_BUILD_DATE, AppUtil.getBuildTime() ); + logProperty( logger, AppUtil.PROPERTY_APP_BUILD_JDK, AppUtil.getBuildJdk() ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_OS_NAME ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_SPEC_VENDOR ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_SPEC_NAME ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_SPEC_VERSION ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_VERSION ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_VERSION_VM ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_VERSION_RUNTIME ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_BITNESS ); + logJavaProperty( logger, AppUtil.PROPERTY_JAVA_OS_ARCH ); + logProperty( logger, AppUtil.PROPERTY_JAVA_MEMORY_LIMIT, mem ); + logger.info( "-------------------------------------------------------------------------------" ); + } +} diff --git a/src/main/java/org/openslx/util/FsUtil.java b/src/main/java/org/openslx/util/FsUtil.java index 76571ef..3f9731a 100644 --- a/src/main/java/org/openslx/util/FsUtil.java +++ b/src/main/java/org/openslx/util/FsUtil.java @@ -2,12 +2,13 @@ package org.openslx.util; import java.io.File; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class FsUtil { - private static final Logger LOGGER = Logger.getLogger( FsUtil.class ); + private static final Logger LOGGER = LogManager.getLogger( FsUtil.class ); public static String getRelativePath( File absolutePath, File parentDir ) { diff --git a/src/main/java/org/openslx/util/GenericDataCache.java b/src/main/java/org/openslx/util/GenericDataCache.java index 5ae73fb..a7116b7 100644 --- a/src/main/java/org/openslx/util/GenericDataCache.java +++ b/src/main/java/org/openslx/util/GenericDataCache.java @@ -2,12 +2,13 @@ package org.openslx.util; import java.util.concurrent.atomic.AtomicReference; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public abstract class GenericDataCache<T> { - private static final Logger LOGGER = Logger.getLogger( GenericDataCache.class ); + private static final Logger LOGGER = LogManager.getLogger( GenericDataCache.class ); /** * How long the cached data is valid after fetching diff --git a/src/main/java/org/openslx/util/Json.java b/src/main/java/org/openslx/util/Json.java index f92bb58..5e5fbcb 100644 --- a/src/main/java/org/openslx/util/Json.java +++ b/src/main/java/org/openslx/util/Json.java @@ -8,7 +8,8 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.thrift.TBase; import com.google.gson.Gson; @@ -25,7 +26,7 @@ import com.google.gson.JsonSyntaxException; public class Json { - private static final Logger LOGGER = Logger.getLogger(Json.class); + private static final Logger LOGGER = LogManager.getLogger(Json.class); /** * Global static instance. The Gson object is thread-safe. @@ -137,7 +138,7 @@ public class Json { if (element == null || element.isJsonNull()) continue; try { - field.setter.invoke(inst, context.deserialize(element, field.field.getType())); + field.setter.invoke(inst, new Object[] { context.deserialize(element, field.field.getType()) }); } catch (Exception e) { LOGGER.warn("Could not call " + field.setter.getName() + " on " + clazz.getSimpleName(), e); } diff --git a/src/main/java/org/openslx/util/LevenshteinDistance.java b/src/main/java/org/openslx/util/LevenshteinDistance.java new file mode 100644 index 0000000..0f33167 --- /dev/null +++ b/src/main/java/org/openslx/util/LevenshteinDistance.java @@ -0,0 +1,85 @@ +package org.openslx.util; + +public final class LevenshteinDistance +{ + private final int insertionCost; + private final int deletionCost; + private final int substitutionCost; + + public LevenshteinDistance() + { + this( 1, 1, 1 ); + } + + public LevenshteinDistance( int insertionCost, int deletionCost, int substitutionCost ) + { + this.validateCostArgument( insertionCost >= 0, "Insertion cost must be greater than or equal to 0" ); + this.validateCostArgument( deletionCost >= 0, "Deletion cost must be greater than or equal to 0" ); + this.validateCostArgument( substitutionCost >= 0, "Substitution cost must be greater than or equal to 0" ); + + this.insertionCost = insertionCost; + this.deletionCost = deletionCost; + this.substitutionCost = substitutionCost; + } + + private void validateCostArgument( boolean condition, String errorMsg ) + { + if ( !condition ) { + throw new IllegalArgumentException( errorMsg ); + } + } + + public int calculateDistance( CharSequence source, CharSequence target ) + { + if ( source == null || target == null ) { + throw new IllegalArgumentException( "Source or target cannot be null" ); + } + + int sourceLength = source.length(); + int targetLength = target.length(); + + int[][] matrix = new int[ sourceLength + 1 ][ targetLength + 1 ]; + matrix[0][0] = 0; + + for ( int row = 1; row <= sourceLength; ++row ) { + matrix[row][0] = row; + } + + for ( int col = 1; col <= targetLength; ++col ) { + matrix[0][col] = col; + } + + for ( int row = 1; row <= sourceLength; ++row ) { + for ( int col = 1; col <= targetLength; ++col ) { + matrix[row][col] = calcMinCost( source, target, matrix, row, col ); + } + } + + return matrix[sourceLength][targetLength]; + } + + private int calcMinCost( CharSequence source, CharSequence target, int[][] matrix, int row, int col ) + { + return Math.min( calcSubstitutionCost( source, target, matrix, row, col ), + Math.min( calcDeletionCost( matrix, row, col ), calcInsertionCost( matrix, row, col ) ) ); + } + + private int calcInsertionCost( int[][] matrix, int row, int col ) + { + return matrix[row][col - 1] + insertionCost; + } + + private int calcDeletionCost( int[][] matrix, int row, int col ) + { + return matrix[row - 1][col] + deletionCost; + } + + private int calcSubstitutionCost( CharSequence source, CharSequence target, int[][] matrix, int row, int col ) + { + int cost = 0; + if ( source.charAt( row - 1 ) != target.charAt( col - 1 ) ) { + cost = substitutionCost; + } + return matrix[row - 1][col - 1] + cost; + } +} diff --git a/src/main/java/org/openslx/util/QuickTimer.java b/src/main/java/org/openslx/util/QuickTimer.java index ec7c2ed..a26fd76 100644 --- a/src/main/java/org/openslx/util/QuickTimer.java +++ b/src/main/java/org/openslx/util/QuickTimer.java @@ -3,7 +3,8 @@ package org.openslx.util; import java.util.Timer; import java.util.TimerTask; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * This is a global, static {@link Timer} you can use anywhere for repeating @@ -15,7 +16,7 @@ import org.apache.log4j.Logger; */ public class QuickTimer { - private static final Logger LOGGER = Logger.getLogger(QuickTimer.class); + private static final Logger LOGGER = LogManager.getLogger(QuickTimer.class); private static final Timer timer = new Timer("QuickTimer", true); diff --git a/src/main/java/org/openslx/util/Resources.java b/src/main/java/org/openslx/util/Resources.java new file mode 100644 index 0000000..9c1dddf --- /dev/null +++ b/src/main/java/org/openslx/util/Resources.java @@ -0,0 +1,15 @@ +package org.openslx.util; + +/** + * Collection of resource utils. + * + * @author Manuel Bentele + * @version 1.0 + */ +public class Resources +{ + /** + * Path separator for resource {@link URL}s. + */ + public static final String PATH_SEPARATOR = "/"; +} diff --git a/src/main/java/org/openslx/util/TarArchiveUtil.java b/src/main/java/org/openslx/util/TarArchiveUtil.java new file mode 100644 index 0000000..9970b0b --- /dev/null +++ b/src/main/java/org/openslx/util/TarArchiveUtil.java @@ -0,0 +1,146 @@ +package org.openslx.util; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; + +public class TarArchiveUtil +{ + + private TarArchiveUtil() + { + } + + public static class TarArchiveReader implements AutoCloseable + { + private final TarArchiveInputStream tarInputStream; + private TarArchiveEntry currentEntry = null; + + public TarArchiveReader( InputStream in ) throws IOException + { + this( in, true, false ); + } + + public TarArchiveReader( InputStream in, boolean isBuffered, boolean isCompressed ) throws IOException + { + InputStream stream = in; + if ( isBuffered ) { + stream = new BufferedInputStream( stream ); + } + + if ( isCompressed ) { + stream = new GZIPInputStream( stream ); + } + + this.tarInputStream = new TarArchiveInputStream( stream ); + } + + public boolean hasNextEntry() throws IOException + { + this.currentEntry = this.tarInputStream.getNextTarEntry(); + if ( this.currentEntry != null ) { + return true; + } else { + return false; + } + } + + public String getEntryName() + { + if ( this.currentEntry == null ) + return null; + + return this.currentEntry.getName(); + } + + public byte[] readCurrentEntry() throws IOException + { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] rawData = new byte[ 1024 ]; + int count = 0; + + while ( ( count = this.tarInputStream.read( rawData ) ) != -1 ) { + output.write( rawData, 0, count ); + } + + return output.toByteArray(); + } + + @Override + public void close() throws IOException + { + tarInputStream.close(); + } + + } + + public static class TarArchiveWriter implements AutoCloseable + { + private final TarArchiveOutputStream tarOutputStream; + + public TarArchiveWriter( OutputStream out ) throws IOException + { + this( out, true, true ); + } + + public TarArchiveWriter( OutputStream out, boolean isBuffered, boolean isCompressed ) throws IOException + { + OutputStream stream = out; + + if ( isBuffered ) { + stream = new BufferedOutputStream( stream ); + } + + if ( isCompressed ) { + stream = new GZIPOutputStream( stream ); + } + + this.tarOutputStream = new TarArchiveOutputStream( stream ); + } + + public void writeFile( String filename, String data ) throws IOException + { + + if ( data == null ) + return; + putFile( filename, data.getBytes( StandardCharsets.UTF_8 ) ); + } + + public void writeFile( String filename, byte[] data ) throws IOException + { + if ( data == null ) + return; + putFile( filename, data ); + } + + private void putFile( String filename, byte[] data ) throws IOException + { + if ( data == null ) + return; + + TarArchiveEntry entry = new TarArchiveEntry( filename ); + entry.setSize( data.length ); + entry.setModTime( System.currentTimeMillis() ); + entry.setMode( 0644 ); + tarOutputStream.putArchiveEntry( entry ); + tarOutputStream.write( data ); + tarOutputStream.closeArchiveEntry(); + } + + @Override + public void close() throws IOException + { + tarOutputStream.close(); + } + } +} diff --git a/src/main/java/org/openslx/util/ThriftUtil.java b/src/main/java/org/openslx/util/ThriftUtil.java index bafe566..ef10798 100644 --- a/src/main/java/org/openslx/util/ThriftUtil.java +++ b/src/main/java/org/openslx/util/ThriftUtil.java @@ -2,11 +2,12 @@ package org.openslx.util; import java.io.BufferedReader; import java.io.IOException; +import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; -import org.openslx.util.vm.VmwareConfig; +import org.openslx.virtualization.configuration.VirtualizationConfigurationVmwareFileFormat; public class ThriftUtil { @@ -16,9 +17,9 @@ public class ThriftUtil { List<byte[]> hashList = new ArrayList<>(blockHashes.size()); for (ByteBuffer hash : blockHashes) { byte[] buffer = new byte[hash.remaining()]; - hash.mark(); + ((Buffer)hash).mark(); hash.get(buffer); - hash.reset(); + ((Buffer)hash).reset(); hashList.add(buffer); } return hashList; @@ -28,9 +29,9 @@ public class ThriftUtil { byte[] byteArray = null; if (buffer != null) { byteArray = new byte[buffer.remaining()]; - buffer.mark(); + ((Buffer)buffer).mark(); buffer.get(byteArray); - buffer.reset(); + ((Buffer)buffer).reset(); } return byteArray; } @@ -40,7 +41,8 @@ public class ThriftUtil { BufferedReader reader; StringBuffer content = new StringBuffer(""); try { - reader = VmwareConfig.getVmxReader(bytes, bytes.length); + // Why is a generic function to convert a buffer to string CALLING A VMWARE SPECIFIC FUNCTION!? + reader = VirtualizationConfigurationVmwareFileFormat.getVmxReader(bytes, bytes.length); String line=""; while ((line=reader.readLine()) != null) { content.append(line + "\n"); diff --git a/src/main/java/org/openslx/util/Util.java b/src/main/java/org/openslx/util/Util.java index 441bc88..8593f80 100644 --- a/src/main/java/org/openslx/util/Util.java +++ b/src/main/java/org/openslx/util/Util.java @@ -2,11 +2,12 @@ package org.openslx.util; import java.util.regex.Pattern; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class Util { - private static Logger log = Logger.getLogger( Util.class ); + private static Logger log = LogManager.getLogger( Util.class ); /** * Check if the given object is null, abort program if true. An optional @@ -117,9 +118,20 @@ public class Util } } + /** + * Number of seconds elapsed since 1970-01-01 UTC. + */ public static long unixTime() { return System.currentTimeMillis() / 1000; } + /** + * Monotonic tick count in milliseconds, not bound to RTC. + */ + public static long tickCount() + { + return System.nanoTime() / 1000; + } + } diff --git a/src/main/java/org/openslx/util/XmlHelper.java b/src/main/java/org/openslx/util/XmlHelper.java index 70c5be8..90d282b 100644 --- a/src/main/java/org/openslx/util/XmlHelper.java +++ b/src/main/java/org/openslx/util/XmlHelper.java @@ -3,6 +3,8 @@ package org.openslx.util; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -14,24 +16,29 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.Attr; import org.w3c.dom.Document; +import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlHelper { - private final static Logger LOGGER = Logger.getLogger( XmlHelper.class ); + private final static Logger LOGGER = LogManager.getLogger( XmlHelper.class ); // TODO check thread-safety - public static final XPath XPath = XPathFactory.newInstance().newXPath(); + private static final XPath XPath = XPathFactory.newInstance().newXPath(); private static DocumentBuilder dBuilder; static { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setNamespaceAware( true ); dbFactory.setIgnoringComments( true ); try { dBuilder = dbFactory.newDocumentBuilder(); @@ -40,17 +47,64 @@ public class XmlHelper } } + public static String globalXPathToLocalXPath( String xPath ) + { + final StringBuilder exprBuilder = new StringBuilder(); + final String[] elements = xPath.split( "/" ); + + for ( final String element : elements ) { + if ( !element.isEmpty() ) { + final Pattern arraySpecifierRegex = Pattern.compile( "^(.*)\\[(.*)\\]$" ); + final Matcher arraySpecifierMatcher = arraySpecifierRegex.matcher( element ); + final String elementName; + final String elementSpecifier; + + if ( arraySpecifierMatcher.find() ) { + elementName = arraySpecifierMatcher.group( 1 ); + elementSpecifier = arraySpecifierMatcher.group( 2 ); + } else { + elementName = element; + elementSpecifier = null; + } + + if ( !elementName.startsWith( "@" ) && !elementName.equals( "*" ) ) { + exprBuilder.append( "/*[local-name()='" + elementName + "']" ); + + } else { + exprBuilder.append( "/" + elementName ); + } + + if ( elementSpecifier != null && !elementSpecifier.isEmpty() ) { + exprBuilder.append( "[" + elementSpecifier + "]" ); + } + } + } + + return exprBuilder.toString(); + } + + public static XPathExpression compileXPath( String xPath ) throws XPathExpressionException + { + final String localXPath = XmlHelper.globalXPathToLocalXPath( xPath ); + return XPath.compile( localXPath ); + } + public static Document parseDocumentFromStream( InputStream is ) { Document doc = null; + + // read document from stream try { doc = dBuilder.parse( is ); } catch ( SAXException | IOException e ) { - LOGGER.error( "Failed to parse input stream to document." ); + doc = null; } - if ( doc == null ) - return null; - doc.getDocumentElement().normalize(); + + // normalize parsed document + if ( doc != null ) { + doc.getDocumentElement().normalize(); + } + return doc; } @@ -105,4 +159,51 @@ public class XmlHelper return null; } } + + public static Element getOrCreateElement( Document doc, Element parent, String nsUri, String nsName, + String name, String attrName, String attrValue ) + { + final NodeList childList; + if ( nsUri == null ) { + childList = parent.getElementsByTagName( name ); + } else { + childList = parent.getElementsByTagNameNS( nsUri, name ); + } + Element element = null; + outer: for ( int i = 0; i < childList.getLength(); ++i ) { + Node n = childList.item( i ); + if ( n.getNodeType() != Node.ELEMENT_NODE ) + continue; + if ( attrName != null && attrValue != null ) { + for ( int ai = 0; ai < n.getAttributes().getLength(); ++ai ) { + Node attr = n.getAttributes().item( ai ); + if ( attr.getNodeType() != Attr.ELEMENT_NODE ) + continue; + Attr a = (Attr)attr; + if ( !attrName.equals( a.getLocalName() ) || !attrValue.equals( a.getValue() ) ) + continue; + element = (Element)n; + break outer; + } + } else { + element = (Element)n; + break; + } + } + if ( element == null ) { + // Need a new <qemu:device alias="hostdev0"> + if ( nsUri == null || nsName == null ) { + element = doc.createElement( name ); + } else { + element = doc.createElementNS( nsUri, name ); + element.setPrefix( nsName ); + } + if ( attrName != null && attrValue != null ) { + element.setAttribute( attrName, attrValue ); + } + parent.appendChild( element ); + } + return element; + } + } diff --git a/src/main/java/org/openslx/util/vm/DiskImage.java b/src/main/java/org/openslx/util/vm/DiskImage.java deleted file mode 100644 index 2b24a3f..0000000 --- a/src/main/java/org/openslx/util/vm/DiskImage.java +++ /dev/null @@ -1,205 +0,0 @@ -package org.openslx.util.vm; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.Arrays; - -import org.apache.log4j.Logger; -import org.openslx.bwlp.thrift.iface.Virtualizer; -import org.openslx.thrifthelper.TConst; -import org.openslx.util.Util; - -public class DiskImage -{ - private static final Logger LOGGER = Logger.getLogger( DiskImage.class ); - /** - * Big endian representation of the 4 bytes 'KDMV' - */ - private static final int VMDK_MAGIC = 0x4b444d56; - private static final int VDI_MAGIC = 0x7f10dabe; - /** - * Big endian representation of the 4 bytes 'QFI\xFB' - */ - private static final int QEMU_MAGIC = 0x514649fb; - - public enum ImageFormat - { - VMDK( "vmdk" ), QCOW2( "qcow2" ), VDI( "vdi" ); - - public final String extension; - - private ImageFormat( String extension ) - { - this.extension = extension; - } - - public static ImageFormat defaultForVirtualizer( Virtualizer virt ) - { - if ( virt == null ) - return null; - return defaultForVirtualizer( virt.virtId ); - } - - public static ImageFormat defaultForVirtualizer( String virtId ) - { - if ( virtId == null ) - return null; - if ( virtId.equals( TConst.VIRT_VMWARE ) ) - return VMDK; - if ( virtId.equals( TConst.VIRT_VIRTUALBOX ) ) - return VDI; - if ( virtId.equals( TConst.VIRT_QEMU ) ) - return QCOW2; - return null; - } - } - - public final boolean isStandalone; - public final boolean isCompressed; - public final boolean isSnapshot; - public final ImageFormat format; - public final String subFormat; - public final int hwVersion; - public final String diskDescription; - - public ImageFormat getImageFormat() - { - return format; - } - - public DiskImage( File disk ) throws FileNotFoundException, IOException, UnknownImageFormatException - { - LOGGER.debug( "Validating disk file: " + disk.getAbsolutePath() ); - try ( RandomAccessFile file = new RandomAccessFile( disk, "r" ) ) { - // vmdk - boolean isVmdkMagic = ( file.readInt() == VMDK_MAGIC ); - if ( isVmdkMagic || file.length() < 4096 ) { - if ( isVmdkMagic ) { - file.seek( 512 ); - } else { - file.seek( 0 ); - } - byte[] buffer = new byte[ (int)Math.min( 2048, file.length() ) ]; - file.readFully( buffer ); - VmwareConfig config; - try { - config = new VmwareConfig( buffer, findNull( buffer ) ); - } catch ( UnsupportedVirtualizerFormatException e ) { - config = null; - } - if ( config != null ) { - String sf = config.get( "createType" ); - String parent = config.get( "parentCID" ); - if ( sf != null || parent != null ) { - subFormat = sf; - this.isStandalone = isStandaloneCreateType( subFormat, parent ); - this.isCompressed = subFormat != null && subFormat.equalsIgnoreCase( "streamOptimized" ); - this.isSnapshot = parent != null && !parent.equalsIgnoreCase( "ffffffff" ); - this.format = ImageFormat.VMDK; - String hwv = config.get( "ddb.virtualHWVersion" ); - if ( hwv == null ) { - this.hwVersion = 10; - } else { - this.hwVersion = Util.parseInt( hwv, 10 ); - } - this.diskDescription = null; - return; - } - } - } - // Format spec from: https://forums.virtualbox.org/viewtopic.php?t=8046 - // First 64 bytes are the opening tag: <<< .... >>> - // which we don't care about, then comes the VDI signature - file.seek( 64 ); - if ( file.readInt() == VDI_MAGIC ) { - // skip the next 4 ints as they don't interest us: - // - VDI version - // - size of header, strangely irrelevant? - // - image type, 1 for dynamic allocated storage, 2 for fixed size - // - image flags, seem to be always 00 00 00 00 - file.skipBytes( 4 * 4 ); - - // next 256 bytes are image description - byte[] imageDesc = new byte[ 256 ]; - file.readFully( imageDesc ); - // next sections are irrelevant (int if not specified): - // - offset blocks - // - offset data - // - cylinders - // - heads - // - sectors - // - sector size - // - <unused> - // - disk size (long = 8 bytes) - // - block size - // - block extra data - // - blocks in hdd - // - blocks allocated - file.skipBytes( 4 * 13 ); - - // now it gets interesting, UUID of VDI - byte[] diskUuid = new byte[ 16 ]; - file.readFully( diskUuid ); - // last snapshot uuid, mostly uninteresting since we don't support snapshots -> skip 16 bytes - // TODO: meaning of "uuid link"? for now, skip 16 - file.skipBytes( 32 ); - - // parent uuid, indicator if this VDI is a snapshot or not - byte[] parentUuid = new byte[ 16 ]; - file.readFully( parentUuid ); - byte[] zeroUuid = new byte[ 16 ]; - Arrays.fill( zeroUuid, (byte)0 ); - this.isSnapshot = !Arrays.equals( parentUuid, zeroUuid ); - // VDI does not seem to support split VDI files so always standalone - this.isStandalone = true; - // compression is done by sparsifying the disk files, there is no flag for it - this.isCompressed = false; - this.format = ImageFormat.VDI; - this.subFormat = null; - this.diskDescription = new String( imageDesc ); - this.hwVersion = 0; - return; - } - - // TODO: qcow - file.seek( 0 ); - if ( file.readInt() == QEMU_MAGIC ) { - // dummy values - this.isStandalone = true; - this.isCompressed = false; - this.isSnapshot = false; - this.format = ImageFormat.QCOW2; - this.subFormat = null; - this.diskDescription = null; - this.hwVersion = 0; - return; - } - } - throw new UnknownImageFormatException(); - } - - private int findNull( byte[] buffer ) - { - for ( int i = 0; i < buffer.length; ++i ) { - if ( buffer[i] == 0 ) - return i; - } - return buffer.length; - } - - private boolean isStandaloneCreateType( String type, String parent ) - { - if ( type == null ) - return false; - if ( parent != null && !parent.equalsIgnoreCase( "ffffffff" ) ) - return false; - return type.equalsIgnoreCase( "streamOptimized" ) || type.equalsIgnoreCase( "monolithicSparse" ); - } - - public static class UnknownImageFormatException extends Exception - { - private static final long serialVersionUID = -6647935235475007171L; - } -} diff --git a/src/main/java/org/openslx/util/vm/KeyValuePair.java b/src/main/java/org/openslx/util/vm/KeyValuePair.java deleted file mode 100644 index d89d51b..0000000 --- a/src/main/java/org/openslx/util/vm/KeyValuePair.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.openslx.util.vm; - -class KeyValuePair -{ - public final String key; - public final String value; - - public KeyValuePair( String key, String value ) - { - this.key = key; - this.value = value; - } -}
\ No newline at end of file diff --git a/src/main/java/org/openslx/util/vm/QemuMetaData.java b/src/main/java/org/openslx/util/vm/QemuMetaData.java deleted file mode 100644 index 201ffd8..0000000 --- a/src/main/java/org/openslx/util/vm/QemuMetaData.java +++ /dev/null @@ -1,233 +0,0 @@ -package org.openslx.util.vm; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; -import org.openslx.bwlp.thrift.iface.OperatingSystem; -import org.openslx.bwlp.thrift.iface.Virtualizer; -import org.openslx.thrifthelper.TConst; -import org.openslx.util.vm.DiskImage.ImageFormat; -import org.openslx.util.vm.DiskImage.UnknownImageFormatException; - -public class QemuMetaData extends VmMetaData<VBoxSoundCardMeta, VBoxDDAccelMeta, VBoxHWVersionMeta, VBoxEthernetDevTypeMeta, VBoxUsbSpeedMeta> -{ - - private final Map<String, String> arguments = new HashMap<String, String>(); - // the above map's elements will take the place of <args> in the config string - private String config; - private static final Logger LOGGER = Logger.getLogger( QemuMetaData.class ); - - private static final Virtualizer virtualizer = new Virtualizer( TConst.VIRT_QEMU, "QEMU-KVM" ); - - public QemuMetaData( List<OperatingSystem> osList, File file ) throws FileNotFoundException, IOException, UnsupportedVirtualizerFormatException - { - super( osList ); - DiskImage di; - try { - di = new DiskImage( file ); - } catch ( UnknownImageFormatException e ) { - di = null; - } - if ( di == null || di.format != ImageFormat.QCOW2 ) { - throw new UnsupportedVirtualizerFormatException( "This is not a qcow2 disk image" ); - } - config = "qemu-system-i386 <args> <image> -enable-kvm\nqemu-system-x86_64 <args> <image> -enable-kvm"; - displayName = file.getName().substring( 0, file.getName().indexOf( "." ) ); - setOs( "anyOs" ); - hdds.add( new HardDisk( "anychipset", DriveBusType.IDE, file.getAbsolutePath() ) ); - makeStartSequence(); - } - - // initiates the arguments map with a default working sequence that will later be used in the definition array - public void makeStartSequence() - { - arguments.put( "cpu", "host" ); - arguments.put( "smp", "2" ); - arguments.put( "m", "1024" ); - arguments.put( "vga", "std" ); - } - - private String configWithArgs() - { - String tempString = ""; - for ( String key : arguments.keySet() ) { - tempString += "-" + key + " " + arguments.get( key ) + " "; - } - return config.replaceAll( "<args>", tempString ); - } - - @Override - public byte[] getFilteredDefinitionArray() - { - return configWithArgs().getBytes( StandardCharsets.UTF_8 ); - } - - @Override - public void applySettingsForLocalEdit() - { - } - - @Override - public boolean addHddTemplate( File diskImage, String hddMode, String redoDir ) - { - String tempS = config.replaceAll( "<image>", diskImage.getAbsolutePath() ); - config = tempS; - hdds.add( new HardDisk( "anychipset", DriveBusType.IDE, diskImage.getAbsolutePath() ) ); - return true; - } - - @Override - public boolean addHddTemplate( String diskImagePath, String hddMode, String redoDir ) - { - String tempS = config.replaceAll( "<image>", diskImagePath ); - config = tempS; - hdds.add( new HardDisk( "anychipset", DriveBusType.IDE, diskImagePath ) ); - return true; - } - - @Override - public boolean addDefaultNat() - { - return true; - } - - @Override - public void setOs( String vendorOsId ) - { - setOs( TConst.VIRT_QEMU, vendorOsId ); - } - - @Override - public boolean addDisplayName( String name ) - { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean addRam( int mem ) - { - this.arguments.put( "m", Integer.toString( mem ) ); - return true; - } - - @Override - public void addFloppy( int index, String image, boolean readOnly ) - { - // TODO Auto-generated method stub - - } - - @Override - public boolean addCdrom( String image ) - { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean addCpuCoreCount( int nrOfCores ) - { - this.arguments.put( "smp", Integer.toString( nrOfCores ) ); - return true; - } - - @Override - public void setSoundCard( VmMetaData.SoundCardType type ) - { - } - - @Override - public VmMetaData.SoundCardType getSoundCard() - { - return null; - } - - @Override - public void setDDAcceleration( VmMetaData.DDAcceleration type ) - { - } - - @Override - public VmMetaData.DDAcceleration getDDAcceleration() - { - return null; - } - - @Override - public void setHWVersion( VmMetaData.HWVersion type ) - { - } - - @Override - public VmMetaData.HWVersion getHWVersion() - { - return null; - } - - @Override - public void setEthernetDevType( int cardIndex, VmMetaData.EthernetDevType type ) - { - } - - @Override - public VmMetaData.EthernetDevType getEthernetDevType( int cardIndex ) - { - return null; - } - - @Override - public byte[] getDefinitionArray() - { - return configWithArgs().getBytes( StandardCharsets.UTF_8 ); - } - - @Override - public boolean addEthernet( VmMetaData.EtherType type ) - { - return false; - } - - @Override - public Virtualizer getVirtualizer() - { - return virtualizer; - } - - @Override - public boolean tweakForNonPersistent() - { - return false; - } - - @Override - public void registerVirtualHW() - { - } - - @Override - public void setMaxUsbSpeed( VmMetaData.UsbSpeed speed ) - { - // TODO: Actual speed setting? - if ( speed == null || speed == VmMetaData.UsbSpeed.NONE ) { - arguments.remove( "usb" ); - } else { - arguments.put( "usb", "" ); - } - } - - @Override - public VmMetaData.UsbSpeed getMaxUsbSpeed() - { - if ( arguments.containsKey( "usb" ) ) - return VmMetaData.UsbSpeed.USB2_0; // TODO - return VmMetaData.UsbSpeed.NONE; - } - -} diff --git a/src/main/java/org/openslx/util/vm/UnsupportedVirtualizerFormatException.java b/src/main/java/org/openslx/util/vm/UnsupportedVirtualizerFormatException.java deleted file mode 100644 index 08c9673..0000000 --- a/src/main/java/org/openslx/util/vm/UnsupportedVirtualizerFormatException.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.openslx.util.vm; - -@SuppressWarnings( "serial" ) -public class UnsupportedVirtualizerFormatException extends Exception -{ - public UnsupportedVirtualizerFormatException(String message) { - super(message); - } -}
\ No newline at end of file diff --git a/src/main/java/org/openslx/util/vm/VboxConfig.java b/src/main/java/org/openslx/util/vm/VboxConfig.java deleted file mode 100644 index e9870a5..0000000 --- a/src/main/java/org/openslx/util/vm/VboxConfig.java +++ /dev/null @@ -1,628 +0,0 @@ -package org.openslx.util.vm; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.XMLConstants; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpression; -import javax.xml.xpath.XPathExpressionException; - -import org.apache.log4j.Logger; -import org.openslx.util.Util; -import org.openslx.util.XmlHelper; -import org.openslx.util.vm.VmMetaData.DriveBusType; -import org.openslx.util.vm.VmMetaData.HardDisk; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** - * Class handling the parsing of a .vbox machine description file - */ -public class VboxConfig -{ - private static final Logger LOGGER = Logger.getLogger( VboxConfig.class ); - - // key information set during initial parsing of the XML file - private String osName = new String(); - private ArrayList<HardDisk> hddsArray = new ArrayList<HardDisk>(); - - // XPath and DOM parsing related members - private Document doc = null; - - // list of nodes to automatically remove when reading the vbox file - private static String[] blacklist = { - "/VirtualBox/Machine/Hardware/GuestProperties", - "/VirtualBox/Machine/Hardware/VideoCapture", - "/VirtualBox/Machine/Hardware/HID", - "/VirtualBox/Machine/Hardware/LPT", - "/VirtualBox/Machine/Hardware/SharedFolders", - "/VirtualBox/Machine/Hardware/Network/Adapter[@enabled='true']/*", - "/VirtualBox/Machine/ExtraData", - "/VirtualBox/Machine/StorageControllers/StorageController/AttachedDevice[not(@type='HardDisk')]", - "/VirtualBox/Machine/MediaRegistry/FloppyImages", - "/VirtualBox/Machine/MediaRegistry/DVDImages" }; - - public static enum PlaceHolder - { - FLOPPYUUID( "%VM_FLOPPY_UUID%" ), FLOPPYLOCATION( "%VM_FLOPPY_LOCATION%" ), CPU( "%VM_CPU_CORES%" ), MEMORY( "%VM_RAM%" ), MACHINEUUID( "%VM_MACHINE_UUID%" ), NETWORKMAC( - "%VM_NIC_MAC%" ), HDDLOCATION( "%VM_HDD_LOCATION%" ), HDDUUID( "%VM_HDD_UUID_" ); - - private final String holderName; - - private PlaceHolder( String name ) - { - this.holderName = name; - } - - @Override - public String toString() - { - return holderName; - } - } - - /** - * Creates a vbox configuration by constructing a DOM from the given VirtualBox machine - * configuration file. - * Will validate the given file against the VirtualBox XSD schema and only proceed if it is - * valid. - * - * @param file the VirtualBox machine configuration file - * @throws IOException if an error occurs while reading the file - * @throws UnsupportedVirtualizerFormatException if the given file is not a valid VirtualBox - * configuration file. - */ - public VboxConfig( File file ) throws IOException, UnsupportedVirtualizerFormatException - { - // first validate xml - try { - SchemaFactory factory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); - InputStream xsdStream = VboxConfig.class.getResourceAsStream( "/master-sync-shared/xml/VirtualBox-settings.xsd" ); - if ( xsdStream == null ) { - LOGGER.warn( "Cannot validate Vbox XML: No XSD found in JAR" ); - } else { - Schema schema = factory.newSchema( new StreamSource( xsdStream ) ); - Validator validator = schema.newValidator(); - validator.validate( new StreamSource( file ) ); - } - } catch ( SAXException e ) { - LOGGER.error( "Selected vbox file was not validated against the XSD schema: " + e.getMessage() ); - } - // valid xml, try to create the DOM - doc = XmlHelper.parseDocumentFromStream( new FileInputStream( file ) ); - doc = XmlHelper.removeFormattingNodes( doc ); - if ( doc == null ) - throw new UnsupportedVirtualizerFormatException( "Could not create DOM from given VirtualBox machine configuration file!" ); - init(); - } - - /** - * Creates an vbox configuration by constructing a DOM from the XML content given as a byte - * array. - * - * @param machineDescription content of the XML file saved as a byte array. - * @param length of the machine description byte array. - * @throws IOException if an - */ - public VboxConfig( byte[] machineDescription, int length ) throws UnsupportedVirtualizerFormatException - { - ByteArrayInputStream is = new ByteArrayInputStream( machineDescription ); - doc = XmlHelper.parseDocumentFromStream( is ); - if ( doc == null ) { - LOGGER.error( "Failed to create a DOM from given machine description." ); - throw new UnsupportedVirtualizerFormatException( "Could not create DOM from given machine description as. byte array." ); - } - init(); - } - - /** - * Main initialization functions parsing the document created during the constructor. - * @throws UnsupportedVirtualizerFormatException - */ - private void init() throws UnsupportedVirtualizerFormatException - { - if ( Util.isEmptyString( getDisplayName() ) ) { - throw new UnsupportedVirtualizerFormatException( "Machine doesn't have a name" ); - } - try { - ensureHardwareUuid(); - setOsType(); - fixUsb(); // Since we now support selecting specific speed - if ( checkForPlaceholders() ) { - return; - } - setHdds(); - removeBlacklistedElements(); - addPlaceHolders(); - } catch ( XPathExpressionException e ) { - LOGGER.debug( "Could not initialize VBoxConfig", e ); - return; - } - } - - private void fixUsb() - { - NodeList list = findNodes( "/VirtualBox/Machine/Hardware/USB/Controllers/Controller" ); - if ( list != null && list.getLength() != 0 ) { - LOGGER.info( "USB present, not fixing anything" ); - return; - } - // If there's no USB section, this can mean two things: - // 1) Old config that would always default to USB 2.0 for "USB enabled" or nothing for disabled - // 2) New config with USB disabled - list = findNodes( "/VirtualBox/OpenSLX/USB[@disabled]" ); - if ( list != null && list.getLength() != 0 ) { - LOGGER.info( "USB explicitly disabled" ); - return; // Explicitly marked as disabled, do nothing - } - // We assume case 1) and add USB 2.0 - LOGGER.info( "Fixing USB: Adding USB 2.0" ); - Element controller; - Element node = createNodeRecursive( "/VirtualBox/Machine/Hardware/USB/Controllers" ); - controller = addNewNode( node, "Controller" ); - controller.setAttribute( "name", "OHCI" ); - controller.setAttribute( "type", "OHCI" ); - controller = addNewNode( node, "Controller" ); - controller.setAttribute( "name", "EHCI" ); - controller.setAttribute( "type", "EHCI" ); - } - - /** - * Saves the machine's uuid as hardware uuid to prevent VMs from - * believing in a hardware change. - * - * @throws XPathExpressionException - * @throws UnsupportedVirtualizerFormatException - */ - private void ensureHardwareUuid() throws XPathExpressionException, UnsupportedVirtualizerFormatException - { - // we will need the machine uuid, so get it - String machineUuid = XmlHelper.XPath.compile( "/VirtualBox/Machine/@uuid" ).evaluate( this.doc ); - if ( machineUuid.isEmpty() ) { - LOGGER.error( "Machine UUID empty, should never happen!" ); - throw new UnsupportedVirtualizerFormatException( "XML doesn't contain a machine uuid" ); - } - - NodeList hwNodes = findNodes( "/VirtualBox/Machine/Hardware" ); - int count = hwNodes.getLength(); - if ( count != 1 ) { - throw new UnsupportedVirtualizerFormatException( "Zero or more '/VirtualBox/Machine/Hardware' node were found, should never happen!" ); - } - Element hw = (Element)hwNodes.item( 0 ); - String hwUuid = hw.getAttribute( "uuid" ); - if ( !hwUuid.isEmpty() ) { - LOGGER.info( "Found hardware uuid: " + hwUuid ); - return; - } else { - if ( !addAttributeToNode( hw, "uuid", machineUuid ) ) { - LOGGER.error( "Failed to set machine UUID '" + machineUuid + "' as hardware UUID." ); - return; - } - LOGGER.info( "Saved machine UUID as hardware UUID." ); - } - } - - /** - * Self-explanatory. - */ - public void addPlaceHolders() - { - // placeholder for the machine uuid - changeAttribute( "/VirtualBox/Machine", "uuid", PlaceHolder.MACHINEUUID.toString() ); - - // placeholder for the location of the virtual hdd - changeAttribute( "/VirtualBox/Machine/MediaRegistry/HardDisks/HardDisk", "location", PlaceHolder.HDDLOCATION.toString() ); - - // placeholder for the memory - changeAttribute( "/VirtualBox/Machine/Hardware/Memory", "RAMSize", PlaceHolder.MEMORY.toString() ); - - // placeholder for the CPU - changeAttribute( "/VirtualBox/Machine/Hardware/CPU", "count", PlaceHolder.CPU.toString() ); - - // placeholder for the MACAddress - changeAttribute( "/VirtualBox/Machine/Hardware/Network/Adapter", "MACAddress", PlaceHolder.NETWORKMAC.toString() ); - - NodeList hdds = findNodes( "/VirtualBox/Machine/MediaRegistry/HardDisks/HardDisk" ); - for ( int i = 0; i < hdds.getLength(); i++ ) { - Element hdd = (Element)hdds.item( i ); - if ( hdd == null ) - continue; - String hddUuid = hdd.getAttribute( "uuid" ); - hdd.setAttribute( "uuid", PlaceHolder.HDDUUID.toString() + i + "%" ); - NodeList images = findNodes( "/VirtualBox/Machine/StorageControllers/StorageController/AttachedDevice/Image" ); - for ( int j = 0; j < images.getLength(); j++ ) { - Element image = (Element)images.item( j ); - if ( image == null ) - continue; - if ( hddUuid.equals( image.getAttribute( "uuid" ) ) ) { - image.setAttribute( "uuid", PlaceHolder.HDDUUID.toString() + i + "%" ); - break; - } - } - } - } - - /** - * Function checks if the placeholders are present - * - * @return true if the placeholders are present, false otherwise - */ - private boolean checkForPlaceholders() - { - // TODO this should be more robust... - NodeList hdds = findNodes( "/VirtualBox/Machine/MediaRegistry/HardDisks/HardDisk" ); - for ( int i = 0; i < hdds.getLength(); i++ ) { - Element hdd = (Element)hdds.item( i ); - if ( hdd == null ) - continue; - if ( hdd.getAttribute( "location" ).equals( PlaceHolder.HDDLOCATION.toString() ) ) { - return true; - } - } - return false; - } - - /** - * Called during init(), prunes the DOM from the elements blacklisted defined - * in the member blacklist, a list of XPath expressions as String - * - * @throws XPathExpressionException - */ - private void removeBlacklistedElements() throws XPathExpressionException - { - // iterate over the blackList - for ( String blackedTag : blacklist ) { - XPathExpression blackedExpr = XmlHelper.XPath.compile( blackedTag ); - NodeList blackedNodes = (NodeList)blackedExpr.evaluate( this.doc, XPathConstants.NODESET ); - for ( int i = 0; i < blackedNodes.getLength(); i++ ) { - // go through the child nodes of the blacklisted ones -> why? - Element child = (Element)blackedNodes.item( i ); - removeNode( child ); - } - } - } - - /** - * Getter for the display name - * - * @return the display name of this VM - */ - public String getDisplayName() - { - try { - return XmlHelper.XPath.compile( "/VirtualBox/Machine/@name" ).evaluate( this.doc ); - } catch ( XPathExpressionException e ) { - return ""; - } - } - - /** - * Function finds and saves the name of the guest OS - * - * @throws XPathExpressionException - */ - public void setOsType() throws XPathExpressionException - { - String os = XmlHelper.XPath.compile( "/VirtualBox/Machine/@OSType" ).evaluate( this.doc ); - if ( os != null && !os.isEmpty() ) { - osName = os; - } - } - - /** - * Getter for the parsed guest OS name - * - * @return name of the guest OS - */ - public String getOsName() - { - return osName; - } - - /** - * Search for attached hard drives and determine their controller and their path. - * - * @throws XPathExpressionException - */ - public void setHdds() throws XPathExpressionException - { - XPathExpression hddsExpr = XmlHelper.XPath.compile( "/VirtualBox/Machine/StorageControllers/StorageController/AttachedDevice[@type='HardDisk']/Image" ); - NodeList nodes = (NodeList)hddsExpr.evaluate( this.doc, XPathConstants.NODESET ); - if ( nodes == null ) { - LOGGER.error( "Failed to find attached hard drives." ); - return; - } - for ( int i = 0; i < nodes.getLength(); i++ ) { - Element hddElement = (Element)nodes.item( i ); - if ( hddElement == null ) - continue; - String uuid = hddElement.getAttribute( "uuid" ); - if ( uuid.isEmpty() ) - continue; - // got uuid, check if it was registered - XPathExpression hddsRegistered = XmlHelper.XPath.compile( "/VirtualBox/Machine/MediaRegistry/HardDisks/HardDisk[@uuid='" + uuid + "']" ); - NodeList hddsRegisteredNodes = (NodeList)hddsRegistered.evaluate( this.doc, XPathConstants.NODESET ); - if ( hddsRegisteredNodes == null || hddsRegisteredNodes.getLength() != 1 ) { - LOGGER.error( "Found hard disk with uuid '" + uuid + "' which does not appear (unique) in the Media Registry. Skipping." ); - continue; - } - Element hddElementReg = (Element)hddsRegisteredNodes.item( 0 ); - if ( hddElementReg == null ) - continue; - String fileName = hddElementReg.getAttribute( "location" ); - String type = hddElementReg.getAttribute( "type" ); - if ( !type.equals( "Normal" ) && !type.equals( "Writethrough" ) ) { - LOGGER.warn( "Type of the disk file is neither 'Normal' nor 'Writethrough' but: " + type ); - LOGGER.warn( "This makes the image not directly modificable, which might lead to problems when editing it locally." ); - } - // search if it is also attached to a controller - Node hddDevice = hddElement.getParentNode(); - if ( hddDevice == null ) { - LOGGER.error( "HDD node had a null parent, shouldn't happen" ); - continue; - } - Element hddController = (Element)hddDevice.getParentNode(); - if ( hddController == null ) { - LOGGER.error( "HDD node had a null parent, shouldn't happen" ); - continue; - } - String controllerMode = hddController.getAttribute( "type" ); - String controllerType = hddController.getAttribute( "name" ); - DriveBusType busType = null; - if ( controllerType.equals( "IDE" ) ) { - busType = DriveBusType.IDE; - } else if ( controllerType.equals( "SCSI" ) ) { - busType = DriveBusType.SCSI; - } else if ( controllerType.equals( "SATA" ) ) { - busType = DriveBusType.SATA; - } else - continue; - LOGGER.info( "Adding hard disk with controller: " + busType + " (" + controllerMode + ") from file '" + fileName + "'." ); - hddsArray.add( new HardDisk( controllerMode, busType, fileName ) ); - } - } - - /** - * Getter for the list of detected hard drives. - * - * @return list of disk drives. - */ - public ArrayList<HardDisk> getHdds() - { - return hddsArray; - } - - /** - * Detect if the vbox file has any machine snapshot by looking at - * the existance of '/VirtualBox/Machine/Snapshot' elements. - * - * @return true if a machine snapshot is present, false otherwise. - */ - public boolean isMachineSnapshot() - { - // check if the vbox configuration file contains some machine snapshots. - // by looking at the existance of /VirtualBox/Machine/Snapshot - NodeList machineSnapshots = findNodes( "/VirtualBox/Machine/Snapshot" ); - return machineSnapshots != null && machineSnapshots.getLength() > 0; - } - - /** - * Searches the DOM for the elements matching the given XPath expression. - * - * @param xpath expression to search the DOM with - * @return nodes found by evaluating given XPath expression - */ - public NodeList findNodes( String xpath ) - { - NodeList nodes = null; - try { - XPathExpression expr = XmlHelper.XPath.compile( xpath ); - Object nodesObject = expr.evaluate( this.doc, XPathConstants.NODESET ); - nodes = (NodeList)nodesObject; - } catch ( XPathExpressionException e ) { - LOGGER.error( "Could not build path", e ); - } - return nodes; - } - - /** - * Function used to change the value of an attribute of given element. - * The given xpath to the element needs to find a single node, or this function will return - * false. If only one element was found, it will return the result of calling addAttributeToNode. - * Note that due to the way setAttribute() works, this function to create the attribute if it - * doesn't exists. - * - * @param elementXPath given as an xpath expression - * @param attribute attribute to change - * @param value to set the attribute to - */ - public boolean changeAttribute( String elementXPath, String attribute, String value ) - { - NodeList nodes = findNodes( elementXPath ); - if ( nodes == null || nodes.getLength() != 1 ) { - LOGGER.error( "No unique node could be found for: " + elementXPath ); - return false; - } - return addAttributeToNode( nodes.item( 0 ), attribute, value ); - } - - /** - * Add given attribute with given value to the given node. - * NOTE: this will overwrite the attribute of the node if it already exists. - * - * @param node to add the attribute to - * @param attribute attribute to add to the node - * @param value of the attribute - * @return true if successful, false otherwise - */ - public boolean addAttributeToNode( Node node, String attribute, String value ) - { - if ( node == null || node.getNodeType() != Node.ELEMENT_NODE ) { - LOGGER.error( "Trying to change attribute of a non element node!" ); - return false; - } - try { - ( (Element)node ).setAttribute( attribute, value ); - } catch ( DOMException e ) { - LOGGER.error( "Failed set '" + attribute + "' to '" + value + "' of xml node '" + node.getNodeName() + "': ", e ); - return false; - } - return true; - } - - /** - * Adds a new node named nameOfNewNode to the given parent found by parentXPath. - * - * @param parentXPath XPath expression to the parent - * @param nameOfnewNode name of the node to be added - * @return the newly added Node - */ - public Node addNewNode( String parentXPath, String childName ) - { - NodeList possibleParents = findNodes( parentXPath ); - if ( possibleParents == null || possibleParents.getLength() != 1 ) { - LOGGER.error( "Could not find unique parent node to add new node to: " + parentXPath ); - return null; - } - return addNewNode( possibleParents.item( 0 ), childName ); - } - - public Element createNodeRecursive( String xPath ) - { - String[] nodeNames = xPath.split( "/" ); - Node parent = this.doc; - Element latest = null; - for ( int nodeIndex = 0; nodeIndex < nodeNames.length; ++nodeIndex ) { - if ( nodeNames[nodeIndex].length() == 0 ) - continue; - Node node = skipNonElementNodes( parent.getFirstChild() ); - while ( node != null ) { - if ( node.getNodeType() == Node.ELEMENT_NODE && nodeNames[nodeIndex].equals( node.getNodeName() ) ) - break; // Found existing - // Check next on same level - node = skipNonElementNodes( node.getNextSibling() ); - } - if ( node == null ) { - node = doc.createElement( nodeNames[nodeIndex] ); - parent.appendChild( node ); - } - parent = node; - latest = (Element)node; - } - return latest; - } - - private Element skipNonElementNodes( Node nn ) - { - while ( nn != null && nn.getNodeType() != Node.ELEMENT_NODE ) { - nn = nn.getNextSibling(); - } - return (Element)nn; - } - - public void setExtraData( String key, String value ) - { - NodeList nl = findNodes( "/VirtualBox/Machine/ExtraData/ExtraDataItem[@name='" + key + "']" ); - Element e = null; - for ( int i = 0; i < nl.getLength(); ++i ) { - Node n = nl.item( i ); - if ( n.getNodeType() == Node.ELEMENT_NODE ) { - e = (Element)n; - break; - } - } - if ( e == null ) { - Element p = createNodeRecursive( "/VirtualBox/Machine/ExtraData" ); - e = addNewNode( p, "ExtraDataItem" ); - e.setAttribute( "name", key ); - } - e.setAttribute( "value", value ); - } - - /** - * Creates a new element to the given parent node. - * - * @param parent to add the new element to - * @param childName name of the new element to create - * @return the newly created node - */ - public Element addNewNode( Node parent, String childName ) - { - if ( parent == null || parent.getNodeType() != Node.ELEMENT_NODE ) { - return null; - } - Element newNode = null; - try { - newNode = doc.createElement( childName ); - parent.appendChild( newNode ); - } catch ( DOMException e ) { - LOGGER.error( "Failed to add '" + childName + "' to '" + parent.getNodeName() + "'." ); - } - return newNode; - } - - /** - * Helper to remove given node from the DOM. - * - * @param node Node object to remove. - */ - private void removeNode( Node node ) - { - if ( node == null ) - return; - Node parent = node.getParentNode(); - if ( parent != null ) - parent.removeChild( node ); - } - - /** - * Helper to output the DOM as a String. - * - * @param prettyPrint sets whether to indent the output - * @return (un-)formatted XML - */ - public String toString( boolean prettyPrint ) - { - return XmlHelper.getXmlFromDocument( doc, prettyPrint ); - } - - /** - * Remove all nodes with name childName from parentPath - * @param parentPath XPath to parent node of where child nodes are to be deleted - * @param childName Name of nodes to delete - */ - public void removeNodes( String parentPath, String childName ) - { - NodeList parentNodes = findNodes( parentPath ); - // XPath might match multiple nodes - for ( int i = 0; i < parentNodes.getLength(); ++i ) { - Node parent = parentNodes.item( i ); - List<Node> delList = new ArrayList<>( 0 ); - // Iterate over child nodes - for ( Node child = parent.getFirstChild(); child != null; child = child.getNextSibling() ) { - if ( childName.equals( child.getNodeName() ) ) { - // Remember all to be deleted (don't delete while iterating) - delList.add( child ); - } - } - // Now delete them all - for ( Node child : delList ) { - parent.removeChild( child ); - } - } - } -} diff --git a/src/main/java/org/openslx/util/vm/VboxMetaData.java b/src/main/java/org/openslx/util/vm/VboxMetaData.java deleted file mode 100644 index da5189e..0000000 --- a/src/main/java/org/openslx/util/vm/VboxMetaData.java +++ /dev/null @@ -1,521 +0,0 @@ -package org.openslx.util.vm; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.List; -import java.util.Map.Entry; -import java.util.UUID; - -import org.apache.log4j.Logger; -import org.openslx.bwlp.thrift.iface.OperatingSystem; -import org.openslx.bwlp.thrift.iface.Virtualizer; -import org.openslx.thrifthelper.TConst; -import org.openslx.util.vm.VboxConfig.PlaceHolder; -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -class VBoxSoundCardMeta -{ - public final boolean isPresent; - public final String value; - - public VBoxSoundCardMeta( boolean present, String val ) - { - isPresent = present; - value = val; - } -} - -class VBoxDDAccelMeta -{ - public final boolean isPresent; - - public VBoxDDAccelMeta( boolean present ) - { - isPresent = present; - } -} - -class VBoxHWVersionMeta -{ - public final int version; - - public VBoxHWVersionMeta( int vers ) - { - version = vers; - } -} - -class VBoxEthernetDevTypeMeta -{ - public final String value; - public final boolean isPresent; - - public VBoxEthernetDevTypeMeta( boolean present, String val ) - { - value = val; - isPresent = present; - } -} - -class VBoxUsbSpeedMeta -{ - public final String value; - public final int speed; - public VBoxUsbSpeedMeta( String value, int speed ) - { - this.value = value; - this.speed = speed; - } -} - -public class VboxMetaData extends VmMetaData<VBoxSoundCardMeta, VBoxDDAccelMeta, VBoxHWVersionMeta, VBoxEthernetDevTypeMeta, VBoxUsbSpeedMeta> -{ - private static final Logger LOGGER = Logger.getLogger( VboxMetaData.class ); - - private static final Virtualizer virtualizer = new Virtualizer( TConst.VIRT_VIRTUALBOX, "VirtualBox" ); - - private final VboxConfig config; - - public static enum EthernetType - { - NAT( "vboxnet1" ), BRIDGED( "vboxnet0" ), HOST_ONLY( "vboxnet2" ); - - public final String vnet; - - private EthernetType( String vnet ) - { - this.vnet = vnet; - } - } - - public VboxMetaData( List<OperatingSystem> osList, File file ) throws IOException, UnsupportedVirtualizerFormatException - { - super( osList ); - this.config = new VboxConfig( file ); - init(); - } - - public VboxMetaData( List<OperatingSystem> osList, byte[] vmContent, int length ) throws IOException, UnsupportedVirtualizerFormatException - { - super( osList ); - this.config = new VboxConfig( vmContent, length ); - init(); - } - - private void init() - { - registerVirtualHW(); - displayName = config.getDisplayName(); - setOs( config.getOsName() ); - this.isMachineSnapshot = config.isMachineSnapshot(); - for ( HardDisk hardDisk : config.getHdds() ) { - hdds.add( hardDisk ); - } - } - - @Override - public Virtualizer getVirtualizer() - { - return virtualizer; - } - - @Override - public void applySettingsForLocalEdit() - { - // TODO Auto-generated method stub - } - - @Override - public byte[] getDefinitionArray() - { - return config.toString( false ).getBytes( StandardCharsets.UTF_8 ); - } - - @Override - public byte[] getFilteredDefinitionArray() - { - return config.toString( false ).getBytes( StandardCharsets.UTF_8 ); - } - - @Override - public boolean addHddTemplate( String diskImage, String hddMode, String redoDir ) - { - config.changeAttribute( "/VirtualBox/Machine/MediaRegistry/HardDisks/HardDisk[@location='" + PlaceHolder.HDDLOCATION.toString() + "']", "location", diskImage ); - config.changeAttribute( "/VirtualBox/Machine", "snapshotFolder", redoDir ); - return true; - } - - @Override - public boolean addHddTemplate( File diskImage, String hddMode, String redoDir ) - { - String diskImagePath = diskImage.getName(); - config.changeAttribute( "/VirtualBox/Machine/MediaRegistry/HardDisks/HardDisk", "location", diskImagePath ); - - UUID newhdduuid = UUID.randomUUID(); - - // patching the new uuid in the vbox config file here - String vboxUUid = "{" + newhdduuid.toString() + "}"; - config.changeAttribute( "/VirtualBox/Machine/MediaRegistry/HardDisks/HardDisk", "uuid", vboxUUid ); - config.changeAttribute( "/VirtualBox/Machine/StorageControllers/StorageController/AttachedDevice/Image", "uuid", vboxUUid ); - - // the order of the UUID is BIG_ENDIAN but we need to change the order of the first 8 Bytes - // to be able to write them to the vdi file... the PROBLEM here is that the first 8 - // are in LITTLE_ENDIAN order in pairs of 4-2-2 not the whole 8 so just changing the - // order when we are adding them to the bytebuffer won't help - // - // the following is a workaround that works - ByteBuffer buffer = ByteBuffer.wrap( new byte[ 16 ] ); - buffer.putLong( newhdduuid.getMostSignificantBits() ); - buffer.putLong( newhdduuid.getLeastSignificantBits() ); - byte[] oldOrder = buffer.array(); - // make a coppy here because the last 8 Bytes don't need to change position - byte[] bytesToWrite = Arrays.copyOf( oldOrder, oldOrder.length ); - // use an offset int[] to help with the shuffle - int[] offsets = { 3, 2, 1, 0, 5, 4, 7, 6 }; - for ( int index = 0; index < 8; index++ ) { - bytesToWrite[index] = oldOrder[offsets[index]]; - } - try ( RandomAccessFile file = new RandomAccessFile( diskImage, "rw" ) ) { - file.seek( 392 ); - file.write( bytesToWrite, 0, 16 ); - } catch ( Exception e ) { - LOGGER.warn( "could not patch new uuid in the vdi", e ); - } - - // we need a new machine uuid - UUID newMachineUuid = UUID.randomUUID(); - if ( newMachineUuid.equals( newhdduuid ) ) { - LOGGER.warn( "The new Machine UUID is the same as the new HDD UUID; tying again...this vm might not start" ); - newMachineUuid = UUID.randomUUID(); - } - String machineUUid = "{" + newMachineUuid.toString() + "}"; - return config.changeAttribute( "/VirtualBox/Machine", "uuid", machineUUid ); - } - - @Override - public boolean addDefaultNat() - { - if ( config.addNewNode( "/VirtualBox/Machine/Hardware/Network/Adapter", "NAT" ) == null ) { - LOGGER.error( "Failed to set network adapter to NAT." ); - return false; - } - return config.changeAttribute( "/VirtualBox/Machine/Hardware/Network/Adapter", "MACAddress", "080027B86D12" ); - } - - @Override - public void setOs( String vendorOsId ) - { - config.changeAttribute( "/VirtualBox/Machine", "OSType", vendorOsId ); - setOs( TConst.VIRT_VIRTUALBOX, vendorOsId ); - } - - @Override - public boolean addDisplayName( String name ) - { - return config.changeAttribute( "/VirtualBox/Machine", "name", name ); - } - - @Override - public boolean addRam( int mem ) - { - return config.changeAttribute( "/VirtualBox/Machine/Hardware/Memory", "RAMSize", Integer.toString( mem ) ); - } - - @Override - public void addFloppy( int index, String image, boolean readOnly ) - { - Element floppyController = null; - NodeList matches = (NodeList)config.findNodes( "/VirtualBox/Machine/StorageControllers/StorageController[@name='Floppy']" ); - if ( matches == null || matches.getLength() == 0 ) { - floppyController = (Element)config.addNewNode( "/VirtualBox/Machine/StorageControllers", "StorageController" ); - if ( floppyController == null ) { - LOGGER.error( "Failed to add <Image> to floppy device." ); - return; - } - floppyController.setAttribute( "name", "Floppy" ); - floppyController.setAttribute( "type", "I82078" ); - floppyController.setAttribute( "PortCount", "1" ); - floppyController.setAttribute( "useHostIOCache", "true" ); - floppyController.setAttribute( "Bootable", "false" ); - } - // virtualbox only allows one controller per type - if ( matches.getLength() > 1 ) { - LOGGER.error( "Multiple floppy controllers detected, this should never happen! " ); - return; - } - // so if we had any matches, we know we have exactly one - if ( floppyController == null ) - floppyController = (Element)matches.item( 0 ); - - // add the floppy device - Element floppyDevice = (Element)config.addNewNode( floppyController, "AttachedDevice" ); - if ( floppyDevice == null ) { - LOGGER.error( "Failed to add <Image> to floppy device." ); - return; - } - floppyDevice.setAttribute( "type", "Floppy" ); - floppyDevice.setAttribute( "hotpluggable", "false" ); - floppyDevice.setAttribute( "port", "0" ); - floppyDevice.setAttribute( "device", Integer.toString( index ) ); - - // finally add the image to it, if one was given - if ( image != null ) { - Element floppyImage = (Element)config.addNewNode( floppyDevice, "Image" ); - if ( floppyImage == null ) { - LOGGER.error( "Failed to add <Image> to floppy device." ); - return; - } - floppyImage.setAttribute( "uuid", VboxConfig.PlaceHolder.FLOPPYUUID.toString() ); - // register the image in the media registry - Element floppyImages = (Element)config.addNewNode( "/VirtualBox/Machine/MediaRegistry", "FloppyImages" ); - if ( floppyImages == null ) { - LOGGER.error( "Failed to add <FloppyImages> to media registry." ); - return; - } - Element floppyImageReg = (Element)config.addNewNode( "/VirtualBox/Machine/MediaRegistry/FloppyImages", "Image" ); - if ( floppyImageReg == null ) { - LOGGER.error( "Failed to add <Image> to floppy images in the media registry." ); - return; - } - floppyImageReg.setAttribute( "uuid", VboxConfig.PlaceHolder.FLOPPYUUID.toString() ); - floppyImageReg.setAttribute( "location", VboxConfig.PlaceHolder.FLOPPYLOCATION.toString() ); - } - } - - @Override - public boolean addCdrom( String image ) - { - // TODO - done in run-virt currently - return false; - } - - @Override - public boolean addCpuCoreCount( int nrOfCores ) - { - return config.changeAttribute( "/VirtualBox/Machine/Hardware/CPU", "count", Integer.toString( nrOfCores ) ); - } - - @Override - public void setSoundCard( org.openslx.util.vm.VmMetaData.SoundCardType type ) - { - VBoxSoundCardMeta sound = soundCards.get( type ); - config.changeAttribute( "/VirtualBox/Machine/Hardware/AudioAdapter", "enabled", Boolean.toString( sound.isPresent ) ); - config.changeAttribute( "/VirtualBox/Machine/Hardware/AudioAdapter", "controller", sound.value ); - } - - @Override - public VmMetaData.SoundCardType getSoundCard() - { - // initialize here to type None to avoid all null pointer exceptions thrown for unknown user written sound cards - VmMetaData.SoundCardType returnsct = VmMetaData.SoundCardType.NONE; - Element x = (Element)config.findNodes( "/VirtualBox/Machine/Hardware/AudioAdapter" ).item( 0 ); - if ( !x.hasAttribute( "enabled" ) || ( x.hasAttribute( "enabled" ) && x.getAttribute( "enabled" ).equals( "false" ) ) ) { - return returnsct; - } else { - // extra separate case for the non-existing argument} - if ( !x.hasAttribute( "controller" ) ) { - returnsct = VmMetaData.SoundCardType.AC; - } else { - String controller = x.getAttribute( "controller" ); - VBoxSoundCardMeta soundMeta = null; - for ( VmMetaData.SoundCardType type : VmMetaData.SoundCardType.values() ) { - soundMeta = soundCards.get( type ); - if ( soundMeta != null ) { - if ( controller.equals( soundMeta.value ) ) { - returnsct = type; - } - } - } - } - } - return returnsct; - } - - @Override - public void setDDAcceleration( VmMetaData.DDAcceleration type ) - { - VBoxDDAccelMeta accel = ddacc.get( type ); - config.changeAttribute( "/VirtualBox/Machine/Hardware/Display", "accelerate3D", Boolean.toString( accel.isPresent ) ); - } - - @Override - public VmMetaData.DDAcceleration getDDAcceleration() - { - VmMetaData.DDAcceleration returndda = null; - Element x = (Element)config.findNodes( "/VirtualBox/Machine/Hardware/Display" ).item( 0 ); - if ( x.hasAttribute( "accelerate3D" ) ) { - if ( x.getAttribute( "accelerate3D" ).equals( "true" ) ) { - returndda = VmMetaData.DDAcceleration.ON; - } else { - returndda = VmMetaData.DDAcceleration.OFF; - } - } else { - returndda = VmMetaData.DDAcceleration.OFF; - } - return returndda; - } - - /** - * Function does nothing for Virtual Box; - * Virtual Box accepts per default only one hardware version and is hidden from the user - */ - @Override - public void setHWVersion( HWVersion type ) - { - } - - @Override - public VmMetaData.HWVersion getHWVersion() - { - // Virtual Box uses only one virtual hardware version and can't be changed - return VmMetaData.HWVersion.DEFAULT; - } - - @Override - public void setEthernetDevType( int cardIndex, EthernetDevType type ) - { - String index = "0"; - VBoxEthernetDevTypeMeta nic = networkCards.get( type ); - // cardIndex is not used yet...maybe later needed for different network cards - config.changeAttribute( "/VirtualBox/Machine/Hardware/Network/Adapter[@slot='" + index + "']", "enabled", Boolean.toString( nic.isPresent ) ); - config.changeAttribute( "/VirtualBox/Machine/Hardware/Network/Adapter[@slot='" + index + "']", "type", nic.value ); - } - - @Override - public VmMetaData.EthernetDevType getEthernetDevType( int cardIndex ) - { - VmMetaData.EthernetDevType returnedt = VmMetaData.EthernetDevType.NONE; - Element x = (Element)config.findNodes( "/VirtualBox/Machine/Hardware/Network/Adapter" ).item( 0 ); - if ( !x.hasAttribute( "enabled" ) || ( x.hasAttribute( "enabled" ) && x.getAttribute( "enabled" ).equals( "false" ) ) ) { - return returnedt; - } else { - // extra separate case for the non-existing argument} - if ( !x.hasAttribute( "type" ) ) { - returnedt = VmMetaData.EthernetDevType.PCNETFAST3; - } else { - String temp = x.getAttribute( "type" ); - VBoxEthernetDevTypeMeta etherMeta = null; - for ( VmMetaData.EthernetDevType type : VmMetaData.EthernetDevType.values() ) { - etherMeta = networkCards.get( type ); - if ( etherMeta != null ) { - if ( temp.equals( etherMeta.value ) ) { - returnedt = type; - } - } - } - } - } - return returnedt; - } - - public void registerVirtualHW() - { - // none type needs to have a valid value; it takes the value of AC97; if value is left null or empty vm will not start because value is not valid - // TODO: Maybe just remove the entire section from the XML? Same for ethernet... - soundCards.put( VmMetaData.SoundCardType.NONE, new VBoxSoundCardMeta( false, "AC97" ) ); - soundCards.put( VmMetaData.SoundCardType.SOUND_BLASTER, new VBoxSoundCardMeta( true, "SB16" ) ); - soundCards.put( VmMetaData.SoundCardType.HD_AUDIO, new VBoxSoundCardMeta( true, "HDA" ) ); - soundCards.put( VmMetaData.SoundCardType.AC, new VBoxSoundCardMeta( true, "AC97" ) ); - - ddacc.put( VmMetaData.DDAcceleration.OFF, new VBoxDDAccelMeta( false ) ); - ddacc.put( VmMetaData.DDAcceleration.ON, new VBoxDDAccelMeta( true ) ); - - hwversion.put( VmMetaData.HWVersion.DEFAULT, new VBoxHWVersionMeta( 0 ) ); - - // none type needs to have a valid value; it takes the value of pcnetcpi2; if value is left null or empty vm will not start because value is not valid - networkCards.put( VmMetaData.EthernetDevType.NONE, new VBoxEthernetDevTypeMeta( false, "Am79C970A" ) ); - networkCards.put( VmMetaData.EthernetDevType.PCNETPCI2, new VBoxEthernetDevTypeMeta( true, "Am79C970A" ) ); - networkCards.put( VmMetaData.EthernetDevType.PCNETFAST3, new VBoxEthernetDevTypeMeta( true, "Am79C973" ) ); - networkCards.put( VmMetaData.EthernetDevType.PRO1000MTD, new VBoxEthernetDevTypeMeta( true, "82540EM" ) ); - networkCards.put( VmMetaData.EthernetDevType.PRO1000TS, new VBoxEthernetDevTypeMeta( true, "82543GC" ) ); - networkCards.put( VmMetaData.EthernetDevType.PRO1000MTS, new VBoxEthernetDevTypeMeta( true, "82545EM" ) ); - networkCards.put( VmMetaData.EthernetDevType.PARAVIRT, new VBoxEthernetDevTypeMeta( true, "virtio" ) ); - - usbSpeeds.put( VmMetaData.UsbSpeed.NONE, new VBoxUsbSpeedMeta( null, 0 ) ); - usbSpeeds.put( VmMetaData.UsbSpeed.USB1_1, new VBoxUsbSpeedMeta( "OHCI", 1 ) ); - usbSpeeds.put( VmMetaData.UsbSpeed.USB2_0, new VBoxUsbSpeedMeta( "EHCI", 2 ) ); - usbSpeeds.put( VmMetaData.UsbSpeed.USB3_0, new VBoxUsbSpeedMeta( "XHCI", 3 ) ); - } - - @Override - public boolean addEthernet( VmMetaData.EtherType type ) - { - Node hostOnlyInterfaceNode = config.addNewNode( "/VirtualBox/Machine/Hardware/Network/Adapter[@slot='0']", "HostOnlyInterface" ); - if ( hostOnlyInterfaceNode == null ) { - LOGGER.error( "Failed to create node for HostOnlyInterface." ); - return false; - } - return config.addAttributeToNode( hostOnlyInterfaceNode, "name", EthernetType.valueOf( type.name() ).vnet ); - } - - @Override - public boolean tweakForNonPersistent() - { - // Cannot disable suspend - // https://forums.virtualbox.org/viewtopic.php?f=6&t=77169 - // https://forums.virtualbox.org/viewtopic.php?f=8&t=80338 - // But some other stuff that won't make sense in non-persistent mode - config.setExtraData( "GUI/LastCloseAction", "PowerOff" ); - // Could use "Default" instead of "Last" above, but you won't get any confirmation dialog in that case - config.setExtraData( "GUI/RestrictedRuntimeHelpMenuActions", "All" ); - config.setExtraData( "GUI/RestrictedRuntimeMachineMenuActions", "TakeSnapshot,Pause,SaveState" ); - config.setExtraData( "GUI/RestrictedRuntimeMenus", "Help" ); - config.setExtraData( "GUI/PreventSnapshotOperations", "true" ); - config.setExtraData( "GUI/PreventApplicationUpdate", "true" ); - config.setExtraData( "GUI/RestrictedCloseActions", "SaveState,PowerOffRestoringSnapshot,Detach" ); - return true; - } - - @Override - public void setMaxUsbSpeed( VmMetaData.UsbSpeed speed ) - { - // Wipe existing ones - config.removeNodes( "/VirtualBox/Machine/Hardware", "USB" ); - if ( speed == null || speed == VmMetaData.UsbSpeed.NONE ) { - // Add marker so we know it's not an old config and we really want no USB - Element node = config.createNodeRecursive( "/VirtualBox/OpenSLX/USB" ); - if ( node != null ) { - node.setAttribute( "disabled", "true" ); - } - return; // NO USB - } - Element node = config.createNodeRecursive( "/VirtualBox/Machine/Hardware/USB/Controllers/Controller" ); - VBoxUsbSpeedMeta vboxSpeed = usbSpeeds.get( speed ); - node.setAttribute( "type", vboxSpeed.value ); - node.setAttribute( "name", vboxSpeed.value ); - if ( speed == UsbSpeed.USB2_0 ) { - // If EHCI (2.0) is selected, VBox adds an OHCI controller too... - node.setAttribute( "type", "OHCI" ); - node.setAttribute( "name", "OHCI" ); - } - } - - @Override - public VmMetaData.UsbSpeed getMaxUsbSpeed() - { - NodeList nodes = config.findNodes( "/VirtualBox/Machine/Hardware/USB/Controllers/Controller/@type" ); - int maxSpeed = 0; - VmMetaData.UsbSpeed maxItem = VmMetaData.UsbSpeed.NONE; - for ( int i = 0; i < nodes.getLength(); ++i ) { - if ( nodes.item( i ).getNodeType() != Node.ATTRIBUTE_NODE ) { - LOGGER.info( "Not ATTRIBUTE type" ); - continue; - } - String type = ((Attr)nodes.item( i )).getValue(); - for ( Entry<VmMetaData.UsbSpeed, VBoxUsbSpeedMeta> s : usbSpeeds.entrySet() ) { - if ( s.getValue().speed > maxSpeed && type.equals( s.getValue().value ) ) { - maxSpeed = s.getValue().speed; - maxItem = s.getKey(); - } - } - } - return maxItem; - } -} diff --git a/src/main/java/org/openslx/util/vm/VmMetaData.java b/src/main/java/org/openslx/util/vm/VmMetaData.java deleted file mode 100644 index 29e2db9..0000000 --- a/src/main/java/org/openslx/util/vm/VmMetaData.java +++ /dev/null @@ -1,399 +0,0 @@ -package org.openslx.util.vm; - -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.log4j.Logger; -import org.openslx.bwlp.thrift.iface.OperatingSystem; -import org.openslx.bwlp.thrift.iface.Virtualizer; - -/** - * Describes a configured virtual machine. This class is parsed from a machine - * description, like a *.vmx for VMware machines. - */ -public abstract class VmMetaData<T, U, V, W, X> -{ - private static final Logger LOGGER = Logger.getLogger( VmMetaData.class ); - - /* - * Helper types - */ - protected Map<SoundCardType, T> soundCards = new HashMap<>(); - protected Map<DDAcceleration, U> ddacc = new HashMap<>(); - protected Map<HWVersion, V> hwversion = new HashMap<>(); - protected Map<EthernetDevType, W> networkCards = new HashMap<>(); - protected Map<UsbSpeed, X> usbSpeeds = new HashMap<>(); - - /** - * Virtual sound cards types - */ - public static enum SoundCardType - { - NONE( "None" ), DEFAULT( "(default)" ), SOUND_BLASTER( "Sound Blaster 16" ), ES( "ES 1371" ), HD_AUDIO( "Intel Integrated HD Audio" ), AC( "Intel ICH Audio Codec 97" ); - - public final String displayName; - - private SoundCardType( String dName ) - { - this.displayName = dName; - } - } - - /** - * 3D acceleration types - */ - public static enum DDAcceleration - { - OFF( "Off" ), ON( "On" ); - - public final String displayName; - - private DDAcceleration( String dName ) - { - this.displayName = dName; - } - } - - /** - * Virtual hardware version - currently only in use for VMPlayer - */ - public static enum HWVersion - { - NONE( "(invalid)" ), - THREE( " 3 (Workstation 4/5, Player 1)" ), - FOUR( " 4 (Workstation 4/5, Player 1/2, Fusion 1)" ), - SIX( " 6 (Workstation 6)" ), - SEVEN( " 7 (Workstation 6.5/7, Player 3, Fusion 2/3)" ), - EIGHT( " 8 (Workstation 8, Player/Fusion 4)" ), - NINE( " 9 (Workstation 9, Player/Fusion 5)" ), - TEN( "10 (Workstation 10, Player/Fusion 6)" ), - ELEVEN( "11 (Workstation 11, Player/Fusion 7)" ), - TWELVE( "12 (Workstation/Player 12, Fusion 8)" ), - FOURTEEN( "14 (Workstation/Player 14, Fusion 10)"), - FIFTEEN( "15 (Workstation/Player 15, Fusion 11)"), - FIFTEEN_ONE( "16 (Workstation/Player 15.1, Fusion 11.1)"), - DEFAULT( "default" ); - - public final String displayName; - - private HWVersion( String dName ) - { - this.displayName = dName; - } - } - - /** - * Virtual network cards - */ - public static enum EthernetDevType - { - AUTO( "(default)" ), PCNET32( "AMD PCnet32" ), E1000( "Intel E1000 (PCI)" ), E1000E( "Intel E1000e (PCI-Express)" ), VMXNET( "VMXnet" ), VMXNET3( "VMXnet 3" ), PCNETPCI2( - "PCnet-PCI II" ), PCNETFAST3( "PCnet-FAST III" ), PRO1000MTD( "Intel PRO/1000 MT Desktop" ), PRO1000TS( - "Intel PRO/1000 T Server" ), PRO1000MTS( "Intel PRO/1000 MT Server" ), PARAVIRT( "Paravirtualized Network" ), NONE( "No Network Card" ); - - public final String displayName; - - private EthernetDevType( String dName ) - { - this.displayName = dName; - } - } - - public static enum UsbSpeed - { - NONE( "None" ), - USB1_1( "USB 1.1" ), - USB2_0( "USB 2.0" ), - USB3_0( "USB 3.0" ); - - public final String displayName; - - private UsbSpeed( String dName ) - { - this.displayName = dName; - } - } - - public static enum DriveBusType - { - SCSI, IDE, SATA; - } - - public static class HardDisk - { - public final String chipsetDriver; - public final DriveBusType bus; - public final String diskImage; - - public HardDisk( String chipsetDriver, DriveBusType bus, String diskImage ) - { - this.chipsetDriver = chipsetDriver; - this.bus = bus; - this.diskImage = diskImage; - } - } - - public static enum EtherType - { - NAT, BRIDGED, HOST_ONLY; - } - /* - * Members - */ - - protected final List<HardDisk> hdds = new ArrayList<>(); - - private final List<OperatingSystem> osList; - - private OperatingSystem os = null; - - protected String displayName = null; - - protected boolean isMachineSnapshot; - - /* - * Getters for virtual hardware - */ - public List<SoundCardType> getSupportedSoundCards() - { - ArrayList<SoundCardType> availables = new ArrayList<SoundCardType>( soundCards.keySet() ); - Collections.sort( availables ); - return availables; - } - - public List<DDAcceleration> getSupportedDDAccs() - { - ArrayList<DDAcceleration> availables = new ArrayList<DDAcceleration>( ddacc.keySet() ); - Collections.sort( availables ); - return availables; - } - - public List<HWVersion> getSupportedHWVersions() - { - ArrayList<HWVersion> availables = new ArrayList<HWVersion>( hwversion.keySet() ); - Collections.sort( availables ); - return availables; - } - - public List<EthernetDevType> getSupportedEthernetDevices() - { - ArrayList<EthernetDevType> availables = new ArrayList<EthernetDevType>( networkCards.keySet() ); - Collections.sort( availables ); - return availables; - } - - public List<UsbSpeed> getSupportedUsbSpeeds() - { - ArrayList<UsbSpeed> availables = new ArrayList<>( usbSpeeds.keySet() ); - Collections.sort( availables ); - return availables; - } - - /** - * Get operating system of this VM. - */ - public OperatingSystem getOs() - { - return os; - } - - /** - * Get all hard disks of this VM. - */ - public List<HardDisk> getHdds() - { - return Collections.unmodifiableList( hdds ); - } - - /** - * Get display name of VM. - */ - public String getDisplayName() - { - return displayName; - } - - /* - * Getter for isMachineSnapshot - */ - public boolean isMachineSnapshot() - { - return isMachineSnapshot; - } - - /** - * This method should return a minimal representation of the input meta data. - * The representation is platform dependent, and should be stripped of all - * non-essential configuration, such as CD/DVD/FLoppy drives, serial or parallel - * ports, shared folders, or anything else that could be considered sensible - * information (absolute paths containing the local user's name). - */ - public abstract byte[] getFilteredDefinitionArray(); - - public final ByteBuffer getFilteredDefinition() - { - return ByteBuffer.wrap( getFilteredDefinitionArray() ); - } - - /* - * Methods - */ - - public VmMetaData( List<OperatingSystem> osList ) - { - this.osList = osList; - } - - /** - * Called from subclass to set the OS. If the OS cannot be determined from the - * given parameters, it will not be set. - * - * @param virtId - * virtualizer, eg "vmware" for VMware - * @param virtOsId - * the os identifier used by the virtualizer, eg. windows7-64 for - * 64bit Windows 7 on VMware - */ - protected final void setOs( String virtId, String virtOsId ) - { - OperatingSystem lazyMatch = null; - for ( OperatingSystem os : osList ) { - if ( os.getVirtualizerOsId() == null ) - continue; - for ( Entry<String, String> entry : os.getVirtualizerOsId().entrySet() ) { - if ( !entry.getValue().equals( virtOsId ) ) - continue; - if ( entry.getKey().equals( virtId ) ) { - this.os = os; - return; - } else { - lazyMatch = os; - } - } - } - this.os = lazyMatch; - } - - /** - * Apply config options that are desired when locally editing a VM. for vmware, - * this disables automatic DPI scaling of the guest. - */ - public abstract void applySettingsForLocalEdit(); - - /** - * Returns a VmMetaData instance of the given machine description given as file - * - * @param osList List of supported operating systems - * @param file VM's machine description file to get the metadata instance from - * @return VmMetaData object representing the relevant parts of the given machine description - */ - public static VmMetaData<?, ?, ?, ?, ?> getInstance( List<OperatingSystem> osList, File file ) - throws IOException - { - try { - return new VmwareMetaData( osList, file ); - } catch ( UnsupportedVirtualizerFormatException e ) { - LOGGER.info( "Not a VMware file", e ); - } - try { - return new VboxMetaData( osList, file ); - } catch ( UnsupportedVirtualizerFormatException e ) { - LOGGER.info( "Not a VirtualBox file", e ); - } - try { - return new QemuMetaData( osList, file ); - } catch ( Exception e ) { - LOGGER.info( "Not a QEmu file", e ); - } - LOGGER.error( "Could not detect any known virtualizer format" ); - return null; - } - - /** - * Returns a VmMetaData instance of the given machine description given as a byte array - * - * @param osList List of supported operating systems - * @param vmContent VM's machine description as byte array (e.g. stored in DB) - * @param length length of the byte array given as vmContent - * @return VmMetaData object representing the relevant parts of the given machine description - * @throws IOException - */ - public static VmMetaData<?, ?, ?, ?, ?> getInstance( List<OperatingSystem> osList, byte[] vmContent, int length ) throws IOException - { - Map<String, Exception> exceptions = new HashMap<>(); - try { - return new VmwareMetaData( osList, vmContent, length ); - } catch ( UnsupportedVirtualizerFormatException e ) { - exceptions.put( "Not a VMware file", e ); - } - try { - return new VboxMetaData( osList, vmContent, length ); - } catch ( UnsupportedVirtualizerFormatException e ) { - exceptions.put( "Not a VirtualBox file", e ); - } - // TODO QEmu -- hack above expects qcow2 file, so we can't do anything here yet - LOGGER.error( "Could not detect any known virtualizer format" ); - for ( Entry<String, Exception> e : exceptions.entrySet() ) { - LOGGER.error( e.getKey(), e.getValue() ); - } - return null; - } - - public abstract boolean addHddTemplate( File diskImage, String hddMode, String redoDir ); - - public abstract boolean addHddTemplate( String diskImagePath, String hddMode, String redoDir ); - - public abstract boolean addDefaultNat(); - - public abstract void setOs( String vendorOsId ); - - public abstract boolean addDisplayName( String name ); - - public abstract boolean addRam( int mem ); - - public abstract void addFloppy( int index, String image, boolean readOnly ); - - public abstract boolean addCdrom( String image ); - - public abstract boolean addCpuCoreCount( int nrOfCores ); - - public abstract void setSoundCard( SoundCardType type ); - - public abstract SoundCardType getSoundCard(); - - public abstract void setDDAcceleration( DDAcceleration type ); - - public abstract DDAcceleration getDDAcceleration(); - - public abstract void setHWVersion( HWVersion type ); - - public abstract HWVersion getHWVersion(); - - public abstract void setEthernetDevType( int cardIndex, EthernetDevType type ); - - public abstract EthernetDevType getEthernetDevType( int cardIndex ); - - public abstract void setMaxUsbSpeed( UsbSpeed speed ); - - public abstract UsbSpeed getMaxUsbSpeed(); - - public abstract byte[] getDefinitionArray(); - - public abstract boolean addEthernet( EtherType type ); - - public abstract Virtualizer getVirtualizer(); - - public abstract boolean tweakForNonPersistent(); - - /** - * Function used to register virtual devices - */ - public abstract void registerVirtualHW(); -} diff --git a/src/main/java/org/openslx/util/vm/VmwareConfig.java b/src/main/java/org/openslx/util/vm/VmwareConfig.java deleted file mode 100644 index 20ab3ab..0000000 --- a/src/main/java/org/openslx/util/vm/VmwareConfig.java +++ /dev/null @@ -1,273 +0,0 @@ -package org.openslx.util.vm; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; -import org.openslx.util.Util; - -public class VmwareConfig -{ - - private static final Logger LOGGER = Logger.getLogger( VmwareConfig.class ); - - private Map<String, ConfigEntry> entries = new TreeMap<>( String.CASE_INSENSITIVE_ORDER ); - - public VmwareConfig() - { - // (void) - } - - public VmwareConfig( File file ) throws IOException, UnsupportedVirtualizerFormatException - { - int todo = (int)Math.min( 100000, file.length() ); - int offset = 0; - byte[] data = new byte[ todo ]; - FileInputStream fr = null; - try { - fr = new FileInputStream( file ); - while ( todo > 0 ) { - int ret = fr.read( data, offset, todo ); - if ( ret <= 0 ) - break; - todo -= ret; - offset += ret; - } - } finally { - Util.safeClose( fr ); - } - init( data, offset ); - - } - - public VmwareConfig( InputStream is ) throws IOException, UnsupportedVirtualizerFormatException - { - int todo = Math.max( 4000, Math.min( 100000, is.available() ) ); - int offset = 0; - byte[] data = new byte[ todo ]; - while ( todo > 0 ) { - int ret = is.read( data, offset, todo ); - if ( ret <= 0 ) - break; - todo -= ret; - offset += ret; - } - init( data, offset ); - } - - public VmwareConfig( byte[] vmxContent, int length ) throws UnsupportedVirtualizerFormatException - { - init( vmxContent, length ); - } - - // function is used for both .vmx and .vmdk files - private void init( byte[] vmxContent, int length ) throws UnsupportedVirtualizerFormatException - { - try { - boolean isValid = false; - BufferedReader reader = getVmxReader( vmxContent, length ); - String line; - while ( ( line = reader.readLine() ) != null ) { - KeyValuePair entry = parse( line ); - - if ( entry != null ) { - if ( entry.key.equals( "virtualHW.version" ) || entry.key.equals( "ddb.virtualHWVersion" ) ) { - isValid = true; - } - set( entry.key, unescape( entry.value ) ); - } - } - if ( !isValid ) { - throw new UnsupportedVirtualizerFormatException( "Not in VMX format." ); - } - } catch ( IOException e ) { - LOGGER.warn( "Exception when loading vmx from byte array (how!?)", e ); - } - } - - public static BufferedReader getVmxReader( byte[] vmxContent, int length ) throws IOException - { - Charset cs = getCharset( vmxContent, length ); - return new BufferedReader( new InputStreamReader( new ByteArrayInputStream( vmxContent, 0, length ), cs ) ); - } - - public static Charset getCharset( byte[] vmxContent, int length ) - { - String csName = detectCharset( new ByteArrayInputStream( vmxContent, 0, length ) ); - Charset cs = null; - try { - cs = Charset.forName( csName ); - } catch ( Exception e ) { - LOGGER.warn( "Could not instantiate charset " + csName, e ); - } - if ( cs == null ) - cs = StandardCharsets.ISO_8859_1; - return cs; - } - - private String unescape( String value ) - { - String ret = value; - if ( ret.contains( "|22" ) ) { - ret = ret.replace( "|22", "\"" ); - } - if ( ret.contains( "|7C" ) ) { - ret = ret.replace( "|7C", "|" ); - } - return ret; - } - - public static String detectCharset( InputStream is ) - { - try { - BufferedReader csDetectReader = new BufferedReader( new InputStreamReader( is, StandardCharsets.ISO_8859_1 ) ); - String line; - while ( ( line = csDetectReader.readLine() ) != null ) { - KeyValuePair entry = parse( line ); - if ( entry == null ) - continue; - if ( entry.key.equals( ".encoding" ) || entry.key.equals( "encoding" ) ) { - return entry.value; - } - } - } catch ( Exception e ) { - LOGGER.warn( "Could not detect charset, fallback to latin1", e ); - } - // Dumb fallback - return "ISO-8859-1"; - } - - public Set<Entry<String, ConfigEntry>> entrySet() - { - return entries.entrySet(); - } - - private static final Pattern settingMatcher1 = Pattern.compile( "^\\s*(#?[a-z0-9\\.\\:_]+)\\s*=\\s*\"(.*)\"\\s*$", Pattern.CASE_INSENSITIVE ); - private static final Pattern settingMatcher2 = Pattern.compile( "^\\s*(#?[a-z0-9\\.\\:_]+)\\s*=\\s*([^\"]*)\\s*$", Pattern.CASE_INSENSITIVE ); - - private static KeyValuePair parse( String line ) - { - Matcher matcher = settingMatcher1.matcher( line ); - if ( !matcher.matches() ) { - matcher = settingMatcher2.matcher( line ); - } - if ( !matcher.matches() ) { - return null; - } - return new KeyValuePair( matcher.group( 1 ), matcher.group( 2 ) ); - - } - - public ConfigEntry set( String key, String value, boolean replace ) - { - if ( !replace && entries.containsKey( key ) ) - return null; - ConfigEntry ce = new ConfigEntry( value ); - entries.put( key, ce ); - return ce; - } - - public ConfigEntry set( String key, String value ) - { - return set( key, value, true ); - } - - public ConfigEntry set( KeyValuePair entry ) - { - return set( entry.key, entry.value ); - } - - public void remove( String key ) - { - entries.remove( key ); - } - - public String get( String key ) - { - ConfigEntry ce = entries.get( key ); - if ( ce == null ) - return null; - return ce.value; - } - - public String toString( boolean filteredRequired, boolean generatedRequired ) - { - set( ".encoding", "UTF-8" ).filtered( true ).generated( true ); - StringBuilder sb = new StringBuilder( 300 ); - for ( Entry<String, ConfigEntry> entry : entries.entrySet() ) { - ConfigEntry value = entry.getValue(); - if ( ( !filteredRequired || value.forFiltered ) && ( !generatedRequired || value.forGenerated ) ) { - sb.append( entry.getKey() ); - sb.append( " = \"" ); - sb.append( value.getEscaped() ); - sb.append( "\"\n" ); - } - } - return sb.toString(); - } - - @Override - public String toString() - { - return toString( false, false ); - } - - public static class ConfigEntry - { - private String value; - private boolean forFiltered; - private boolean forGenerated; - - public ConfigEntry( String value ) - { - this.value = value; - } - - public ConfigEntry filtered( boolean set ) - { - this.forFiltered = set; - return this; - } - - public ConfigEntry generated( boolean set ) - { - this.forGenerated = set; - return this; - } - - public String getEscaped() - { - String ret = value; - if ( ret.contains( "|" ) ) { - ret = ret.replace( "|", "|7C" ); - } - if ( ret.contains( "\"" ) ) { - ret = ret.replace( "\"", "|22" ); - } - return ret; - } - - public String getValue() - { - return value; - } - - public void setValue( String value ) - { - this.value = value; - } - } -} diff --git a/src/main/java/org/openslx/util/vm/VmwareMetaData.java b/src/main/java/org/openslx/util/vm/VmwareMetaData.java deleted file mode 100644 index 29227a7..0000000 --- a/src/main/java/org/openslx/util/vm/VmwareMetaData.java +++ /dev/null @@ -1,664 +0,0 @@ -package org.openslx.util.vm; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.log4j.Logger; -import org.openslx.bwlp.thrift.iface.OperatingSystem; -import org.openslx.bwlp.thrift.iface.Virtualizer; -import org.openslx.thrifthelper.TConst; -import org.openslx.util.Util; -import org.openslx.util.vm.VmwareConfig.ConfigEntry; - -class VmWareSoundCardMeta -{ - public final boolean isPresent; - public final String value; - - public VmWareSoundCardMeta( boolean present, String val ) - { - isPresent = present; - value = val; - } -} - -class VmWareDDAccelMeta -{ - public final boolean isPresent; - - public VmWareDDAccelMeta( boolean present ) - { - isPresent = present; - } -} - -class VmWareHWVersionMeta -{ - public final int version; - - public VmWareHWVersionMeta( int vers ) - { - version = vers; - } -} - -class VmWareEthernetDevTypeMeta -{ - public final String value; - - public VmWareEthernetDevTypeMeta( String val ) - { - value = val; - } -} - -class VmwareUsbSpeed -{ - public final String keyName; - public final int speedNumeric; - - public VmwareUsbSpeed( int speed, String key ) - { - this.keyName = key + ".present"; - this.speedNumeric = speed; - } -} - -public class VmwareMetaData extends VmMetaData<VmWareSoundCardMeta, VmWareDDAccelMeta, VmWareHWVersionMeta, VmWareEthernetDevTypeMeta, VmwareUsbSpeed> -{ - - private static final Logger LOGGER = Logger.getLogger( VmwareMetaData.class ); - - private static final Virtualizer virtualizer = new Virtualizer( TConst.VIRT_VMWARE, "VMware" ); - - private static final Pattern hddKey = Pattern.compile( "^(ide\\d|scsi\\d|sata\\d):?(\\d)?\\.(.*)", Pattern.CASE_INSENSITIVE ); - - // Lowercase list of allowed settings for upload (as regex) - private static final Pattern[] whitelist; - - private final VmwareConfig config; - - // Init static members - static { - String[] list = { "^guestos", "^uuid\\.bios", "^config\\.version", "^ehci[.:]", "^mks\\.enable3d", "^virtualhw\\.", - "^sound[.:]", "\\.pcislotnumber$", "^pcibridge", "\\.virtualdev$", "^tools\\.syncTime$", "^time\\.synchronize", - "^bios\\.bootDelay", "^rtc\\.", "^xhci[.:]", "^usb_xhci[.:]", "\\.deviceType$", "\\.port$", "\\.parent$", "^usb[.:]", - "^firmware" }; - whitelist = new Pattern[ list.length ]; - for ( int i = 0; i < list.length; ++i ) { - whitelist[i] = Pattern.compile( list[i].toLowerCase() ); - } - } - - public static enum EthernetType - { - NAT( "vmnet1" ), BRIDGED( "vmnet0" ), HOST_ONLY( "vmnet2" ); - - public final String vmnet; - - private EthernetType( String vnet ) - { - this.vmnet = vnet; - } - } - - private final Map<String, Controller> disks = new HashMap<>(); - - public VmwareMetaData( List<OperatingSystem> osList, File file ) throws IOException, UnsupportedVirtualizerFormatException - { - super( osList ); - this.config = new VmwareConfig( file ); - init(); - } - - public VmwareMetaData( List<OperatingSystem> osList, byte[] vmxContent, int length ) throws UnsupportedVirtualizerFormatException - { - super( osList ); - this.config = new VmwareConfig( vmxContent, length ); // still unfiltered - init(); // now filtered - } - - private void init() - { - registerVirtualHW(); - - for ( Entry<String, ConfigEntry> entry : config.entrySet() ) { - handleLoadEntry( entry ); - } - // Fix accidentally filtered USB config if we see EHCI is present - if ( isSetAndTrue( "ehci.present" ) && !isSetAndTrue( "usb.present" ) ) { - addFiltered( "usb.present", "TRUE" ); - } - // if we find this tag, we already went through the hdd's - so we're done. - if ( config.get( "#SLX_HDD_BUS" ) != null ) { - return; - } - // Now find the HDDs and add to list - for ( Entry<String, Controller> cEntry : disks.entrySet() ) { - Controller controller = cEntry.getValue(); - String controllerType = cEntry.getKey(); - if ( !controller.present ) - continue; - for ( Entry<String, Device> dEntry : controller.devices.entrySet() ) { - Device device = dEntry.getValue(); - if ( !device.present ) - continue; // Not present - if ( device.deviceType != null && !device.deviceType.toLowerCase().endsWith( "disk" ) ) - continue; // Not a HDD - DriveBusType bus = null; - if ( controllerType.startsWith( "ide" ) ) { - bus = DriveBusType.IDE; - } else if ( controllerType.startsWith( "scsi" ) ) { - bus = DriveBusType.SCSI; - } else if ( controllerType.startsWith( "sata" ) ) { - bus = DriveBusType.SATA; - } - hdds.add( new HardDisk( controller.virtualDev, bus, device.filename ) ); - } - } - // TODO check if this machine is in a paused/suspended state - this.isMachineSnapshot = false; - - // Add HDD to cleaned vmx - if ( !hdds.isEmpty() ) { - HardDisk hdd = hdds.get( 0 ); - addFiltered( "#SLX_HDD_BUS", hdd.bus.toString() ); - if ( hdd.chipsetDriver != null ) { - addFiltered( "#SLX_HDD_CHIP", hdd.chipsetDriver ); - } - } - } - - private void addFiltered( String key, String value ) - { - config.set( key, value ).filtered( true ); - } - - private boolean isSetAndTrue( String key ) - { - String value = config.get( key ); - return value != null && value.equalsIgnoreCase( "true" ); - } - - private void handleLoadEntry( Entry<String, ConfigEntry> entry ) - { - String lowerKey = entry.getKey().toLowerCase(); - // Cleaned vmx construction - for ( Pattern exp : whitelist ) { - if ( exp.matcher( lowerKey ).find() ) { - entry.getValue().filtered( true ); - break; - } - } - // - // Dig Usable meta data - String value = entry.getValue().getValue(); - if ( lowerKey.equals( "guestos" ) ) { - setOs( value ); - return; - } - if ( lowerKey.equals( "displayname" ) ) { - displayName = value; - return; - } - Matcher hdd = hddKey.matcher( entry.getKey() ); - if ( hdd.find() ) { - handleHddEntry( hdd.group( 1 ).toLowerCase(), hdd.group( 2 ), hdd.group( 3 ), value ); - } - } - - private void handleHddEntry( String controllerStr, String deviceStr, String property, String value ) - { - Controller controller = disks.get( controllerStr ); - if ( controller == null ) { - controller = new Controller(); - disks.put( controllerStr, controller ); - } - if ( deviceStr == null || deviceStr.isEmpty() ) { - // Controller property - if ( property.equalsIgnoreCase( "present" ) ) { - controller.present = Boolean.parseBoolean( value ); - } else if ( property.equalsIgnoreCase( "virtualDev" ) ) { - controller.virtualDev = value; - } - return; - } - // Device property - Device device = controller.devices.get( deviceStr ); - if ( device == null ) { - device = new Device(); - controller.devices.put( deviceStr, device ); - } - if ( property.equalsIgnoreCase( "deviceType" ) ) { - device.deviceType = value; - } else if ( property.equalsIgnoreCase( "filename" ) ) { - device.filename = value; - } else if ( property.equalsIgnoreCase( "present" ) ) { - device.present = Boolean.parseBoolean( value ); - } - } - - @Override - public boolean addHddTemplate( File diskImage, String hddMode, String redoDir ) - { - return addHddTemplate( diskImage.getName(), hddMode, redoDir ); - } - - @Override - public boolean addHddTemplate( String diskImagePath, String hddMode, String redoDir ) - { - if ( diskImagePath.isEmpty() ) { - LOGGER.error( "Empty disk image path given!" ); - return false; - } - DriveBusType bus; - try { - bus = DriveBusType.valueOf( config.get( "#SLX_HDD_BUS" ) ); - } catch ( Exception e ) { - LOGGER.warn( "Unknown bus type: " + config.get( "#SLX_HDD_BUS" ) + ". Cannot add hdd config." ); - return false; - } - String chipset = config.get( "#SLX_HDD_CHIP" ); - String prefix; - switch ( bus ) { - case IDE: - prefix = "ide0:0"; - addFiltered( "ide0.present", "TRUE" ); - break; - case SATA: - // Cannot happen?... use lsisas1068 - case SCSI: - prefix = "scsi0:0"; - addFiltered( "scsi0.present", "TRUE" ); - if ( chipset != null ) { - addFiltered( "scsi0.virtualDev", chipset ); - } - break; - default: - LOGGER.warn( "Unknown HDD bus type: " + bus.toString() ); - return false; - } - // Gen - addFiltered( prefix + ".present", "TRUE" ); - addFiltered( prefix + ".deviceType", "disk" ); - addFiltered( prefix + ".fileName", diskImagePath ); - if ( hddMode != null ) { - addFiltered( prefix + ".mode", hddMode ); - addFiltered( prefix + ".redo", "" ); - addFiltered( prefix + ".redoLogDir", redoDir ); - } - config.remove( "#SLX_HDD_BUS" ); - config.remove( "#SLX_HDD_CHIP" ); - return true; - } - - public boolean addDefaultNat() - { - addFiltered( "ethernet0.present", "TRUE" ); - addFiltered( "ethernet0.connectionType", "nat" ); - return true; - } - - public boolean addEthernet( VmMetaData.EtherType type ) - { - boolean ret = false; - int index = 0; - for ( ;; ++index ) { - if ( config.get( "ethernet" + index + ".present" ) == null ) - break; - } - switch ( type ) { - case NAT: - ret = addEthernet( index, EthernetType.NAT ); - break; - case BRIDGED: - ret = addEthernet( index, EthernetType.BRIDGED ); - break; - case HOST_ONLY: - ret = addEthernet( index, EthernetType.HOST_ONLY ); - break; - default: - // Should not come to this... - break; - } - return ret; - } - - public boolean addEthernet( int index, EthernetType type ) - { - String ether = "ethernet" + index; - addFiltered( ether + ".present", "TRUE" ); - addFiltered( ether + ".connectionType", "custom" ); - addFiltered( ether + ".vnet", type.vmnet ); - if ( config.get( ether + ".virtualDev" ) == null ) { - String dev = config.get( "ethernet0.virtualDev" ); - if ( dev != null ) { - addFiltered( ether + ".virtualDev", dev ); - } - } - return true; - } - - public void addFloppy( int index, String image, boolean readOnly ) - { - String pre = "floppy" + index; - addFiltered( pre + ".present", "TRUE" ); - if ( image == null ) { - addFiltered( pre + ".startConnected", "FALSE" ); - addFiltered( pre + ".fileType", "device" ); - config.remove( pre + ".fileName" ); - config.remove( pre + ".readonly" ); - addFiltered( pre + ".autodetect", "TRUE" ); - } else { - addFiltered( pre + ".startConnected", "TRUE" ); - addFiltered( pre + ".fileType", "file" ); - addFiltered( pre + ".fileName", image ); - addFiltered( pre + ".readonly", vmBoolean( readOnly ) ); - config.remove( pre + ".autodetect" ); - } - } - - public boolean addCdrom( String image ) - { - for ( String port : new String[] { "ide0:0", "ide0:1", "ide1:0", "ide1:1", "scsi0:1" } ) { - if ( !isSetAndTrue( port + ".present" ) ) { - addFiltered( port + ".present", "TRUE" ); - if ( image == null ) { - addFiltered( port + ".autodetect", "TRUE" ); - addFiltered( port + ".deviceType", "cdrom-raw" ); - config.remove( port + ".fileName" ); - } else { - config.remove( port + ".autodetect" ); - addFiltered( port + ".deviceType", "cdrom-image" ); - addFiltered( port + ".fileName", image ); - } - return true; - } - } - return false; - } - - private static String vmBoolean( boolean var ) - { - return Boolean.toString( var ).toUpperCase(); - } - - private static String vmInteger( int val ) - { - return Integer.toString( val ); - } - - @Override - public boolean tweakForNonPersistent() - { - addFiltered( "suspend.disabled", "TRUE" ); - return true; - } - - @Override - public boolean addDisplayName( String name ) - { - addFiltered( "displayName", name ); - return true; - } - - @Override - public boolean addRam( int mem ) - { - addFiltered( "memsize", Integer.toString( mem ) ); - return true; - } - - public void setOs( String vendorOsId ) - { - addFiltered( "guestOS", vendorOsId ); - setOs( TConst.VIRT_VMWARE, vendorOsId ); - } - - @Override - public byte[] getFilteredDefinitionArray() - { - return config.toString( true, false ).getBytes( StandardCharsets.UTF_8 ); - } - - public byte[] getDefinitionArray() - { - return config.toString( false, false ).getBytes( StandardCharsets.UTF_8 ); - } - - @Override - public Virtualizer getVirtualizer() - { - return virtualizer; - } - - private static class Device - { - public boolean present = false; - public String deviceType = null; - public String filename = null; - - @Override - public String toString() - { - return filename + " is " + deviceType + " (present: " + present + ")"; - } - } - - private static class Controller - { - public boolean present = true; // Seems to be implicit, seen at least for IDE... - public String virtualDev = null; - Map<String, Device> devices = new HashMap<>(); - - @Override - public String toString() - { - return virtualDev + " is (present: " + present + "): " + devices.toString(); - } - } - - @Override - public void applySettingsForLocalEdit() - { - addFiltered( "gui.applyHostDisplayScalingToGuest", "FALSE" ); - } - - public String getValue( String key ) - { - return config.get( key ); - } - - public void setSoundCard( VmMetaData.SoundCardType type ) - { - VmWareSoundCardMeta soundCardMeta = soundCards.get( type ); - addFiltered( "sound.present", vmBoolean( soundCardMeta.isPresent ) ); - if ( soundCardMeta.value != null ) { - addFiltered( "sound.virtualDev", soundCardMeta.value ); - } else { - config.remove( "sound.virtualDev" ); - } - } - - public VmMetaData.SoundCardType getSoundCard() - { - if ( !isSetAndTrue( "sound.present" ) || !isSetAndTrue( "sound.autodetect" ) ) { - return VmMetaData.SoundCardType.NONE; - } - String current = config.get( "sound.virtualDev" ); - if ( current != null ) { - VmWareSoundCardMeta soundCardMeta = null; - for ( VmMetaData.SoundCardType type : VmMetaData.SoundCardType.values() ) { - soundCardMeta = soundCards.get( type ); - if ( soundCardMeta != null ) { - if ( current.equals( soundCardMeta.value ) ) { - return type; - } - } - } - } - return VmMetaData.SoundCardType.DEFAULT; - } - - public void setDDAcceleration( VmMetaData.DDAcceleration type ) - { - VmWareDDAccelMeta ddaMeta = ddacc.get( type ); - addFiltered( "mks.enable3d", vmBoolean( ddaMeta.isPresent ) ); - } - - public VmMetaData.DDAcceleration getDDAcceleration() - { - if ( isSetAndTrue( "mks.enable3d" ) ) { - return VmMetaData.DDAcceleration.ON; - } else { - return VmMetaData.DDAcceleration.OFF; - } - } - - public void setHWVersion( VmMetaData.HWVersion type ) - { - VmWareHWVersionMeta hwVersionMeta = hwversion.get( type ); - addFiltered( "virtualHW.version", vmInteger( hwVersionMeta.version ) ); - } - - public VmMetaData.HWVersion getHWVersion() - { - int currentValue = Util.parseInt( config.get( "virtualHW.version" ), -1 ); - VmWareHWVersionMeta hwVersionMeta = null; - for ( VmMetaData.HWVersion ver : VmMetaData.HWVersion.values() ) { - hwVersionMeta = hwversion.get( ver ); - if ( hwVersionMeta == null ) { - continue; - } - if ( currentValue == hwVersionMeta.version ) { - return ver; - } - } - return HWVersion.NONE; - } - - public void setEthernetDevType( int cardIndex, VmMetaData.EthernetDevType type ) - { - VmWareEthernetDevTypeMeta ethernetDevTypeMeta = networkCards.get( type ); - if ( ethernetDevTypeMeta.value != null ) { - addFiltered( "ethernet" + cardIndex + ".virtualDev", ethernetDevTypeMeta.value ); - } else { - config.remove( "ethernet" + cardIndex + ".virtualDev" ); - } - } - - public VmMetaData.EthernetDevType getEthernetDevType( int cardIndex ) - { - String temp = config.get( "ethernet" + cardIndex + ".virtualDev" ); - if ( temp != null ) { - VmWareEthernetDevTypeMeta ethernetDevTypeMeta = null; - for ( VmMetaData.EthernetDevType type : VmMetaData.EthernetDevType.values() ) { - ethernetDevTypeMeta = networkCards.get( type ); - if ( ethernetDevTypeMeta == null ) { - continue; - } - if ( temp.equals( ethernetDevTypeMeta.value ) ) { - return type; - } - } - } - return VmMetaData.EthernetDevType.AUTO; - } - - @Override - public void setMaxUsbSpeed( VmMetaData.UsbSpeed newSpeed ) - { - if ( newSpeed == null ) { - newSpeed = VmMetaData.UsbSpeed.NONE; - } - VmwareUsbSpeed newSpeedMeta = usbSpeeds.get( newSpeed ); - if ( newSpeedMeta == null ) { - throw new RuntimeException( "USB Speed " + newSpeed.name() + " not registered with VMware" ); - } - for ( VmwareUsbSpeed meta : usbSpeeds.values() ) { - if ( meta == null ) - continue; // Should not happen - if ( meta.keyName == null ) - continue; // "No USB" has no config entry, obviously - if ( meta.speedNumeric <= newSpeedMeta.speedNumeric ) { - // Enable desired speed class, plus all lower ones - addFiltered( meta.keyName, "TRUE" ); - } else { - // This one is higher – remove - config.remove( meta.keyName ); - } - } - // VMware 14+ needs this to use USB 3.0 devices at USB 3.0 ports in VMs configured for < 3.0 - if ( newSpeedMeta.speedNumeric > 0 && newSpeedMeta.speedNumeric < 3 ) { - addFiltered( "usb.mangleUsb3Speed", "TRUE" ); - } - } - - @Override - public VmMetaData.UsbSpeed getMaxUsbSpeed() - { - int max = 0; - VmMetaData.UsbSpeed maxEnum = VmMetaData.UsbSpeed.NONE; - for ( Entry<VmMetaData.UsbSpeed, VmwareUsbSpeed> entry : usbSpeeds.entrySet() ) { - VmwareUsbSpeed v = entry.getValue(); - if ( v.speedNumeric > max && isSetAndTrue( v.keyName ) ) { - max = v.speedNumeric; - maxEnum = entry.getKey(); - } - } - return maxEnum; - } - - @Override - public boolean addCpuCoreCount( int numCores ) - { - // TODO actually add the cpu core count to the machine description - return false; - } - - public void registerVirtualHW() - { - soundCards.put( VmMetaData.SoundCardType.NONE, new VmWareSoundCardMeta( false, null ) ); - soundCards.put( VmMetaData.SoundCardType.DEFAULT, new VmWareSoundCardMeta( true, null ) ); - soundCards.put( VmMetaData.SoundCardType.SOUND_BLASTER, new VmWareSoundCardMeta( true, "sb16" ) ); - soundCards.put( VmMetaData.SoundCardType.ES, new VmWareSoundCardMeta( true, "es1371" ) ); - soundCards.put( VmMetaData.SoundCardType.HD_AUDIO, new VmWareSoundCardMeta( true, "hdaudio" ) ); - - ddacc.put( VmMetaData.DDAcceleration.OFF, new VmWareDDAccelMeta( false ) ); - ddacc.put( VmMetaData.DDAcceleration.ON, new VmWareDDAccelMeta( true ) ); - - hwversion.put( VmMetaData.HWVersion.NONE, new VmWareHWVersionMeta( 0 ) ); - hwversion.put( VmMetaData.HWVersion.THREE, new VmWareHWVersionMeta( 3 ) ); - hwversion.put( VmMetaData.HWVersion.FOUR, new VmWareHWVersionMeta( 4 ) ); - hwversion.put( VmMetaData.HWVersion.SIX, new VmWareHWVersionMeta( 6 ) ); - hwversion.put( VmMetaData.HWVersion.SEVEN, new VmWareHWVersionMeta( 7 ) ); - hwversion.put( VmMetaData.HWVersion.EIGHT, new VmWareHWVersionMeta( 8 ) ); - hwversion.put( VmMetaData.HWVersion.NINE, new VmWareHWVersionMeta( 9 ) ); - hwversion.put( VmMetaData.HWVersion.TEN, new VmWareHWVersionMeta( 10 ) ); - hwversion.put( VmMetaData.HWVersion.ELEVEN, new VmWareHWVersionMeta( 11 ) ); - hwversion.put( VmMetaData.HWVersion.TWELVE, new VmWareHWVersionMeta( 12 ) ); - hwversion.put( VmMetaData.HWVersion.FOURTEEN, new VmWareHWVersionMeta( 14 ) ); - hwversion.put( VmMetaData.HWVersion.FIFTEEN, new VmWareHWVersionMeta( 15 ) ); - hwversion.put( VmMetaData.HWVersion.FIFTEEN_ONE, new VmWareHWVersionMeta( 16 ) ); - - networkCards.put( VmMetaData.EthernetDevType.AUTO, new VmWareEthernetDevTypeMeta( null ) ); - networkCards.put( VmMetaData.EthernetDevType.PCNET32, new VmWareEthernetDevTypeMeta( "vlance" ) ); - networkCards.put( VmMetaData.EthernetDevType.E1000, new VmWareEthernetDevTypeMeta( "e1000" ) ); - networkCards.put( VmMetaData.EthernetDevType.E1000E, new VmWareEthernetDevTypeMeta( "e1000e" ) ); - networkCards.put( VmMetaData.EthernetDevType.VMXNET, new VmWareEthernetDevTypeMeta( "vmxnet" ) ); - networkCards.put( VmMetaData.EthernetDevType.VMXNET3, new VmWareEthernetDevTypeMeta( "vmxnet3" ) ); - - usbSpeeds.put( VmMetaData.UsbSpeed.NONE, new VmwareUsbSpeed( 0, null )); - usbSpeeds.put( VmMetaData.UsbSpeed.USB1_1, new VmwareUsbSpeed( 1, "usb" ) ); - usbSpeeds.put( VmMetaData.UsbSpeed.USB2_0, new VmwareUsbSpeed( 2, "ehci" ) ); - usbSpeeds.put( VmMetaData.UsbSpeed.USB3_0, new VmwareUsbSpeed( 3, "usb_xhci" ) ); - } - -} |