summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/util/vm/VboxConfig.java
blob: 2c3a4157dd009b2042051dce143116b1a9797478 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
package org.openslx.util.vm;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
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.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.InputSource;
import org.xml.sax.SAXException;

/**
 * Class representing a .vbox machine description file
 */
public class VboxConfig
{
	private static final Logger LOGGER = Logger.getLogger( VboxConfig.class );
	XPath xPath = XPathFactory.newInstance().newXPath();

	private Document doc = null;
	private String displayNameExpression = "/VirtualBox/Machine/@name";
	private String displayName = new String();

	private String osTypeExpression = "/VirtualBox/Machine/@OSType";
	private String osName = new String();

	private String hddsExpression = "/VirtualBox/Machine/MediaRegistry/HardDisks/*";
	private ArrayList<HardDisk> hddsArray = new ArrayList<HardDisk>();
	private boolean isMachineSnapshot = false;
	// list of nodes to automatically remove when reading the vbox file
	private static String[] blackList = { "SharedFolders", "HID", "USB", "ExtraData", "Adapter", "GuestProperties", "LPT", "StorageController", "FloppyImages", "DVDImages",
			"AttachedDevice", "RemoteDisplay", "VideoCapture" };

	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;
		}
	}

	/**
	 * constructor with input xml file
	 * used to set the doc variable of this class when creating vm
	 * 
	 * @param file as File - the input xml File
	 * @throws IOException
	 * @throws UnsupportedVirtualizerFormatException
	 */
	public VboxConfig( File file ) throws IOException, UnsupportedVirtualizerFormatException
	{
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

			doc = dBuilder.parse( file );

			// TODO - does this test suffice??
			if ( !doc.getDocumentElement().getNodeName().equals( "VirtualBox" ) ) {
				throw new UnsupportedVirtualizerFormatException( "No <VirtualBox> root node." );
			}

		} catch ( ParserConfigurationException | SAXException | IOException e ) {
			LOGGER.warn( "Could not parse .Vbox", e );
			throw new UnsupportedVirtualizerFormatException( "Could not create VBoxConfig!" );
		}
	}

	/**
	 * constructor with input string from server
	 * used to set the doc variable of this class when rebuilding the doc
	 * 
	 * @param filtered as String - sent from server
	 * @param length
	 * @throws IOException
	 */
	public VboxConfig( byte[] filtered, int length ) throws IOException
	{
		try {
			String filteredString = new String( filtered );
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			// TODO following two settings should handle the formatting of the xml
			// but did not work correctly according to Victor... to test.
			//dbFactory.setValidating( true );
			//dbFactory.setIgnoringElementContentWhitespace( true );
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			InputSource is = new InputSource( new StringReader( filteredString ) );

			doc = dBuilder.parse( is );

		} catch ( ParserConfigurationException | SAXException e ) {
			LOGGER.warn( "Could not recreate the dom", e );
		}
	}

	/**
	 * getter for the xmldoc
	 * 
	 * @return definition document
	 */
	public Document getConfigDoc()
	{
		return doc;
	}

	/**
	 * Main initialization functions parsing the XML document.
	 */
	public void init()
	{
		if ( doc.getChildNodes().item( 0 ).getNodeType() == 8 ) {
			doc.removeChild( doc.getChildNodes().item( 0 ) );
		}
		try {
			setMachineName();
			checkForMachineSnapshots();
			ensureHardwareUuid();
			setOsType();
			if ( checkForPlaceholders() ) {
				return;
			}
			setHdds();
			removeBlackListedTags();
			addPlaceHolders();
		} catch ( XPathExpressionException e ) {
			LOGGER.debug( "Could not initialize VBoxConfig", e );
			return;
		}
	}

	private void checkForMachineSnapshots() throws XPathExpressionException
	{
		// 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" );
		isMachineSnapshot = ( machineSnapshots != null && machineSnapshots.getLength() > 0 );
	}

	private void ensureHardwareUuid() throws XPathExpressionException
	{
		// we will need the machine uuid, so get it
		String machineUuid = xPath.compile( "/VirtualBox/Machine/@uuid" ).evaluate( this.doc );
		if ( machineUuid.isEmpty() ) {
			LOGGER.error( "Machine UUID empty, should never happen!" );
			return;
		}

		NodeList hwNodes = findNodes( "/VirtualBox/Machine/Hardware" );
		int count = hwNodes.getLength();
		if ( count == 1 ) {
			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." );
			}
		} else {
			// HACK: hijack XPathExpressionException ...
			throw new XPathExpressionException( "Zero or more '/VirtualBox/Machine/Hardware' node were found, should never happen!" );
		}
	}

	/**
	 * Function checks if the placeholders are present
	 * 
	 * @return true if the placeholders are present, false otherwise
	 */
	private boolean checkForPlaceholders()
	{
		NodeList hdds = findNodes( "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;
	}

	/**
	 * Function finds and saves the name of the machine
	 * 
	 * @throws XPathExpressionException
	 */
	public void setMachineName() throws XPathExpressionException
	{
		String name = xPath.compile( displayNameExpression ).evaluate( this.doc );
		if ( name != null && !name.isEmpty() ) {
			displayName = name;
		}
	}

	/**
	 * Function finds and saves the name of the os
	 * 
	 * @throws XPathExpressionException
	 */
	public void setOsType() throws XPathExpressionException
	{
		String os = xPath.compile( osTypeExpression ).evaluate( this.doc );
		if ( os != null && !os.isEmpty() ) {
			osName = os;
		}
	}

	public void setHdds() throws XPathExpressionException
	{
		XPathExpression hddsExpr = xPath.compile( hddsExpression );
		Object result = hddsExpr.evaluate( this.doc, XPathConstants.NODESET );
		// take all the hdd nodes
		NodeList nodes = (NodeList)result;
		// foreach hdd in the hddnodes do:
		for ( int i = 0; i < nodes.getLength(); i++ ) {
			// have the node
			// take the uuid
			// look under <AttachedDevice if found and do stuff with it
			Element hddElement = (Element)nodes.item( i );
			if ( hddElement == null )
				continue;
			// read the filePath
			String fileName = hddElement.getAttribute( "location" );
			// take the uuid
			String uuid = hddElement.getAttribute( "uuid" );
			// search in the xml object and give back the parent of the parent of the node that is called Image and has the given uuid
			String type = hddElement.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." );
			}
			String pathToParent = "//Image[contains(@uuid, \'" + uuid + "\')]/../..";
			XPathExpression attachedDevicesExpr = xPath.compile( pathToParent );
			Object devicesResult = attachedDevicesExpr.evaluate( this.doc, XPathConstants.NODESET );
			NodeList devicesNodes = (NodeList)devicesResult;
			// TODO -- ehm...should only have 1 element...what do when there are more?
			if ( devicesNodes.getLength() > 1 ) {
				LOGGER.error( "There can not be more HDDs with the same UUID!" );
				return;
			}
			if ( devicesNodes.getLength() == 0 ) {
				LOGGER.error( "Image with UUID '" + uuid + "' does not seem connected to any storage controller. Is it a snapshot?" );
				return;
			}
			Element deviceElement = (Element)devicesNodes.item( 0 );
			String controllerDevice = deviceElement.getAttribute( "type" );
			String bus = deviceElement.getAttribute( "name" );
			DriveBusType busType = null;
			if ( bus.equals( "IDE" ) ) {
				busType = DriveBusType.IDE;
			} else if ( bus.equals( "SCSI" ) ) {
				busType = DriveBusType.SCSI;
			} else if ( bus.equals( "SATA" ) ) {
				busType = DriveBusType.SATA;
			}
			// add them together
			hddsArray.add( new HardDisk( controllerDevice, busType, fileName ) );
		}
	}

	public void addPlaceHolders()
	{
		// placeholder for the MACAddress
		changeAttribute( "Adapter", "MACAddress", PlaceHolder.NETWORKMAC.toString() );

		// placeholder for the machine uuid
		changeAttribute( "Machine", "uuid", PlaceHolder.MACHINEUUID.toString() );

		// placeholder for the location of the virtual hdd
		changeAttribute( "HardDisk", "location", PlaceHolder.HDDLOCATION.toString() );

		// placeholder for the memory
		changeAttribute( "Memory", "RAMSize", PlaceHolder.MEMORY.toString() );

		// placeholder for the CPU
		changeAttribute( "CPU", "count", PlaceHolder.CPU.toString() );

		// add placeholder for the uuid of the virtual harddrive.
		// must be added on 2 positions...in the HardDisk tag and the attachedDevice tag
		// first find the uuid
		NodeList hdds = findNodes( "HardDisk" );
		for ( int i = 0; i < hdds.getLength(); i++ ) {
			Element hdd = (Element)findNodes( "HardDisk" ).item( i );
			if ( hdd == null )
				continue;
			String uuid = hdd.getAttribute( "uuid" );
			hdd.setAttribute( "uuid", PlaceHolder.HDDUUID.toString() + i + "%" );
			NodeList images = findNodes( "Image" );
			Element image;
			for ( int j = 0; j < images.getLength(); j++ ) {
				if ( ( (Element)images.item( j ) ).getAttribute( "uuid" ).equals( uuid ) ) {
					image = (Element)images.item( j );
					image.setAttribute( "uuid", PlaceHolder.HDDUUID.toString() + i + "%" );
					break;
				}
			}
		}
	}

	/**
	 * Search through the doc for nodes with the given name.
	 * If the given name starts with '/', assume a full XPath was
	 * given and do not do a full search
	 * 
	 * @param identifier
	 * @return nodes as NodeList
	 */
	public NodeList findNodes( String identifier )
	{
		String path;
		if ( identifier.startsWith( "/", 0 ) )
			path = identifier;
		else
			path = ".//" + identifier;

		XPathExpression expr;
		NodeList nodes = null;
		try {
			expr = xPath.compile( path );
			Object nodesObject = expr.evaluate( this.doc, XPathConstants.NODESET );
			nodes = (NodeList)nodesObject;
		} catch ( XPathExpressionException e ) {
			LOGGER.error( "Could not build path", e );
		}
		return nodes;
	}

	/**
	 * Function uses the findNodes function to narrow down the wanted node using 1 attribute and
	 * its value
	 * 
	 * @param targetTag
	 * @param targetAttr0
	 * @param value0
	 * @return
	 */
	public Node findNode( String targetTag, String targetAttr0, String value0 )
	{
		Node returnNode = null;

		NodeList foundNodes = findNodes( targetTag );

		for ( int i = 0; i < foundNodes.getLength(); i++ ) {
			Element node = (Element)foundNodes.item( i );
			if ( node != null && node.hasAttribute( targetAttr0 ) && node.getAttribute( targetAttr0 ).equals( value0 ) ) {
				returnNode = foundNodes.item( i );
			}
		}
		return returnNode;
	}

	/**
	 * Function used to change the value of an attribute
	 * Use this function if you know the targetNode is unique
	 * 
	 * @param targetTag
	 * @param attribute
	 * @param newValue
	 */
	public void changeAttribute( String targetTag, String attribute, String newValue )
	{
		changeAttribute( targetTag, attribute, newValue, null, null );
	}

	/**
	 * Function used to change the value of an attribute
	 * Use this function if you are not sure if the targetNode is unique
	 * Use refAttr and refVal to address the right node
	 * 
	 * @param targetTag
	 * @param targetAttr
	 * @param newValue
	 * @param refAttr
	 * @param refVal
	 */
	public void changeAttribute( String targetTag, String targetAttr, String newValue, String refAttr, String refVal )
	{
		NodeList nodes = findNodes( targetTag );

		for ( int i = 0; i < nodes.getLength(); i++ ) {
			Element element = (Element)nodes.item( i );
			if ( element == null )
				return;
			if ( refAttr != null && refVal != null ) {
				if ( element.getAttribute( refAttr ).equals( refVal ) ) {
					element.setAttribute( targetAttr, newValue );
					break;
				}
			} else {
				if ( nodes.getLength() > 1 ) {
					LOGGER.error( "Action would change values of more than one node; stopped!" );
					return;
				}
				element.setAttribute( targetAttr, newValue );
			}
		}
	}

	public boolean addAttributeToNode( Node targetNode, String attrName, String value )
	{
		if ( targetNode == null ) {
			LOGGER.warn( "Node is null; stopped!" );
			return false;
		}
		try {
			( (Element)targetNode ).setAttribute( attrName, value );
		} catch ( DOMException e ) {
			LOGGER.error( "Failed set '" + attrName + "' to '" + value + "' of xml node '" + targetNode.getNodeName() + "': ", e );
			return false;
		}
		return true;
	}

	public Node addNewNode( String nameOfParent, String nameOfnewNode, boolean oneLiner )
	{
		return addNewNode( nameOfParent, nameOfnewNode, oneLiner, null, null );
	}

	public Node addNewNode( String nameOfParent, String nameOfnewNode, boolean oneLiner, String refAttr, String refVal )
	{
		Node parent = null;
		NodeList posibleParents = findNodes( nameOfParent );
		Element newNode;
		try {
			if ( posibleParents.getLength() > 1 ) {
				// if we have more then 1 parent we need to have an sanityArg s.t. we insert our new attribute in the right tag
				if ( refAttr == null ) {
					LOGGER.warn( "Action would change values of more than one node; stopped!" );
					return null;
				}
				for ( int i = 1; i < posibleParents.getLength(); i++ ) {
					if ( ( (Element)posibleParents.item( i ) ).getAttribute( refAttr ).equals( refVal ) ) {
						parent = posibleParents.item( i );
						break;
					}
				}
			} else {
				parent = posibleParents.item( 0 );
			}

			if ( parent == null ) {
				LOGGER.warn( "Node: '" + nameOfParent + "' could not be found" );
				return null;
			}
			newNode = doc.createElement( nameOfnewNode );

			if ( !oneLiner ) {
				org.w3c.dom.Text a = doc.createTextNode( "\n" );
				newNode.appendChild( a );
			}
			parent.appendChild( newNode );
		} catch ( DOMException e ) {
			LOGGER.error( "Something went wrong: ", e );
			return null;
		}

		return newNode;
	}

	/**
	 * USB will be enabled
	 */
	public void enableUsb()
	{
		addNewNode( "Hardware", "USB", false );
		addNewNode( "USB", "Controllers", false );
		// OHCI for USB 1.0
		Node controller1 = addNewNode( "Controllers", "Controller", true );
		addAttributeToNode( controller1, "name", "OHCI" );
		addAttributeToNode( controller1, "type", "OHCI" );
		// EHCI for USB 2.0
		Node controller2 = addNewNode( "Controllers", "Controller", true );
		addAttributeToNode( controller2, "name", "EHCI" );
		addAttributeToNode( controller2, "type", "EHCI" );
	}

	/**
	 * Disable usb by removing the USB tag
	 */
	public void disableUsb()
	{
		NodeList usbList = findNodes( "USB" );
		removeNode( usbList.item( 0 ) );
	}

	// function removes a given child and the format childNode 
	private void removeNode( Node node )
	{
		if ( node == null ) {
			return;
		}
		Node parent = node.getParentNode();
		// this node here is usually a type3 Node used only for the formating of the vbox file
		Node previousSibling = node.getPreviousSibling();

		parent.removeChild( node );

		// HACK remove empty lines
		// format children (\n or \t) have type 3
		if ( previousSibling.getNodeType() == 3 ) {
			// the value of these Nodes are characters
			String tmp = previousSibling.getNodeValue();
			boolean shouldDelete = true;
			for ( int i = 0; i < tmp.length(); i++ ) {
				if ( !Character.isWhitespace( tmp.charAt( i ) ) ) {
					shouldDelete = false;
					break;
				}
			}
			if ( shouldDelete )
				parent.removeChild( previousSibling );
		}
	}

	// cleanup part here
	private void removeBlackListedTags() throws XPathExpressionException
	{
		// iterate over the blackList
		for ( String blackedTag : blackList ) {
			String blackedExpression = ".//" + blackedTag;
			XPathExpression blackedExpr = xPath.compile( blackedExpression );

			NodeList blackedNodes = (NodeList)blackedExpr.evaluate( this.doc, XPathConstants.NODESET );
			for ( int i = 0; i < blackedNodes.getLength(); i++ ) {
				// get the child node
				Element child = (Element)blackedNodes.item( i );
				// remove child
				if ( child.getTagName().equals( "Adapter" ) && child.getAttribute( "enabled" ).equals( "true" ) ) {
					// we need to remove the children of the active network adapter
					// these are the mode of network connection and disabled modes...they go together -> see wiki
					Node firstChild = child.getChildNodes().item( 0 );
					Node secondChild = child.getChildNodes().item( 1 );
					if ( firstChild != null && secondChild != null ) {
						if ( firstChild.getNodeName().equals( "#text" ) && !secondChild.getNodeName().equals( "#text" ) ) {
							removeNode( child.getChildNodes().item( 1 ) );
						}
					}
					LOGGER.warn( "possible problem while removing formating node" );
					continue;
				}

				if ( ( child.getTagName().equals( "StorageController" ) && !child.getAttribute( "name" ).equals( "Floppy" ) )
						|| ( child.getTagName().equals( "AttachedDevice" ) && child.getAttribute( "type" ).equals( "HardDisk" ) ) ) {
					continue;
				}
				// the structure of the xml Document is achieved through children nodes that are made up of just /n and spaces
				// when a child node is deleted we get an empty line there the old child node used to be
				removeNode( child );
			}
		}
	}

	public String getDisplayName()
	{
		return displayName;
	}

	public String getOsName()
	{
		return osName;
	}

	public ArrayList<HardDisk> getHdds()
	{
		return hddsArray;
	}

	public String toString()
	{
		try {
			StringWriter sw = new StringWriter();
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" );
			transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
			transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
			transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );

			transformer.transform( new DOMSource( doc ), new StreamResult( sw ) );
			return sw.toString();
		} catch ( Exception ex ) {
			throw new RuntimeException( "Error converting to String", ex );
		}
	}

	public boolean isMachineSnapshot()
	{
		return isMachineSnapshot;
	}
}