VirtualBox

source: vbox/trunk/src/VBox/Main/ApplianceImplImport.cpp@ 34867

Last change on this file since 34867 was 34501, checked in by vboxsync, 14 years ago

Main/OVF: use ostype from ovf:/OperatingSystemSection/vbox:OSType element if present (reading only so far)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 116.8 KB
Line 
1/* $Id: ApplianceImplImport.cpp 34501 2010-11-30 12:30:30Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2010 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19#include <iprt/path.h>
20#include <iprt/dir.h>
21#include <iprt/file.h>
22#include <iprt/s3.h>
23#include <iprt/sha.h>
24#include <iprt/manifest.h>
25#include <iprt/tar.h>
26#include <iprt/stream.h>
27
28#include <VBox/vd.h>
29#include <VBox/com/array.h>
30
31#include "ApplianceImpl.h"
32#include "VirtualBoxImpl.h"
33#include "GuestOSTypeImpl.h"
34#include "ProgressImpl.h"
35#include "MachineImpl.h"
36#include "MediumImpl.h"
37#include "MediumFormatImpl.h"
38#include "SystemPropertiesImpl.h"
39
40#include "AutoCaller.h"
41#include "Logging.h"
42
43#include "ApplianceImplPrivate.h"
44
45#include <VBox/param.h>
46#include <VBox/version.h>
47#include <VBox/settings.h>
48
49using namespace std;
50
51////////////////////////////////////////////////////////////////////////////////
52//
53// IAppliance public methods
54//
55////////////////////////////////////////////////////////////////////////////////
56
57/**
58 * Public method implementation. This opens the OVF with ovfreader.cpp.
59 * Thread implementation is in Appliance::readImpl().
60 *
61 * @param path
62 * @return
63 */
64STDMETHODIMP Appliance::Read(IN_BSTR path, IProgress **aProgress)
65{
66 if (!path) return E_POINTER;
67 CheckComArgOutPointerValid(aProgress);
68
69 AutoCaller autoCaller(this);
70 if (FAILED(autoCaller.rc())) return autoCaller.rc();
71
72 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
73
74 if (!isApplianceIdle())
75 return E_ACCESSDENIED;
76
77 if (m->pReader)
78 {
79 delete m->pReader;
80 m->pReader = NULL;
81 }
82
83 // see if we can handle this file; for now we insist it has an ovf/ova extension
84 Utf8Str strPath (path);
85 if (!( strPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
86 || strPath.endsWith(".ova", Utf8Str::CaseInsensitive)))
87 return setError(VBOX_E_FILE_ERROR,
88 tr("Appliance file must have .ovf extension"));
89
90 ComObjPtr<Progress> progress;
91 HRESULT rc = S_OK;
92 try
93 {
94 /* Parse all necessary info out of the URI */
95 parseURI(strPath, m->locInfo);
96 rc = readImpl(m->locInfo, progress);
97 }
98 catch (HRESULT aRC)
99 {
100 rc = aRC;
101 }
102
103 if (SUCCEEDED(rc))
104 /* Return progress to the caller */
105 progress.queryInterfaceTo(aProgress);
106
107 return S_OK;
108}
109
110/**
111 * Public method implementation. This looks at the output of ovfreader.cpp and creates
112 * VirtualSystemDescription instances.
113 * @return
114 */
115STDMETHODIMP Appliance::Interpret()
116{
117 // @todo:
118 // - don't use COM methods but the methods directly (faster, but needs appropriate locking of that objects itself (s. HardDisk))
119 // - Appropriate handle errors like not supported file formats
120 AutoCaller autoCaller(this);
121 if (FAILED(autoCaller.rc())) return autoCaller.rc();
122
123 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
124
125 if (!isApplianceIdle())
126 return E_ACCESSDENIED;
127
128 HRESULT rc = S_OK;
129
130 /* Clear any previous virtual system descriptions */
131 m->virtualSystemDescriptions.clear();
132
133 if (!m->pReader)
134 return setError(E_FAIL,
135 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
136
137 // Change the appliance state so we can safely leave the lock while doing time-consuming
138 // disk imports; also the below method calls do all kinds of locking which conflicts with
139 // the appliance object lock
140 m->state = Data::ApplianceImporting;
141 alock.release();
142
143 /* Try/catch so we can clean up on error */
144 try
145 {
146 list<ovf::VirtualSystem>::const_iterator it;
147 /* Iterate through all virtual systems */
148 for (it = m->pReader->m_llVirtualSystems.begin();
149 it != m->pReader->m_llVirtualSystems.end();
150 ++it)
151 {
152 const ovf::VirtualSystem &vsysThis = *it;
153
154 ComObjPtr<VirtualSystemDescription> pNewDesc;
155 rc = pNewDesc.createObject();
156 if (FAILED(rc)) throw rc;
157 rc = pNewDesc->init();
158 if (FAILED(rc)) throw rc;
159
160 // if the virtual system in OVF had a <vbox:Machine> element, have the
161 // VirtualBox settings code parse that XML now
162 if (vsysThis.pelmVboxMachine)
163 pNewDesc->importVboxMachineXML(*vsysThis.pelmVboxMachine);
164
165 // Guest OS type
166 // This is taken from one of three places, in this order:
167 Utf8Str strOsTypeVBox;
168 Utf8StrFmt strCIMOSType("%RU32", (uint32_t)vsysThis.cimos);
169 // 1) If there is a <vbox:Machine>, then use the type from there.
170 if ( vsysThis.pelmVboxMachine
171 && pNewDesc->m->pConfig->machineUserData.strOsType.isNotEmpty()
172 )
173 strOsTypeVBox = pNewDesc->m->pConfig->machineUserData.strOsType;
174 // 2) Otherwise, if there is OperatingSystemSection/vbox:OSType, use that one.
175 else if (vsysThis.strTypeVbox.isNotEmpty()) // OVFReader has found vbox:OSType
176 strOsTypeVBox = vsysThis.strTypeVbox;
177 // 3) Otherwise, make a best guess what the vbox type is from the OVF (CIM) OS type.
178 else
179 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
180 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
181 "",
182 strCIMOSType,
183 strOsTypeVBox);
184
185 /* VM name */
186 Utf8Str nameVBox;
187 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
188 if ( vsysThis.pelmVboxMachine
189 && pNewDesc->m->pConfig->machineUserData.strName.isNotEmpty())
190 nameVBox = pNewDesc->m->pConfig->machineUserData.strName;
191 else
192 nameVBox = vsysThis.strName;
193 /* If the there isn't any name specified create a default one out
194 * of the OS type */
195 if (nameVBox.isEmpty())
196 nameVBox = strOsTypeVBox;
197 searchUniqueVMName(nameVBox);
198 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
199 "",
200 vsysThis.strName,
201 nameVBox);
202
203 /* Based on the VM name, create a target machine path. */
204 Bstr bstrMachineFilename;
205 rc = mVirtualBox->ComposeMachineFilename(Bstr(nameVBox).raw(),
206 NULL,
207 bstrMachineFilename.asOutParam());
208 if (FAILED(rc)) throw rc;
209 /* Determine the machine folder from that */
210 Utf8Str strMachineFolder = Utf8Str(bstrMachineFilename).stripFilename();
211
212 /* VM Product */
213 if (!vsysThis.strProduct.isEmpty())
214 pNewDesc->addEntry(VirtualSystemDescriptionType_Product,
215 "",
216 vsysThis.strProduct,
217 vsysThis.strProduct);
218
219 /* VM Vendor */
220 if (!vsysThis.strVendor.isEmpty())
221 pNewDesc->addEntry(VirtualSystemDescriptionType_Vendor,
222 "",
223 vsysThis.strVendor,
224 vsysThis.strVendor);
225
226 /* VM Version */
227 if (!vsysThis.strVersion.isEmpty())
228 pNewDesc->addEntry(VirtualSystemDescriptionType_Version,
229 "",
230 vsysThis.strVersion,
231 vsysThis.strVersion);
232
233 /* VM ProductUrl */
234 if (!vsysThis.strProductUrl.isEmpty())
235 pNewDesc->addEntry(VirtualSystemDescriptionType_ProductUrl,
236 "",
237 vsysThis.strProductUrl,
238 vsysThis.strProductUrl);
239
240 /* VM VendorUrl */
241 if (!vsysThis.strVendorUrl.isEmpty())
242 pNewDesc->addEntry(VirtualSystemDescriptionType_VendorUrl,
243 "",
244 vsysThis.strVendorUrl,
245 vsysThis.strVendorUrl);
246
247 /* VM description */
248 if (!vsysThis.strDescription.isEmpty())
249 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
250 "",
251 vsysThis.strDescription,
252 vsysThis.strDescription);
253
254 /* VM license */
255 if (!vsysThis.strLicenseText.isEmpty())
256 pNewDesc->addEntry(VirtualSystemDescriptionType_License,
257 "",
258 vsysThis.strLicenseText,
259 vsysThis.strLicenseText);
260
261 /* Now that we know the OS type, get our internal defaults based on that. */
262 ComPtr<IGuestOSType> pGuestOSType;
263 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox).raw(), pGuestOSType.asOutParam());
264 if (FAILED(rc)) throw rc;
265
266 /* CPU count */
267 ULONG cpuCountVBox;
268 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
269 if ( vsysThis.pelmVboxMachine
270 && pNewDesc->m->pConfig->hardwareMachine.cCPUs)
271 cpuCountVBox = pNewDesc->m->pConfig->hardwareMachine.cCPUs;
272 else
273 cpuCountVBox = vsysThis.cCPUs;
274 /* Check for the constraints */
275 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
276 {
277 addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for max %u CPU's only."),
278 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
279 cpuCountVBox = SchemaDefs::MaxCPUCount;
280 }
281 if (vsysThis.cCPUs == 0)
282 cpuCountVBox = 1;
283 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
284 "",
285 Utf8StrFmt("%RU32", (uint32_t)vsysThis.cCPUs),
286 Utf8StrFmt("%RU32", (uint32_t)cpuCountVBox));
287
288 /* RAM */
289 uint64_t ullMemSizeVBox;
290 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
291 if ( vsysThis.pelmVboxMachine
292 && pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB)
293 ullMemSizeVBox = pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB;
294 else
295 ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
296 /* Check for the constraints */
297 if ( ullMemSizeVBox != 0
298 && ( ullMemSizeVBox < MM_RAM_MIN_IN_MB
299 || ullMemSizeVBox > MM_RAM_MAX_IN_MB
300 )
301 )
302 {
303 addWarning(tr("The virtual system \"%s\" claims support for %llu MB RAM size, but VirtualBox has support for min %u & max %u MB RAM size only."),
304 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
305 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
306 }
307 if (vsysThis.ullMemorySize == 0)
308 {
309 /* If the RAM of the OVF is zero, use our predefined values */
310 ULONG memSizeVBox2;
311 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
312 if (FAILED(rc)) throw rc;
313 /* VBox stores that in MByte */
314 ullMemSizeVBox = (uint64_t)memSizeVBox2;
315 }
316 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
317 "",
318 Utf8StrFmt("%RU64", (uint64_t)vsysThis.ullMemorySize),
319 Utf8StrFmt("%RU64", (uint64_t)ullMemSizeVBox));
320
321 /* Audio */
322 Utf8Str strSoundCard;
323 Utf8Str strSoundCardOrig;
324 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
325 if ( vsysThis.pelmVboxMachine
326 && pNewDesc->m->pConfig->hardwareMachine.audioAdapter.fEnabled)
327 strSoundCard = Utf8StrFmt("%RU32", (uint32_t)pNewDesc->m->pConfig->hardwareMachine.audioAdapter.controllerType);
328 else if (vsysThis.strSoundCardType.isNotEmpty())
329 {
330 /* Set the AC97 always for the simple OVF case.
331 * @todo: figure out the hardware which could be possible */
332 strSoundCard = Utf8StrFmt("%RU32", (uint32_t)AudioControllerType_AC97);
333 strSoundCardOrig = vsysThis.strSoundCardType;
334 }
335 if (strSoundCard.isNotEmpty())
336 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
337 "",
338 strSoundCardOrig,
339 strSoundCard);
340
341#ifdef VBOX_WITH_USB
342 /* USB Controller */
343 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
344 if ( ( vsysThis.pelmVboxMachine
345 && pNewDesc->m->pConfig->hardwareMachine.usbController.fEnabled)
346 || vsysThis.fHasUsbController)
347 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
348#endif /* VBOX_WITH_USB */
349
350 /* Network Controller */
351 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
352 if (vsysThis.pelmVboxMachine)
353 {
354 const settings::NetworkAdaptersList &llNetworkAdapters = pNewDesc->m->pConfig->hardwareMachine.llNetworkAdapters;
355 /* Check for the constrains */
356 if (llNetworkAdapters.size() > SchemaDefs::NetworkAdapterCount)
357 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
358 vsysThis.strName.c_str(), llNetworkAdapters.size(), SchemaDefs::NetworkAdapterCount);
359 /* Iterate through all network adapters. */
360 settings::NetworkAdaptersList::const_iterator it1;
361 size_t a = 0;
362 for (it1 = llNetworkAdapters.begin();
363 it1 != llNetworkAdapters.end() && a < SchemaDefs::NetworkAdapterCount;
364 ++it1, ++a)
365 {
366 if (it1->fEnabled)
367 {
368 Utf8Str strMode = convertNetworkAttachmentTypeToString(it1->mode);
369 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
370 "", // ref
371 strMode, // orig
372 Utf8StrFmt("%RU32", (uint32_t)it1->type), // conf
373 0,
374 Utf8StrFmt("slot=%RU32;type=%s", it1->ulSlot, strMode.c_str())); // extra conf
375 }
376 }
377 }
378 /* else we use the ovf configuration. */
379 else if (size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size() > 0)
380 {
381 /* Check for the constrains */
382 if (cEthernetAdapters > SchemaDefs::NetworkAdapterCount)
383 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
384 vsysThis.strName.c_str(), cEthernetAdapters, SchemaDefs::NetworkAdapterCount);
385
386 /* Get the default network adapter type for the selected guest OS */
387 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
388 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
389 if (FAILED(rc)) throw rc;
390
391 ovf::EthernetAdaptersList::const_iterator itEA;
392 /* Iterate through all abstract networks. We support 8 network
393 * adapters at the maximum, so the first 8 will be added only. */
394 size_t a = 0;
395 for (itEA = vsysThis.llEthernetAdapters.begin();
396 itEA != vsysThis.llEthernetAdapters.end() && a < SchemaDefs::NetworkAdapterCount;
397 ++itEA, ++a)
398 {
399 const ovf::EthernetAdapter &ea = *itEA; // logical network to connect to
400 Utf8Str strNetwork = ea.strNetworkName;
401 // make sure it's one of these two
402 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
403 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
404 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
405 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
406 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
407 && (strNetwork.compare("VDE", Utf8Str::CaseInsensitive))
408 )
409 strNetwork = "Bridged"; // VMware assumes this is the default apparently
410
411 /* Figure out the hardware type */
412 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
413 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
414 {
415 /* If the default adapter is already one of the two
416 * PCNet adapters use the default one. If not use the
417 * Am79C970A as fallback. */
418 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
419 defaultAdapterVBox == NetworkAdapterType_Am79C973))
420 nwAdapterVBox = NetworkAdapterType_Am79C970A;
421 }
422#ifdef VBOX_WITH_E1000
423 /* VMWare accidentally write this with VirtualCenter 3.5,
424 so make sure in this case always to use the VMWare one */
425 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
426 nwAdapterVBox = NetworkAdapterType_I82545EM;
427 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
428 {
429 /* Check if this OVF was written by VirtualBox */
430 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
431 {
432 /* If the default adapter is already one of the three
433 * E1000 adapters use the default one. If not use the
434 * I82545EM as fallback. */
435 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
436 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
437 defaultAdapterVBox == NetworkAdapterType_I82545EM))
438 nwAdapterVBox = NetworkAdapterType_I82540EM;
439 }
440 else
441 /* Always use this one since it's what VMware uses */
442 nwAdapterVBox = NetworkAdapterType_I82545EM;
443 }
444#endif /* VBOX_WITH_E1000 */
445
446 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
447 "", // ref
448 ea.strNetworkName, // orig
449 Utf8StrFmt("%RU32", (uint32_t)nwAdapterVBox), // conf
450 0,
451 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
452 }
453 }
454
455 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
456 bool fFloppy = false;
457 bool fDVD = false;
458 if (vsysThis.pelmVboxMachine)
459 {
460 settings::StorageControllersList &llControllers = pNewDesc->m->pConfig->storageMachine.llStorageControllers;
461 settings::StorageControllersList::iterator it3;
462 for (it3 = llControllers.begin();
463 it3 != llControllers.end();
464 ++it3)
465 {
466 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
467 settings::AttachedDevicesList::iterator it4;
468 for (it4 = llAttachments.begin();
469 it4 != llAttachments.end();
470 ++it4)
471 {
472 fDVD |= it4->deviceType == DeviceType_DVD;
473 fFloppy |= it4->deviceType == DeviceType_Floppy;
474 if (fFloppy && fDVD)
475 break;
476 }
477 if (fFloppy && fDVD)
478 break;
479 }
480 }
481 else
482 {
483 fFloppy = vsysThis.fHasFloppyDrive;
484 fDVD = vsysThis.fHasCdromDrive;
485 }
486 /* Floppy Drive */
487 if (fFloppy)
488 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
489 /* CD Drive */
490 if (fDVD)
491 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
492
493 /* Hard disk Controller */
494 uint16_t cIDEused = 0;
495 uint16_t cSATAused = 0; NOREF(cSATAused);
496 uint16_t cSCSIused = 0; NOREF(cSCSIused);
497 ovf::ControllersMap::const_iterator hdcIt;
498 /* Iterate through all hard disk controllers */
499 for (hdcIt = vsysThis.mapControllers.begin();
500 hdcIt != vsysThis.mapControllers.end();
501 ++hdcIt)
502 {
503 const ovf::HardDiskController &hdc = hdcIt->second;
504 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
505
506 switch (hdc.system)
507 {
508 case ovf::HardDiskController::IDE:
509 /* Check for the constrains */
510 if (cIDEused < 4)
511 {
512 // @todo: figure out the IDE types
513 /* Use PIIX4 as default */
514 Utf8Str strType = "PIIX4";
515 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
516 strType = "PIIX3";
517 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
518 strType = "ICH6";
519 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
520 strControllerID, // strRef
521 hdc.strControllerType, // aOvfValue
522 strType); // aVboxValue
523 }
524 else
525 /* Warn only once */
526 if (cIDEused == 2)
527 addWarning(tr("The virtual \"%s\" system requests support for more than two IDE controller channels, but VirtualBox supports only two."),
528 vsysThis.strName.c_str());
529
530 ++cIDEused;
531 break;
532
533 case ovf::HardDiskController::SATA:
534 /* Check for the constrains */
535 if (cSATAused < 1)
536 {
537 // @todo: figure out the SATA types
538 /* We only support a plain AHCI controller, so use them always */
539 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
540 strControllerID,
541 hdc.strControllerType,
542 "AHCI");
543 }
544 else
545 {
546 /* Warn only once */
547 if (cSATAused == 1)
548 addWarning(tr("The virtual system \"%s\" requests support for more than one SATA controller, but VirtualBox has support for only one"),
549 vsysThis.strName.c_str());
550
551 }
552 ++cSATAused;
553 break;
554
555 case ovf::HardDiskController::SCSI:
556 /* Check for the constrains */
557 if (cSCSIused < 1)
558 {
559 VirtualSystemDescriptionType_T vsdet = VirtualSystemDescriptionType_HardDiskControllerSCSI;
560 Utf8Str hdcController = "LsiLogic";
561 if (!hdc.strControllerType.compare("lsilogicsas", Utf8Str::CaseInsensitive))
562 {
563 // OVF considers SAS a variant of SCSI but VirtualBox considers it a class of its own
564 vsdet = VirtualSystemDescriptionType_HardDiskControllerSAS;
565 hdcController = "LsiLogicSas";
566 }
567 else if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
568 hdcController = "BusLogic";
569 pNewDesc->addEntry(vsdet,
570 strControllerID,
571 hdc.strControllerType,
572 hdcController);
573 }
574 else
575 addWarning(tr("The virtual system \"%s\" requests support for an additional SCSI controller of type \"%s\" with ID %s, but VirtualBox presently supports only one SCSI controller."),
576 vsysThis.strName.c_str(),
577 hdc.strControllerType.c_str(),
578 strControllerID.c_str());
579 ++cSCSIused;
580 break;
581 }
582 }
583
584 /* Hard disks */
585 if (vsysThis.mapVirtualDisks.size() > 0)
586 {
587 ovf::VirtualDisksMap::const_iterator itVD;
588 /* Iterate through all hard disks ()*/
589 for (itVD = vsysThis.mapVirtualDisks.begin();
590 itVD != vsysThis.mapVirtualDisks.end();
591 ++itVD)
592 {
593 const ovf::VirtualDisk &hd = itVD->second;
594 /* Get the associated disk image */
595 const ovf::DiskImage &di = m->pReader->m_mapDisks[hd.strDiskId];
596
597 // @todo:
598 // - figure out all possible vmdk formats we also support
599 // - figure out if there is a url specifier for vhd already
600 // - we need a url specifier for the vdi format
601 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
602 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
603 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
604 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
605 )
606 {
607 /* If the href is empty use the VM name as filename */
608 Utf8Str strFilename = di.strHref;
609 if (!strFilename.length())
610 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
611
612 Utf8Str strTargetPath = Utf8Str(strMachineFolder)
613 .append(RTPATH_DELIMITER)
614 .append(di.strHref);
615 searchUniqueDiskImageFilePath(strTargetPath);
616
617 /* find the description for the hard disk controller
618 * that has the same ID as hd.idController */
619 const VirtualSystemDescriptionEntry *pController;
620 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
621 throw setError(E_FAIL,
622 tr("Cannot find hard disk controller with OVF instance ID %RI32 to which disk \"%s\" should be attached"),
623 hd.idController,
624 di.strHref.c_str());
625
626 /* controller to attach to, and the bus within that controller */
627 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
628 pController->ulIndex,
629 hd.ulAddressOnParent);
630 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
631 hd.strDiskId,
632 di.strHref,
633 strTargetPath,
634 di.ulSuggestedSizeMB,
635 strExtraConfig);
636 }
637 else
638 throw setError(VBOX_E_FILE_ERROR,
639 tr("Unsupported format for virtual disk image in OVF: \"%s\"", di.strFormat.c_str()));
640 }
641 }
642
643 m->virtualSystemDescriptions.push_back(pNewDesc);
644 }
645 }
646 catch (HRESULT aRC)
647 {
648 /* On error we clear the list & return */
649 m->virtualSystemDescriptions.clear();
650 rc = aRC;
651 }
652
653 // reset the appliance state
654 alock.acquire();
655 m->state = Data::ApplianceIdle;
656
657 return rc;
658}
659
660/**
661 * Public method implementation. This creates one or more new machines according to the
662 * VirtualSystemScription instances created by Appliance::Interpret().
663 * Thread implementation is in Appliance::importImpl().
664 * @param aProgress
665 * @return
666 */
667STDMETHODIMP Appliance::ImportMachines(IProgress **aProgress)
668{
669 CheckComArgOutPointerValid(aProgress);
670
671 AutoCaller autoCaller(this);
672 if (FAILED(autoCaller.rc())) return autoCaller.rc();
673
674 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
675
676 // do not allow entering this method if the appliance is busy reading or writing
677 if (!isApplianceIdle())
678 return E_ACCESSDENIED;
679
680 if (!m->pReader)
681 return setError(E_FAIL,
682 tr("Cannot import machines without reading it first (call read() before importMachines())"));
683
684 ComObjPtr<Progress> progress;
685 HRESULT rc = S_OK;
686 try
687 {
688 rc = importImpl(m->locInfo, progress);
689 }
690 catch (HRESULT aRC)
691 {
692 rc = aRC;
693 }
694
695 if (SUCCEEDED(rc))
696 /* Return progress to the caller */
697 progress.queryInterfaceTo(aProgress);
698
699 return rc;
700}
701
702////////////////////////////////////////////////////////////////////////////////
703//
704// Appliance private methods
705//
706////////////////////////////////////////////////////////////////////////////////
707
708
709/*******************************************************************************
710 * Read stuff
711 ******************************************************************************/
712
713/**
714 * Implementation for reading an OVF. This starts a new thread which will call
715 * Appliance::taskThreadImportOrExport() which will then call readFS() or readS3().
716 * This will then open the OVF with ovfreader.cpp.
717 *
718 * This is in a separate private method because it is used from three locations:
719 *
720 * 1) from the public Appliance::Read().
721 *
722 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
723 * called Appliance::readFSOVA(), which called Appliance::importImpl(), which then called this again.
724 *
725 * 3) from Appliance::readS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
726 *
727 * @param aLocInfo
728 * @param aProgress
729 * @return
730 */
731HRESULT Appliance::readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
732{
733 BstrFmt bstrDesc = BstrFmt(tr("Reading appliance '%s'"),
734 aLocInfo.strPath.c_str());
735 HRESULT rc;
736 /* Create the progress object */
737 aProgress.createObject();
738 if (aLocInfo.storageType == VFSType_File)
739 /* 1 operation only */
740 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
741 bstrDesc.raw(),
742 TRUE /* aCancelable */);
743 else
744 /* 4/5 is downloading, 1/5 is reading */
745 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
746 bstrDesc.raw(),
747 TRUE /* aCancelable */,
748 2, // ULONG cOperations,
749 5, // ULONG ulTotalOperationsWeight,
750 BstrFmt(tr("Download appliance '%s'"),
751 aLocInfo.strPath.c_str()).raw(), // CBSTR bstrFirstOperationDescription,
752 4); // ULONG ulFirstOperationWeight,
753 if (FAILED(rc)) throw rc;
754
755 /* Initialize our worker task */
756 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Read, aLocInfo, aProgress));
757
758 rc = task->startThread();
759 if (FAILED(rc)) throw rc;
760
761 /* Don't destruct on success */
762 task.release();
763
764 return rc;
765}
766
767/**
768 * Actual worker code for reading an OVF from disk. This is called from Appliance::taskThreadImportOrExport()
769 * and therefore runs on the OVF read worker thread. This opens the OVF with ovfreader.cpp.
770 *
771 * This runs in two contexts:
772 *
773 * 1) in a first worker thread; in that case, Appliance::Read() called Appliance::readImpl();
774 *
775 * 2) in a second worker thread; in that case, Appliance::Read() called Appliance::readImpl(), which
776 * called Appliance::readS3(), which called Appliance::readImpl(), which then called this.
777 *
778 * @param pTask
779 * @return
780 */
781HRESULT Appliance::readFS(TaskOVF *pTask)
782{
783 LogFlowFuncEnter();
784 LogFlowFunc(("Appliance %p\n", this));
785
786 AutoCaller autoCaller(this);
787 if (FAILED(autoCaller.rc())) return autoCaller.rc();
788
789 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
790
791 HRESULT rc = S_OK;
792
793 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
794 rc = readFSOVF(pTask);
795 else
796 rc = readFSOVA(pTask);
797
798 LogFlowFunc(("rc=%Rhrc\n", rc));
799 LogFlowFuncLeave();
800
801 return rc;
802}
803
804HRESULT Appliance::readFSOVF(TaskOVF *pTask)
805{
806 LogFlowFuncEnter();
807
808 HRESULT rc = S_OK;
809
810 PVDINTERFACEIO pSha1Callbacks = 0;
811 PVDINTERFACEIO pFileCallbacks = 0;
812 do
813 {
814 pSha1Callbacks = Sha1CreateInterface();
815 if (!pSha1Callbacks)
816 {
817 rc = E_OUTOFMEMORY;
818 break;
819 }
820 pFileCallbacks = FileCreateInterface();
821 if (!pFileCallbacks)
822 {
823 rc = E_OUTOFMEMORY;
824 break;
825 }
826 VDINTERFACE VDInterfaceIO;
827 SHA1STORAGE storage;
828 RT_ZERO(storage);
829 int vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IOFile",
830 VDINTERFACETYPE_IO, pFileCallbacks,
831 0, &storage.pVDImageIfaces);
832 if (RT_FAILURE(vrc))
833 {
834 rc = E_FAIL;
835 break;
836 }
837 rc = readFSImpl(pTask, pSha1Callbacks, &storage);
838 }while(0);
839
840 /* Cleanup */
841 if (pSha1Callbacks)
842 RTMemFree(pSha1Callbacks);
843 if (pFileCallbacks)
844 RTMemFree(pFileCallbacks);
845
846 LogFlowFunc(("rc=%Rhrc\n", rc));
847 LogFlowFuncLeave();
848
849 return rc;
850}
851
852HRESULT Appliance::readFSOVA(TaskOVF *pTask)
853{
854 LogFlowFuncEnter();
855
856 RTTAR tar;
857 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, true);
858 if (RT_FAILURE(vrc))
859 return setError(VBOX_E_FILE_ERROR,
860 tr("Could not open OVA file '%s' (%Rrc)"),
861 pTask->locInfo.strPath.c_str(), vrc);
862
863 HRESULT rc = S_OK;
864
865 PVDINTERFACEIO pSha1Callbacks = 0;
866 PVDINTERFACEIO pTarCallbacks = 0;
867 do
868 {
869 pSha1Callbacks = Sha1CreateInterface();
870 if (!pSha1Callbacks)
871 {
872 rc = E_OUTOFMEMORY;
873 break;
874 }
875 pTarCallbacks = TarCreateInterface();
876 if (!pTarCallbacks)
877 {
878 rc = E_OUTOFMEMORY;
879 break;
880 }
881 VDINTERFACE VDInterfaceIO;
882 SHA1STORAGE storage;
883 RT_ZERO(storage);
884 vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IOTar",
885 VDINTERFACETYPE_IO, pTarCallbacks,
886 tar, &storage.pVDImageIfaces);
887 if (RT_FAILURE(vrc))
888 {
889 rc = E_FAIL;
890 break;
891 }
892 rc = readFSImpl(pTask, pSha1Callbacks, &storage);
893 }while(0);
894
895 RTTarClose(tar);
896
897 /* Cleanup */
898 if (pSha1Callbacks)
899 RTMemFree(pSha1Callbacks);
900 if (pTarCallbacks)
901 RTMemFree(pTarCallbacks);
902
903 LogFlowFunc(("rc=%Rhrc\n", rc));
904 LogFlowFuncLeave();
905
906 return rc;
907}
908
909HRESULT Appliance::readFSImpl(TaskOVF *pTask, PVDINTERFACEIO pCallbacks, PSHA1STORAGE pStorage)
910{
911 LogFlowFuncEnter();
912
913 HRESULT rc = S_OK;
914
915 pStorage->fCreateDigest = true;
916
917 void *pvTmpBuf = 0;
918 try
919 {
920 Utf8Str strOvfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".ovf");
921 /* Read the OVF into a memory buffer */
922 size_t cbSize = 0;
923 int vrc = Sha1ReadBuf(strOvfFile.c_str(), &pvTmpBuf, &cbSize, pCallbacks, pStorage);
924 if ( RT_FAILURE(vrc)
925 || !pvTmpBuf)
926 throw setError(VBOX_E_FILE_ERROR,
927 tr("Could not read OVF file '%s' (%Rrc)"),
928 RTPathFilename(strOvfFile.c_str()), vrc);
929 /* Copy the SHA1 sum of the OVF file for later validation */
930 m->strOVFSHA1Digest = pStorage->strDigest;
931 /* Read & parse the XML structure of the OVF file */
932 m->pReader = new ovf::OVFReader(pvTmpBuf, cbSize, pTask->locInfo.strPath);
933 }
934 catch (iprt::Error &x) // includes all XML exceptions
935 {
936 rc = setError(VBOX_E_FILE_ERROR,
937 x.what());
938 }
939 catch (HRESULT aRC)
940 {
941 rc = aRC;
942 }
943
944 /* Cleanup */
945 if (pvTmpBuf)
946 RTMemFree(pvTmpBuf);
947
948 LogFlowFunc(("rc=%Rhrc\n", rc));
949 LogFlowFuncLeave();
950
951 return rc;
952}
953
954/**
955 * Worker code for reading OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
956 * in S3 mode and therefore runs on the OVF read worker thread. This then starts a second worker
957 * thread to create temporary files (see Appliance::readFS()).
958 *
959 * @param pTask
960 * @return
961 */
962HRESULT Appliance::readS3(TaskOVF *pTask)
963{
964 LogFlowFuncEnter();
965 LogFlowFunc(("Appliance %p\n", this));
966
967 AutoCaller autoCaller(this);
968 if (FAILED(autoCaller.rc())) return autoCaller.rc();
969
970 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
971
972 HRESULT rc = S_OK;
973 int vrc = VINF_SUCCESS;
974 RTS3 hS3 = NIL_RTS3;
975 char szOSTmpDir[RTPATH_MAX];
976 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
977 /* The template for the temporary directory created below */
978 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
979 list< pair<Utf8Str, ULONG> > filesList;
980 Utf8Str strTmpOvf;
981
982 try
983 {
984 /* Extract the bucket */
985 Utf8Str tmpPath = pTask->locInfo.strPath;
986 Utf8Str bucket;
987 parseBucket(tmpPath, bucket);
988
989 /* We need a temporary directory which we can put the OVF file & all
990 * disk images in */
991 vrc = RTDirCreateTemp(pszTmpDir);
992 if (RT_FAILURE(vrc))
993 throw setError(VBOX_E_FILE_ERROR,
994 tr("Cannot create temporary directory '%s'"), pszTmpDir);
995
996 /* The temporary name of the target OVF file */
997 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
998
999 /* Next we have to download the OVF */
1000 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1001 if (RT_FAILURE(vrc))
1002 throw setError(VBOX_E_IPRT_ERROR,
1003 tr("Cannot create S3 service handler"));
1004 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1005
1006 /* Get it */
1007 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
1008 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
1009 if (RT_FAILURE(vrc))
1010 {
1011 if (vrc == VERR_S3_CANCELED)
1012 throw S_OK; /* todo: !!!!!!!!!!!!! */
1013 else if (vrc == VERR_S3_ACCESS_DENIED)
1014 throw setError(E_ACCESSDENIED,
1015 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right."
1016 "Also check that your host clock is properly synced"),
1017 pszFilename);
1018 else if (vrc == VERR_S3_NOT_FOUND)
1019 throw setError(VBOX_E_FILE_ERROR,
1020 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1021 else
1022 throw setError(VBOX_E_IPRT_ERROR,
1023 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1024 }
1025
1026 /* Close the connection early */
1027 RTS3Destroy(hS3);
1028 hS3 = NIL_RTS3;
1029
1030 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")).raw(), 1);
1031
1032 /* Prepare the temporary reading of the OVF */
1033 ComObjPtr<Progress> progress;
1034 LocationInfo li;
1035 li.strPath = strTmpOvf;
1036 /* Start the reading from the fs */
1037 rc = readImpl(li, progress);
1038 if (FAILED(rc)) throw rc;
1039
1040 /* Unlock the appliance for the reading thread */
1041 appLock.release();
1042 /* Wait until the reading is done, but report the progress back to the
1043 caller */
1044 ComPtr<IProgress> progressInt(progress);
1045 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1046
1047 /* Again lock the appliance for the next steps */
1048 appLock.acquire();
1049 }
1050 catch(HRESULT aRC)
1051 {
1052 rc = aRC;
1053 }
1054 /* Cleanup */
1055 RTS3Destroy(hS3);
1056 /* Delete all files which where temporary created */
1057 if (RTPathExists(strTmpOvf.c_str()))
1058 {
1059 vrc = RTFileDelete(strTmpOvf.c_str());
1060 if (RT_FAILURE(vrc))
1061 rc = setError(VBOX_E_FILE_ERROR,
1062 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
1063 }
1064 /* Delete the temporary directory */
1065 if (RTPathExists(pszTmpDir))
1066 {
1067 vrc = RTDirRemove(pszTmpDir);
1068 if (RT_FAILURE(vrc))
1069 rc = setError(VBOX_E_FILE_ERROR,
1070 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1071 }
1072 if (pszTmpDir)
1073 RTStrFree(pszTmpDir);
1074
1075 LogFlowFunc(("rc=%Rhrc\n", rc));
1076 LogFlowFuncLeave();
1077
1078 return rc;
1079}
1080
1081/*******************************************************************************
1082 * Import stuff
1083 ******************************************************************************/
1084
1085/**
1086 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
1087 * Appliance::taskThreadImportOrExport().
1088 *
1089 * This creates one or more new machines according to the VirtualSystemScription instances created by
1090 * Appliance::Interpret().
1091 *
1092 * This is in a separate private method because it is used from two locations:
1093 *
1094 * 1) from the public Appliance::ImportMachines().
1095 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
1096 *
1097 * @param aLocInfo
1098 * @param aProgress
1099 * @return
1100 */
1101HRESULT Appliance::importImpl(const LocationInfo &locInfo,
1102 ComObjPtr<Progress> &progress)
1103{
1104 HRESULT rc = S_OK;
1105
1106 SetUpProgressMode mode;
1107 if (locInfo.storageType == VFSType_File)
1108 mode = ImportFile;
1109 else
1110 mode = ImportS3;
1111
1112 rc = setUpProgress(progress,
1113 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1114 mode);
1115 if (FAILED(rc)) throw rc;
1116
1117 /* Initialize our worker task */
1118 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, locInfo, progress));
1119
1120 rc = task->startThread();
1121 if (FAILED(rc)) throw rc;
1122
1123 /* Don't destruct on success */
1124 task.release();
1125
1126 return rc;
1127}
1128
1129/**
1130 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1131 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1132 * VirtualSystemScription instances created by Appliance::Interpret().
1133 *
1134 * This runs in three contexts:
1135 *
1136 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1137 *
1138 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1139 * called Appliance::importFSOVA(), which called Appliance::importImpl(), which then called this again.
1140 *
1141 * 3) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1142 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this again.
1143 *
1144 * @param pTask
1145 * @return
1146 */
1147HRESULT Appliance::importFS(TaskOVF *pTask)
1148{
1149
1150 LogFlowFuncEnter();
1151 LogFlowFunc(("Appliance %p\n", this));
1152
1153 AutoCaller autoCaller(this);
1154 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1155
1156 /* Change the appliance state so we can safely leave the lock while doing
1157 * time-consuming disk imports; also the below method calls do all kinds of
1158 * locking which conflicts with the appliance object lock. */
1159 AutoWriteLock writeLock(this COMMA_LOCKVAL_SRC_POS);
1160 /* Check if the appliance is currently busy. */
1161 if (!isApplianceIdle())
1162 return E_ACCESSDENIED;
1163 /* Set the internal state to importing. */
1164 m->state = Data::ApplianceImporting;
1165
1166 HRESULT rc = S_OK;
1167
1168 /* Clear the list of imported machines, if any */
1169 m->llGuidsMachinesCreated.clear();
1170
1171 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1172 rc = importFSOVF(pTask, writeLock);
1173 else
1174 rc = importFSOVA(pTask, writeLock);
1175
1176 if (FAILED(rc))
1177 {
1178 /* With _whatever_ error we've had, do a complete roll-back of
1179 * machines and disks we've created */
1180 writeLock.release();
1181 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
1182 itID != m->llGuidsMachinesCreated.end();
1183 ++itID)
1184 {
1185 Guid guid = *itID;
1186 Bstr bstrGuid = guid.toUtf16();
1187 ComPtr<IMachine> failedMachine;
1188 HRESULT rc2 = mVirtualBox->FindMachine(bstrGuid.raw(), failedMachine.asOutParam());
1189 if (SUCCEEDED(rc2))
1190 {
1191 SafeIfaceArray<IMedium> aMedia;
1192 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
1193 ComPtr<IProgress> pProgress2;
1194 rc2 = failedMachine->Delete(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
1195 pProgress2->WaitForCompletion(-1);
1196 }
1197 }
1198 writeLock.acquire();
1199 }
1200
1201 /* Reset the state so others can call methods again */
1202 m->state = Data::ApplianceIdle;
1203
1204 LogFlowFunc(("rc=%Rhrc\n", rc));
1205 LogFlowFuncLeave();
1206
1207 return rc;
1208}
1209
1210HRESULT Appliance::importFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1211{
1212 LogFlowFuncEnter();
1213
1214 HRESULT rc = S_OK;
1215
1216 PVDINTERFACEIO pSha1Callbacks = 0;
1217 PVDINTERFACEIO pFileCallbacks = 0;
1218 void *pvMfBuf = 0;
1219 writeLock.release();
1220 try
1221 {
1222 /* Create the necessary file access interfaces. */
1223 pSha1Callbacks = Sha1CreateInterface();
1224 if (!pSha1Callbacks)
1225 throw E_OUTOFMEMORY;
1226 pFileCallbacks = FileCreateInterface();
1227 if (!pFileCallbacks)
1228 throw E_OUTOFMEMORY;
1229
1230 VDINTERFACE VDInterfaceIO;
1231 SHA1STORAGE storage;
1232 RT_ZERO(storage);
1233 storage.fCreateDigest = true;
1234 int vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IOFile",
1235 VDINTERFACETYPE_IO, pFileCallbacks,
1236 0, &storage.pVDImageIfaces);
1237 if (RT_FAILURE(vrc))
1238 throw E_FAIL;
1239
1240 size_t cbMfSize = 0;
1241 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1242 /* Create the import stack for the rollback on errors. */
1243 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1244 /* Do we need the digest information? */
1245 storage.fCreateDigest = RTFileExists(strMfFile.c_str());
1246 /* Now import the appliance. */
1247 importMachines(stack, pSha1Callbacks, &storage);
1248 /* Read & verify the manifest file, if there is one. */
1249 if (storage.fCreateDigest)
1250 {
1251 /* Add the ovf file to the digest list. */
1252 stack.llSrcDisksDigest.push_front(STRPAIR(pTask->locInfo.strPath, m->strOVFSHA1Digest));
1253 rc = readManifestFile(strMfFile, &pvMfBuf, &cbMfSize, pSha1Callbacks, &storage);
1254 if (FAILED(rc)) throw rc;
1255 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1256 if (FAILED(rc)) throw rc;
1257 }
1258 }
1259 catch (HRESULT rc2)
1260 {
1261 rc = rc2;
1262 }
1263 writeLock.acquire();
1264
1265 /* Cleanup */
1266 if (pvMfBuf)
1267 RTMemFree(pvMfBuf);
1268 if (pSha1Callbacks)
1269 RTMemFree(pSha1Callbacks);
1270 if (pFileCallbacks)
1271 RTMemFree(pFileCallbacks);
1272
1273 LogFlowFunc(("rc=%Rhrc\n", rc));
1274 LogFlowFuncLeave();
1275
1276 return rc;
1277}
1278
1279HRESULT Appliance::importFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1280{
1281 LogFlowFuncEnter();
1282
1283 RTTAR tar;
1284 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, true);
1285 if (RT_FAILURE(vrc))
1286 return setError(VBOX_E_FILE_ERROR,
1287 tr("Could not open OVA file '%s' (%Rrc)"),
1288 pTask->locInfo.strPath.c_str(), vrc);
1289
1290 HRESULT rc = S_OK;
1291
1292 PVDINTERFACEIO pSha1Callbacks = 0;
1293 PVDINTERFACEIO pTarCallbacks = 0;
1294 void *pvMfBuf = 0;
1295 writeLock.release();
1296 try
1297 {
1298 /* Create the necessary file access interfaces. */
1299 pSha1Callbacks = Sha1CreateInterface();
1300 if (!pSha1Callbacks)
1301 throw E_OUTOFMEMORY;
1302 pTarCallbacks = TarCreateInterface();
1303 if (!pTarCallbacks)
1304 throw E_OUTOFMEMORY;
1305
1306 VDINTERFACE VDInterfaceIO;
1307 SHA1STORAGE storage;
1308 RT_ZERO(storage);
1309 vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IOTar",
1310 VDINTERFACETYPE_IO, pTarCallbacks,
1311 tar, &storage.pVDImageIfaces);
1312 if (RT_FAILURE(vrc))
1313 throw setError(E_FAIL,
1314 tr("Internal error (%Rrc)"), vrc);
1315
1316 /* Skip the OVF file, cause this was read in IAppliance::Read already. */
1317 vrc = RTTarSeekNextFile(tar);
1318 if ( RT_FAILURE(vrc)
1319 && vrc != VERR_TAR_END_OF_FILE)
1320 throw setError(E_FAIL,
1321 tr("Internal error (%Rrc)"), vrc);
1322
1323 PVDINTERFACEIO pCallbacks = pSha1Callbacks;
1324 PSHA1STORAGE pStorage = &storage;
1325
1326 /* We always need to create the digest, cause we didn't know if there
1327 * is a manifest file in the stream. */
1328 pStorage->fCreateDigest = true;
1329
1330 size_t cbMfSize = 0;
1331 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1332 /* Create the import stack for the rollback on errors. */
1333 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1334 /*
1335 * Try to read the manifest file. First try.
1336 *
1337 * Note: This isn't fatal if the file is not found. The standard
1338 * defines 3 cases.
1339 * 1. no manifest file
1340 * 2. manifest file after the OVF file
1341 * 3. manifest file after all disk files
1342 * If we want streaming capabilities, we can't check if it is there by
1343 * searching for it. We have to try to open it on all possible places.
1344 * If it fails here, we will try it again after all disks where read.
1345 */
1346 rc = readTarManifestFile(tar, strMfFile, &pvMfBuf, &cbMfSize, pCallbacks, pStorage);
1347 if (FAILED(rc)) throw rc;
1348 /* Now import the appliance. */
1349 importMachines(stack, pCallbacks, pStorage);
1350 /* Try to read the manifest file. Second try. */
1351 if (!pvMfBuf)
1352 {
1353 rc = readTarManifestFile(tar, strMfFile, &pvMfBuf, &cbMfSize, pCallbacks, pStorage);
1354 if (FAILED(rc)) throw rc;
1355 }
1356 /* If we were able to read a manifest file we can check it now. */
1357 if (pvMfBuf)
1358 {
1359 /* Add the ovf file to the digest list. */
1360 stack.llSrcDisksDigest.push_front(STRPAIR(Utf8Str(pTask->locInfo.strPath).stripExt().append(".ovf"), m->strOVFSHA1Digest));
1361 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1362 if (FAILED(rc)) throw rc;
1363 }
1364 }
1365 catch (HRESULT rc2)
1366 {
1367 rc = rc2;
1368 }
1369 writeLock.acquire();
1370
1371 RTTarClose(tar);
1372
1373 /* Cleanup */
1374 if (pvMfBuf)
1375 RTMemFree(pvMfBuf);
1376 if (pSha1Callbacks)
1377 RTMemFree(pSha1Callbacks);
1378 if (pTarCallbacks)
1379 RTMemFree(pTarCallbacks);
1380
1381 LogFlowFunc(("rc=%Rhrc\n", rc));
1382 LogFlowFuncLeave();
1383
1384 return rc;
1385}
1386
1387/**
1388 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
1389 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
1390 * thread to import from temporary files (see Appliance::importFS()).
1391 * @param pTask
1392 * @return
1393 */
1394HRESULT Appliance::importS3(TaskOVF *pTask)
1395{
1396 LogFlowFuncEnter();
1397 LogFlowFunc(("Appliance %p\n", this));
1398
1399 AutoCaller autoCaller(this);
1400 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1401
1402 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1403
1404 int vrc = VINF_SUCCESS;
1405 RTS3 hS3 = NIL_RTS3;
1406 char szOSTmpDir[RTPATH_MAX];
1407 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1408 /* The template for the temporary directory created below */
1409 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1410 list< pair<Utf8Str, ULONG> > filesList;
1411
1412 HRESULT rc = S_OK;
1413 try
1414 {
1415 /* Extract the bucket */
1416 Utf8Str tmpPath = pTask->locInfo.strPath;
1417 Utf8Str bucket;
1418 parseBucket(tmpPath, bucket);
1419
1420 /* We need a temporary directory which we can put the all disk images
1421 * in */
1422 vrc = RTDirCreateTemp(pszTmpDir);
1423 if (RT_FAILURE(vrc))
1424 throw setError(VBOX_E_FILE_ERROR,
1425 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1426
1427 /* Add every disks of every virtual system to an internal list */
1428 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1429 for (it = m->virtualSystemDescriptions.begin();
1430 it != m->virtualSystemDescriptions.end();
1431 ++it)
1432 {
1433 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1434 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1435 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1436 for (itH = avsdeHDs.begin();
1437 itH != avsdeHDs.end();
1438 ++itH)
1439 {
1440 const Utf8Str &strTargetFile = (*itH)->strOvf;
1441 if (!strTargetFile.isEmpty())
1442 {
1443 /* The temporary name of the target disk file */
1444 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
1445 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1446 }
1447 }
1448 }
1449
1450 /* Next we have to download the disk images */
1451 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1452 if (RT_FAILURE(vrc))
1453 throw setError(VBOX_E_IPRT_ERROR,
1454 tr("Cannot create S3 service handler"));
1455 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1456
1457 /* Download all files */
1458 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1459 {
1460 const pair<Utf8Str, ULONG> &s = (*it1);
1461 const Utf8Str &strSrcFile = s.first;
1462 /* Construct the source file name */
1463 char *pszFilename = RTPathFilename(strSrcFile.c_str());
1464 /* Advance to the next operation */
1465 if (!pTask->pProgress.isNull())
1466 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), s.second);
1467
1468 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
1469 if (RT_FAILURE(vrc))
1470 {
1471 if (vrc == VERR_S3_CANCELED)
1472 throw S_OK; /* todo: !!!!!!!!!!!!! */
1473 else if (vrc == VERR_S3_ACCESS_DENIED)
1474 throw setError(E_ACCESSDENIED,
1475 tr("Cannot download file '%s' from S3 storage server (Access denied). "
1476 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
1477 pszFilename);
1478 else if (vrc == VERR_S3_NOT_FOUND)
1479 throw setError(VBOX_E_FILE_ERROR,
1480 tr("Cannot download file '%s' from S3 storage server (File not found)"),
1481 pszFilename);
1482 else
1483 throw setError(VBOX_E_IPRT_ERROR,
1484 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1485 pszFilename, vrc);
1486 }
1487 }
1488
1489 /* Provide a OVF file (haven't to exist) so the import routine can
1490 * figure out where the disk images/manifest file are located. */
1491 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1492 /* Now check if there is an manifest file. This is optional. */
1493 Utf8Str strManifestFile; //= queryManifestFileName(strTmpOvf);
1494// Utf8Str strManifestFile = queryManifestFileName(strTmpOvf);
1495 char *pszFilename = RTPathFilename(strManifestFile.c_str());
1496 if (!pTask->pProgress.isNull())
1497 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), 1);
1498
1499 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
1500 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
1501 if (RT_SUCCESS(vrc))
1502 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
1503 else if (RT_FAILURE(vrc))
1504 {
1505 if (vrc == VERR_S3_CANCELED)
1506 throw S_OK; /* todo: !!!!!!!!!!!!! */
1507 else if (vrc == VERR_S3_NOT_FOUND)
1508 vrc = VINF_SUCCESS; /* Not found is ok */
1509 else if (vrc == VERR_S3_ACCESS_DENIED)
1510 throw setError(E_ACCESSDENIED,
1511 tr("Cannot download file '%s' from S3 storage server (Access denied)."
1512 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
1513 pszFilename);
1514 else
1515 throw setError(VBOX_E_IPRT_ERROR,
1516 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1517 pszFilename, vrc);
1518 }
1519
1520 /* Close the connection early */
1521 RTS3Destroy(hS3);
1522 hS3 = NIL_RTS3;
1523
1524 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")).raw(), m->ulWeightForXmlOperation);
1525
1526 ComObjPtr<Progress> progress;
1527 /* Import the whole temporary OVF & the disk images */
1528 LocationInfo li;
1529 li.strPath = strTmpOvf;
1530 rc = importImpl(li, progress);
1531 if (FAILED(rc)) throw rc;
1532
1533 /* Unlock the appliance for the fs import thread */
1534 appLock.release();
1535 /* Wait until the import is done, but report the progress back to the
1536 caller */
1537 ComPtr<IProgress> progressInt(progress);
1538 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1539
1540 /* Again lock the appliance for the next steps */
1541 appLock.acquire();
1542 }
1543 catch(HRESULT aRC)
1544 {
1545 rc = aRC;
1546 }
1547 /* Cleanup */
1548 RTS3Destroy(hS3);
1549 /* Delete all files which where temporary created */
1550 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1551 {
1552 const char *pszFilePath = (*it1).first.c_str();
1553 if (RTPathExists(pszFilePath))
1554 {
1555 vrc = RTFileDelete(pszFilePath);
1556 if (RT_FAILURE(vrc))
1557 rc = setError(VBOX_E_FILE_ERROR,
1558 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
1559 }
1560 }
1561 /* Delete the temporary directory */
1562 if (RTPathExists(pszTmpDir))
1563 {
1564 vrc = RTDirRemove(pszTmpDir);
1565 if (RT_FAILURE(vrc))
1566 rc = setError(VBOX_E_FILE_ERROR,
1567 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1568 }
1569 if (pszTmpDir)
1570 RTStrFree(pszTmpDir);
1571
1572 LogFlowFunc(("rc=%Rhrc\n", rc));
1573 LogFlowFuncLeave();
1574
1575 return rc;
1576}
1577
1578HRESULT Appliance::readManifestFile(const Utf8Str &strFile, void **ppvBuf, size_t *pcbSize, PVDINTERFACEIO pCallbacks, PSHA1STORAGE pStorage)
1579{
1580 HRESULT rc = S_OK;
1581
1582 bool fOldDigest = pStorage->fCreateDigest;
1583 pStorage->fCreateDigest = false; /* No digest for the manifest file */
1584 int vrc = Sha1ReadBuf(strFile.c_str(), ppvBuf, pcbSize, pCallbacks, pStorage);
1585 if ( RT_FAILURE(vrc)
1586 && vrc != VERR_FILE_NOT_FOUND)
1587 rc = setError(VBOX_E_FILE_ERROR,
1588 tr("Could not read manifest file '%s' (%Rrc)"),
1589 RTPathFilename(strFile.c_str()), vrc);
1590 pStorage->fCreateDigest = fOldDigest; /* Restore the old digest creation behavior again. */
1591
1592 return rc;
1593}
1594
1595HRESULT Appliance::readTarManifestFile(RTTAR tar, const Utf8Str &strFile, void **ppvBuf, size_t *pcbSize, PVDINTERFACEIO pCallbacks, PSHA1STORAGE pStorage)
1596{
1597 HRESULT rc = S_OK;
1598
1599 char *pszCurFile;
1600 int vrc = RTTarCurrentFile(tar, &pszCurFile);
1601 if (RT_SUCCESS(vrc))
1602 {
1603 if (!strcmp(pszCurFile, RTPathFilename(strFile.c_str())))
1604 rc = readManifestFile(strFile, ppvBuf, pcbSize, pCallbacks, pStorage);
1605 RTStrFree(pszCurFile);
1606 }
1607 else if (vrc != VERR_TAR_END_OF_FILE)
1608 rc = E_FAIL;
1609
1610 return rc;
1611}
1612
1613HRESULT Appliance::verifyManifestFile(const Utf8Str &strFile, ImportStack &stack, void *pvBuf, size_t cbSize)
1614{
1615 HRESULT rc = S_OK;
1616
1617 PRTMANIFESTTEST paTests = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * stack.llSrcDisksDigest.size());
1618 if (!paTests)
1619 return E_OUTOFMEMORY;
1620
1621 size_t i = 0;
1622 list<STRPAIR>::const_iterator it1;
1623 for (it1 = stack.llSrcDisksDigest.begin();
1624 it1 != stack.llSrcDisksDigest.end();
1625 ++it1, ++i)
1626 {
1627 paTests[i].pszTestFile = (*it1).first.c_str();
1628 paTests[i].pszTestDigest = (*it1).second.c_str();
1629 }
1630 size_t iFailed;
1631 int vrc = RTManifestVerifyFilesBuf(pvBuf, cbSize, paTests, stack.llSrcDisksDigest.size(), &iFailed);
1632 if (RT_UNLIKELY(vrc == VERR_MANIFEST_DIGEST_MISMATCH))
1633 rc = setError(VBOX_E_FILE_ERROR,
1634 tr("The SHA1 digest of '%s' does not match the one in '%s' (%Rrc)"),
1635 RTPathFilename(paTests[iFailed].pszTestFile), RTPathFilename(strFile.c_str()), vrc);
1636 else if (RT_FAILURE(vrc))
1637 rc = setError(VBOX_E_FILE_ERROR,
1638 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1639 RTPathFilename(strFile.c_str()), vrc);
1640
1641 RTMemFree(paTests);
1642
1643 return rc;
1644}
1645
1646
1647/**
1648 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
1649 * Throws HRESULT values on errors!
1650 *
1651 * @param hdc in: the HardDiskController structure to attach to.
1652 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
1653 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
1654 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
1655 * @param lDevice out: the device number to attach to.
1656 */
1657void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
1658 uint32_t ulAddressOnParent,
1659 Bstr &controllerType,
1660 int32_t &lControllerPort,
1661 int32_t &lDevice)
1662{
1663 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n", hdc.system, hdc.fPrimary, ulAddressOnParent));
1664
1665 switch (hdc.system)
1666 {
1667 case ovf::HardDiskController::IDE:
1668 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
1669 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
1670 // the device number can be either 0 or 1, to specify the master or the slave device,
1671 // respectively. For the secondary IDE controller, the device number is always 1 because
1672 // the master device is reserved for the CD-ROM drive.
1673 controllerType = Bstr("IDE Controller");
1674 switch (ulAddressOnParent)
1675 {
1676 case 0: // master
1677 if (!hdc.fPrimary)
1678 {
1679 // secondary master
1680 lControllerPort = (long)1;
1681 lDevice = (long)0;
1682 }
1683 else // primary master
1684 {
1685 lControllerPort = (long)0;
1686 lDevice = (long)0;
1687 }
1688 break;
1689
1690 case 1: // slave
1691 if (!hdc.fPrimary)
1692 {
1693 // secondary slave
1694 lControllerPort = (long)1;
1695 lDevice = (long)1;
1696 }
1697 else // primary slave
1698 {
1699 lControllerPort = (long)0;
1700 lDevice = (long)1;
1701 }
1702 break;
1703
1704 // used by older VBox exports
1705 case 2: // interpret this as secondary master
1706 lControllerPort = (long)1;
1707 lDevice = (long)0;
1708 break;
1709
1710 // used by older VBox exports
1711 case 3: // interpret this as secondary slave
1712 lControllerPort = (long)1;
1713 lDevice = (long)1;
1714 break;
1715
1716 default:
1717 throw setError(VBOX_E_NOT_SUPPORTED,
1718 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
1719 ulAddressOnParent);
1720 break;
1721 }
1722 break;
1723
1724 case ovf::HardDiskController::SATA:
1725 controllerType = Bstr("SATA Controller");
1726 lControllerPort = (long)ulAddressOnParent;
1727 lDevice = (long)0;
1728 break;
1729
1730 case ovf::HardDiskController::SCSI:
1731 controllerType = Bstr("SCSI Controller");
1732 lControllerPort = (long)ulAddressOnParent;
1733 lDevice = (long)0;
1734 break;
1735
1736 default: break;
1737 }
1738
1739 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
1740}
1741
1742/**
1743 * Imports one disk image. This is common code shared between
1744 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1745 * the OVF virtual systems;
1746 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1747 * tag.
1748 *
1749 * Both ways of describing machines use the OVF disk references section, so in both cases
1750 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1751 *
1752 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1753 * spec, even though this cannot really happen in the vbox:Machine case since such data
1754 * would never have been exported.
1755 *
1756 * This advances stack.pProgress by one operation with the disk's weight.
1757 *
1758 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1759 * @param ulSizeMB Size of the disk image (for progress reporting)
1760 * @param strTargetPath Where to create the target image.
1761 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1762 * @param stack
1763 */
1764void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1765 const Utf8Str &strTargetPath,
1766 ComObjPtr<Medium> &pTargetHD,
1767 ImportStack &stack,
1768 PVDINTERFACEIO pCallbacks,
1769 PSHA1STORAGE pStorage)
1770{
1771 ComObjPtr<Progress> pProgress;
1772 pProgress.createObject();
1773 HRESULT rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetPath.c_str()).raw(), TRUE);
1774 if (FAILED(rc)) throw rc;
1775
1776 /* Get the system properties. */
1777 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
1778
1779 /* First of all check if the path is an UUID. If so, the user like to
1780 * import the disk into an existing path. This is useful for iSCSI for
1781 * example. */
1782 RTUUID uuid;
1783 int vrc = RTUuidFromStr(&uuid, strTargetPath.c_str());
1784 if (vrc == VINF_SUCCESS)
1785 {
1786 rc = mVirtualBox->findHardDiskById(Guid(uuid), true, &pTargetHD);
1787 if (FAILED(rc)) throw rc;
1788 }
1789 else
1790 {
1791 Utf8Str strTrgFormat = "VMDK";
1792 if (RTPathHaveExt(strTargetPath.c_str()))
1793 {
1794 char *pszExt = RTPathExt(strTargetPath.c_str());
1795 /* Figure out which format the user like to have. Default is VMDK. */
1796 ComObjPtr<MediumFormat> trgFormat = pSysProps->mediumFormatFromExtension(&pszExt[1]);
1797 if (trgFormat.isNull())
1798 throw setError(VBOX_E_NOT_SUPPORTED,
1799 tr("Could not find a valid medium format for the target disk '%s'"),
1800 strTargetPath.c_str());
1801 /* Check the capabilities. We need create capabilities. */
1802 ULONG lCabs = 0;
1803 rc = trgFormat->COMGETTER(Capabilities)(&lCabs);
1804 if (FAILED(rc)) throw rc;
1805 if (!( ((lCabs & MediumFormatCapabilities_CreateFixed) == MediumFormatCapabilities_CreateFixed)
1806 || ((lCabs & MediumFormatCapabilities_CreateDynamic) == MediumFormatCapabilities_CreateDynamic)))
1807 throw setError(VBOX_E_NOT_SUPPORTED,
1808 tr("Could not find a valid medium format for the target disk '%s'"),
1809 strTargetPath.c_str());
1810 Bstr bstrFormatName;
1811 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
1812 if (FAILED(rc)) throw rc;
1813 strTrgFormat = Utf8Str(bstrFormatName);
1814 }
1815
1816 /* Create an IMedium object. */
1817 pTargetHD.createObject();
1818 rc = pTargetHD->init(mVirtualBox,
1819 strTrgFormat,
1820 strTargetPath,
1821 Guid::Empty, // media registry: none yet
1822 NULL /* llRegistriesThatNeedSaving */);
1823 if (FAILED(rc)) throw rc;
1824
1825 /* Now create an empty hard disk. */
1826 rc = mVirtualBox->CreateHardDisk(NULL,
1827 Bstr(strTargetPath).raw(),
1828 ComPtr<IMedium>(pTargetHD).asOutParam());
1829 if (FAILED(rc)) throw rc;
1830 }
1831
1832 const Utf8Str &strSourceOVF = di.strHref;
1833 /* Construct source file path */
1834 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1835
1836 /* If strHref is empty we have to create a new file. */
1837 if (strSourceOVF.isEmpty())
1838 {
1839 /* Create a dynamic growing disk image with the given capacity. */
1840 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, ComPtr<IProgress>(pProgress).asOutParam());
1841 if (FAILED(rc)) throw rc;
1842
1843 /* Advance to the next operation. */
1844 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()).raw(),
1845 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1846 }
1847 else
1848 {
1849 /* We need a proper source format description */
1850 ComObjPtr<MediumFormat> srcFormat;
1851 /* Which format to use? */
1852 Utf8Str strSrcFormat = "VDI";
1853 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1854 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1855 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1856 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1857 )
1858 strSrcFormat = "VMDK";
1859 srcFormat = pSysProps->mediumFormat(strSrcFormat);
1860 if (srcFormat.isNull())
1861 throw setError(VBOX_E_NOT_SUPPORTED,
1862 tr("Could not find a valid medium format for the source disk '%s'"),
1863 RTPathFilename(strSrcFilePath.c_str()));
1864
1865 /* Clone the source disk image */
1866 ComObjPtr<Medium> nullParent;
1867 rc = pTargetHD->importFile(strSrcFilePath.c_str(),
1868 srcFormat,
1869 MediumVariant_Standard,
1870 pCallbacks, pStorage,
1871 nullParent,
1872 pProgress);
1873 if (FAILED(rc)) throw rc;
1874
1875 /* Advance to the next operation. */
1876 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), RTPathFilename(strSrcFilePath.c_str())).raw(),
1877 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1878 }
1879
1880 /* Now wait for the background disk operation to complete; this throws
1881 * HRESULTs on error. */
1882 ComPtr<IProgress> pp(pProgress);
1883 waitForAsyncProgress(stack.pProgress, pp);
1884
1885 /* Add the newly create disk path + a corresponding digest the our list for
1886 * later manifest verification. */
1887 stack.llSrcDisksDigest.push_back(STRPAIR(strSrcFilePath, pStorage->strDigest));
1888}
1889
1890/**
1891 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1892 * into VirtualBox by creating an IMachine instance, which is returned.
1893 *
1894 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1895 * up any leftovers from this function. For this, the given ImportStack instance has received information
1896 * about what needs cleaning up (to support rollback).
1897 *
1898 * @param vsysThis OVF virtual system (machine) to import.
1899 * @param vsdescThis Matching virtual system description (machine) to import.
1900 * @param pNewMachine out: Newly created machine.
1901 * @param stack Cleanup stack for when this throws.
1902 */
1903void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1904 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1905 ComPtr<IMachine> &pNewMachine,
1906 ImportStack &stack,
1907 PVDINTERFACEIO pCallbacks,
1908 PSHA1STORAGE pStorage)
1909{
1910 HRESULT rc;
1911
1912 // Get the instance of IGuestOSType which matches our string guest OS type so we
1913 // can use recommended defaults for the new machine where OVF doesn't provide any
1914 ComPtr<IGuestOSType> osType;
1915 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
1916 if (FAILED(rc)) throw rc;
1917
1918 /* Create the machine */
1919 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
1920 Bstr(stack.strNameVBox).raw(),
1921 Bstr(stack.strOsTypeVBox).raw(),
1922 NULL, /* uuid */
1923 FALSE, /* fForceOverwrite */
1924 pNewMachine.asOutParam());
1925 if (FAILED(rc)) throw rc;
1926
1927 // set the description
1928 if (!stack.strDescription.isEmpty())
1929 {
1930 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
1931 if (FAILED(rc)) throw rc;
1932 }
1933
1934 // CPU count
1935 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
1936 if (FAILED(rc)) throw rc;
1937
1938 if (stack.fForceHWVirt)
1939 {
1940 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1941 if (FAILED(rc)) throw rc;
1942 }
1943
1944 // RAM
1945 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
1946 if (FAILED(rc)) throw rc;
1947
1948 /* VRAM */
1949 /* Get the recommended VRAM for this guest OS type */
1950 ULONG vramVBox;
1951 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1952 if (FAILED(rc)) throw rc;
1953
1954 /* Set the VRAM */
1955 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1956 if (FAILED(rc)) throw rc;
1957
1958 // I/O APIC: Generic OVF has no setting for this. Enable it if we
1959 // import a Windows VM because if if Windows was installed without IOAPIC,
1960 // it will not mind finding an one later on, but if Windows was installed
1961 // _with_ an IOAPIC, it will bluescreen if it's not found
1962 if (!stack.fForceIOAPIC)
1963 {
1964 Bstr bstrFamilyId;
1965 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1966 if (FAILED(rc)) throw rc;
1967 if (bstrFamilyId == "Windows")
1968 stack.fForceIOAPIC = true;
1969 }
1970
1971 if (stack.fForceIOAPIC)
1972 {
1973 ComPtr<IBIOSSettings> pBIOSSettings;
1974 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1975 if (FAILED(rc)) throw rc;
1976
1977 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1978 if (FAILED(rc)) throw rc;
1979 }
1980
1981 if (!stack.strAudioAdapter.isEmpty())
1982 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
1983 {
1984 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
1985 ComPtr<IAudioAdapter> audioAdapter;
1986 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1987 if (FAILED(rc)) throw rc;
1988 rc = audioAdapter->COMSETTER(Enabled)(true);
1989 if (FAILED(rc)) throw rc;
1990 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1991 if (FAILED(rc)) throw rc;
1992 }
1993
1994#ifdef VBOX_WITH_USB
1995 /* USB Controller */
1996 ComPtr<IUSBController> usbController;
1997 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1998 if (FAILED(rc)) throw rc;
1999 rc = usbController->COMSETTER(Enabled)(stack.fUSBEnabled);
2000 if (FAILED(rc)) throw rc;
2001#endif /* VBOX_WITH_USB */
2002
2003 /* Change the network adapters */
2004 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
2005 if (vsdeNW.size() == 0)
2006 {
2007 /* No network adapters, so we have to disable our default one */
2008 ComPtr<INetworkAdapter> nwVBox;
2009 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
2010 if (FAILED(rc)) throw rc;
2011 rc = nwVBox->COMSETTER(Enabled)(false);
2012 if (FAILED(rc)) throw rc;
2013 }
2014 else if (vsdeNW.size() > SchemaDefs::NetworkAdapterCount)
2015 throw setError(VBOX_E_FILE_ERROR,
2016 tr("Too many network adapters: OVF requests %d network adapters, but VirtualBox only supports %d"),
2017 vsdeNW.size(), SchemaDefs::NetworkAdapterCount);
2018 else
2019 {
2020 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
2021 size_t a = 0;
2022 for (nwIt = vsdeNW.begin();
2023 nwIt != vsdeNW.end();
2024 ++nwIt, ++a)
2025 {
2026 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
2027
2028 const Utf8Str &nwTypeVBox = pvsys->strVboxCurrent;
2029 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
2030 ComPtr<INetworkAdapter> pNetworkAdapter;
2031 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
2032 if (FAILED(rc)) throw rc;
2033 /* Enable the network card & set the adapter type */
2034 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
2035 if (FAILED(rc)) throw rc;
2036 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
2037 if (FAILED(rc)) throw rc;
2038
2039 // default is NAT; change to "bridged" if extra conf says so
2040 if (pvsys->strExtraConfigCurrent.endsWith("type=Bridged", Utf8Str::CaseInsensitive))
2041 {
2042 /* Attach to the right interface */
2043 rc = pNetworkAdapter->AttachToBridgedInterface();
2044 if (FAILED(rc)) throw rc;
2045 ComPtr<IHost> host;
2046 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2047 if (FAILED(rc)) throw rc;
2048 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2049 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2050 if (FAILED(rc)) throw rc;
2051 // We search for the first host network interface which
2052 // is usable for bridged networking
2053 for (size_t j = 0;
2054 j < nwInterfaces.size();
2055 ++j)
2056 {
2057 HostNetworkInterfaceType_T itype;
2058 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2059 if (FAILED(rc)) throw rc;
2060 if (itype == HostNetworkInterfaceType_Bridged)
2061 {
2062 Bstr name;
2063 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2064 if (FAILED(rc)) throw rc;
2065 /* Set the interface name to attach to */
2066 pNetworkAdapter->COMSETTER(HostInterface)(name.raw());
2067 if (FAILED(rc)) throw rc;
2068 break;
2069 }
2070 }
2071 }
2072 /* Next test for host only interfaces */
2073 else if (pvsys->strExtraConfigCurrent.endsWith("type=HostOnly", Utf8Str::CaseInsensitive))
2074 {
2075 /* Attach to the right interface */
2076 rc = pNetworkAdapter->AttachToHostOnlyInterface();
2077 if (FAILED(rc)) throw rc;
2078 ComPtr<IHost> host;
2079 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2080 if (FAILED(rc)) throw rc;
2081 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2082 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2083 if (FAILED(rc)) throw rc;
2084 // We search for the first host network interface which
2085 // is usable for host only networking
2086 for (size_t j = 0;
2087 j < nwInterfaces.size();
2088 ++j)
2089 {
2090 HostNetworkInterfaceType_T itype;
2091 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2092 if (FAILED(rc)) throw rc;
2093 if (itype == HostNetworkInterfaceType_HostOnly)
2094 {
2095 Bstr name;
2096 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2097 if (FAILED(rc)) throw rc;
2098 /* Set the interface name to attach to */
2099 pNetworkAdapter->COMSETTER(HostInterface)(name.raw());
2100 if (FAILED(rc)) throw rc;
2101 break;
2102 }
2103 }
2104 }
2105 /* Next test for internal interfaces */
2106 else if (pvsys->strExtraConfigCurrent.endsWith("type=Internal", Utf8Str::CaseInsensitive))
2107 {
2108 /* Attach to the right interface */
2109 rc = pNetworkAdapter->AttachToInternalNetwork();
2110 if (FAILED(rc)) throw rc;
2111 }
2112 /* Next test for VDE interfaces */
2113 else if (pvsys->strExtraConfigCurrent.endsWith("type=VDE", Utf8Str::CaseInsensitive))
2114 {
2115 /* Attach to the right interface */
2116 rc = pNetworkAdapter->AttachToVDE();
2117 if (FAILED(rc)) throw rc;
2118 }
2119 }
2120 }
2121
2122 // IDE Hard disk controller
2123 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2124 // In OVF (at least VMware's version of it), an IDE controller has two ports, so VirtualBox's single IDE controller
2125 // with two channels and two ports each counts as two OVF IDE controllers -- so we accept one or two such IDE controllers
2126 size_t cIDEControllers = vsdeHDCIDE.size();
2127 if (cIDEControllers > 2)
2128 throw setError(VBOX_E_FILE_ERROR,
2129 tr("Too many IDE controllers in OVF; import facility only supports two"));
2130 if (vsdeHDCIDE.size() > 0)
2131 {
2132 // one or two IDE controllers present in OVF: add one VirtualBox controller
2133 ComPtr<IStorageController> pController;
2134 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2135 if (FAILED(rc)) throw rc;
2136
2137 const char *pcszIDEType = vsdeHDCIDE.front()->strVboxCurrent.c_str();
2138 if (!strcmp(pcszIDEType, "PIIX3"))
2139 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2140 else if (!strcmp(pcszIDEType, "PIIX4"))
2141 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2142 else if (!strcmp(pcszIDEType, "ICH6"))
2143 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2144 else
2145 throw setError(VBOX_E_FILE_ERROR,
2146 tr("Invalid IDE controller type \"%s\""),
2147 pcszIDEType);
2148 if (FAILED(rc)) throw rc;
2149 }
2150
2151 /* Hard disk controller SATA */
2152 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2153 if (vsdeHDCSATA.size() > 1)
2154 throw setError(VBOX_E_FILE_ERROR,
2155 tr("Too many SATA controllers in OVF; import facility only supports one"));
2156 if (vsdeHDCSATA.size() > 0)
2157 {
2158 ComPtr<IStorageController> pController;
2159 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVboxCurrent;
2160 if (hdcVBox == "AHCI")
2161 {
2162 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(), StorageBus_SATA, pController.asOutParam());
2163 if (FAILED(rc)) throw rc;
2164 }
2165 else
2166 throw setError(VBOX_E_FILE_ERROR,
2167 tr("Invalid SATA controller type \"%s\""),
2168 hdcVBox.c_str());
2169 }
2170
2171 /* Hard disk controller SCSI */
2172 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2173 if (vsdeHDCSCSI.size() > 1)
2174 throw setError(VBOX_E_FILE_ERROR,
2175 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2176 if (vsdeHDCSCSI.size() > 0)
2177 {
2178 ComPtr<IStorageController> pController;
2179 Bstr bstrName(L"SCSI Controller");
2180 StorageBus_T busType = StorageBus_SCSI;
2181 StorageControllerType_T controllerType;
2182 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVboxCurrent;
2183 if (hdcVBox == "LsiLogic")
2184 controllerType = StorageControllerType_LsiLogic;
2185 else if (hdcVBox == "LsiLogicSas")
2186 {
2187 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2188 bstrName = L"SAS Controller";
2189 busType = StorageBus_SAS;
2190 controllerType = StorageControllerType_LsiLogicSas;
2191 }
2192 else if (hdcVBox == "BusLogic")
2193 controllerType = StorageControllerType_BusLogic;
2194 else
2195 throw setError(VBOX_E_FILE_ERROR,
2196 tr("Invalid SCSI controller type \"%s\""),
2197 hdcVBox.c_str());
2198
2199 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2200 if (FAILED(rc)) throw rc;
2201 rc = pController->COMSETTER(ControllerType)(controllerType);
2202 if (FAILED(rc)) throw rc;
2203 }
2204
2205 /* Hard disk controller SAS */
2206 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2207 if (vsdeHDCSAS.size() > 1)
2208 throw setError(VBOX_E_FILE_ERROR,
2209 tr("Too many SAS controllers in OVF; import facility only supports one"));
2210 if (vsdeHDCSAS.size() > 0)
2211 {
2212 ComPtr<IStorageController> pController;
2213 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(), StorageBus_SAS, pController.asOutParam());
2214 if (FAILED(rc)) throw rc;
2215 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2216 if (FAILED(rc)) throw rc;
2217 }
2218
2219 /* Now its time to register the machine before we add any hard disks */
2220 rc = mVirtualBox->RegisterMachine(pNewMachine);
2221 if (FAILED(rc)) throw rc;
2222
2223 // store new machine for roll-back in case of errors
2224 Bstr bstrNewMachineId;
2225 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2226 if (FAILED(rc)) throw rc;
2227 Guid uuidNewMachine(bstrNewMachineId);
2228 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2229
2230 // Add floppies and CD-ROMs to the appropriate controllers.
2231 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
2232 if (vsdeFloppy.size() > 1)
2233 throw setError(VBOX_E_FILE_ERROR,
2234 tr("Too many floppy controllers in OVF; import facility only supports one"));
2235 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
2236 if ( (vsdeFloppy.size() > 0)
2237 || (vsdeCDROM.size() > 0)
2238 )
2239 {
2240 // If there's an error here we need to close the session, so
2241 // we need another try/catch block.
2242
2243 try
2244 {
2245 // to attach things we need to open a session for the new machine
2246 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2247 if (FAILED(rc)) throw rc;
2248 stack.fSessionOpen = true;
2249
2250 ComPtr<IMachine> sMachine;
2251 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2252 if (FAILED(rc)) throw rc;
2253
2254 // floppy first
2255 if (vsdeFloppy.size() == 1)
2256 {
2257 ComPtr<IStorageController> pController;
2258 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(), StorageBus_Floppy, pController.asOutParam());
2259 if (FAILED(rc)) throw rc;
2260
2261 Bstr bstrName;
2262 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
2263 if (FAILED(rc)) throw rc;
2264
2265 // this is for rollback later
2266 MyHardDiskAttachment mhda;
2267 mhda.pMachine = pNewMachine;
2268 mhda.controllerType = bstrName;
2269 mhda.lControllerPort = 0;
2270 mhda.lDevice = 0;
2271
2272 Log(("Attaching floppy\n"));
2273
2274 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2275 mhda.lControllerPort,
2276 mhda.lDevice,
2277 DeviceType_Floppy,
2278 NULL);
2279 if (FAILED(rc)) throw rc;
2280
2281 stack.llHardDiskAttachments.push_back(mhda);
2282 }
2283
2284 // CD-ROMs next
2285 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
2286 jt != vsdeCDROM.end();
2287 ++jt)
2288 {
2289 // for now always attach to secondary master on IDE controller;
2290 // there seems to be no useful information in OVF where else to
2291 // attach it (@todo test with latest versions of OVF software)
2292
2293 // find the IDE controller
2294 const ovf::HardDiskController *pController = NULL;
2295 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
2296 kt != vsysThis.mapControllers.end();
2297 ++kt)
2298 {
2299 if (kt->second.system == ovf::HardDiskController::IDE)
2300 {
2301 pController = &kt->second;
2302 break;
2303 }
2304 }
2305
2306 if (!pController)
2307 throw setError(VBOX_E_FILE_ERROR,
2308 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
2309
2310 // this is for rollback later
2311 MyHardDiskAttachment mhda;
2312 mhda.pMachine = pNewMachine;
2313
2314 convertDiskAttachmentValues(*pController,
2315 2, // interpreted as secondary master
2316 mhda.controllerType, // Bstr
2317 mhda.lControllerPort,
2318 mhda.lDevice);
2319
2320 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
2321
2322 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2323 mhda.lControllerPort,
2324 mhda.lDevice,
2325 DeviceType_DVD,
2326 NULL);
2327 if (FAILED(rc)) throw rc;
2328
2329 stack.llHardDiskAttachments.push_back(mhda);
2330 } // end for (itHD = avsdeHDs.begin();
2331
2332 rc = sMachine->SaveSettings();
2333 if (FAILED(rc)) throw rc;
2334
2335 // only now that we're done with all disks, close the session
2336 rc = stack.pSession->UnlockMachine();
2337 if (FAILED(rc)) throw rc;
2338 stack.fSessionOpen = false;
2339 }
2340 catch(HRESULT /* aRC */)
2341 {
2342 if (stack.fSessionOpen)
2343 stack.pSession->UnlockMachine();
2344
2345 throw;
2346 }
2347 }
2348
2349 // create the hard disks & connect them to the appropriate controllers
2350 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2351 if (avsdeHDs.size() > 0)
2352 {
2353 // If there's an error here we need to close the session, so
2354 // we need another try/catch block.
2355 try
2356 {
2357 // to attach things we need to open a session for the new machine
2358 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2359 if (FAILED(rc)) throw rc;
2360 stack.fSessionOpen = true;
2361
2362 /* Iterate over all given disk images */
2363 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2364 for (itHD = avsdeHDs.begin();
2365 itHD != avsdeHDs.end();
2366 ++itHD)
2367 {
2368 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2369
2370 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
2371 // in the virtual system's disks map under that ID and also in the global images map
2372 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
2373 // and find the disk from the OVF's disk list
2374 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
2375 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
2376 || (itDiskImage == stack.mapDisks.end())
2377 )
2378 throw setError(E_FAIL,
2379 tr("Internal inconsistency looking up disk image '%s'"),
2380 vsdeHD->strRef.c_str());
2381
2382 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
2383 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
2384
2385 ComObjPtr<Medium> pTargetHD;
2386 importOneDiskImage(ovfDiskImage,
2387 vsdeHD->strVboxCurrent,
2388 pTargetHD,
2389 stack,
2390 pCallbacks,
2391 pStorage);
2392
2393 // now use the new uuid to attach the disk image to our new machine
2394 ComPtr<IMachine> sMachine;
2395 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2396 if (FAILED(rc)) throw rc;
2397
2398 // find the hard disk controller to which we should attach
2399 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
2400
2401 // this is for rollback later
2402 MyHardDiskAttachment mhda;
2403 mhda.pMachine = pNewMachine;
2404
2405 convertDiskAttachmentValues(hdc,
2406 ovfVdisk.ulAddressOnParent,
2407 mhda.controllerType, // Bstr
2408 mhda.lControllerPort,
2409 mhda.lDevice);
2410
2411 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVboxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
2412
2413 rc = sMachine->AttachDevice(mhda.controllerType.raw(), // wstring name
2414 mhda.lControllerPort, // long controllerPort
2415 mhda.lDevice, // long device
2416 DeviceType_HardDisk, // DeviceType_T type
2417 pTargetHD);
2418 if (FAILED(rc)) throw rc;
2419
2420 stack.llHardDiskAttachments.push_back(mhda);
2421
2422 rc = sMachine->SaveSettings();
2423 if (FAILED(rc)) throw rc;
2424 } // end for (itHD = avsdeHDs.begin();
2425
2426 // only now that we're done with all disks, close the session
2427 rc = stack.pSession->UnlockMachine();
2428 if (FAILED(rc)) throw rc;
2429 stack.fSessionOpen = false;
2430 }
2431 catch(HRESULT /* aRC */)
2432 {
2433 if (stack.fSessionOpen)
2434 stack.pSession->UnlockMachine();
2435
2436 throw;
2437 }
2438 }
2439}
2440
2441/**
2442 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
2443 * structure) into VirtualBox by creating an IMachine instance, which is returned.
2444 *
2445 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2446 * up any leftovers from this function. For this, the given ImportStack instance has received information
2447 * about what needs cleaning up (to support rollback).
2448 *
2449 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
2450 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
2451 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
2452 * will most probably work, reimporting them into the same host will cause conflicts, so we always
2453 * generate new ones on import. This involves the following:
2454 *
2455 * 1) Scan the machine config for disk attachments.
2456 *
2457 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
2458 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
2459 * replace the old UUID with the new one.
2460 *
2461 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
2462 * caller has modified them using setFinalValues().
2463 *
2464 * 4) Create the VirtualBox machine with the modfified machine config.
2465 *
2466 * @param config
2467 * @param pNewMachine
2468 * @param stack
2469 */
2470void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
2471 ComPtr<IMachine> &pReturnNewMachine,
2472 ImportStack &stack,
2473 PVDINTERFACEIO pCallbacks,
2474 PSHA1STORAGE pStorage)
2475{
2476 Assert(vsdescThis->m->pConfig);
2477
2478 HRESULT rc = S_OK;
2479
2480 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
2481
2482 /*
2483 *
2484 * step 1): modify machine config according to OVF config, in case the user
2485 * has modified them using setFinalValues()
2486 *
2487 */
2488
2489 /* OS Type */
2490 config.machineUserData.strOsType = stack.strOsTypeVBox;
2491 /* Description */
2492 config.machineUserData.strDescription = stack.strDescription;
2493 /* CPU count & extented attributes */
2494 config.hardwareMachine.cCPUs = stack.cCPUs;
2495 if (stack.fForceIOAPIC)
2496 config.hardwareMachine.fHardwareVirt = true;
2497 if (stack.fForceIOAPIC)
2498 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
2499 /* RAM size */
2500 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
2501
2502/*
2503 <const name="HardDiskControllerIDE" value="14" />
2504 <const name="HardDiskControllerSATA" value="15" />
2505 <const name="HardDiskControllerSCSI" value="16" />
2506 <const name="HardDiskControllerSAS" value="17" />
2507*/
2508
2509#ifdef VBOX_WITH_USB
2510 /* USB controller */
2511 config.hardwareMachine.usbController.fEnabled = stack.fUSBEnabled;
2512#endif
2513 /* Audio adapter */
2514 if (stack.strAudioAdapter.isNotEmpty())
2515 {
2516 config.hardwareMachine.audioAdapter.fEnabled = true;
2517 config.hardwareMachine.audioAdapter.controllerType = (AudioControllerType_T)stack.strAudioAdapter.toUInt32();
2518 }
2519 else
2520 config.hardwareMachine.audioAdapter.fEnabled = false;
2521 /* Network adapter */
2522 settings::NetworkAdaptersList &llNetworkAdapters = config.hardwareMachine.llNetworkAdapters;
2523 /* First disable all network cards, they will be enabled below again. */
2524 settings::NetworkAdaptersList::iterator it1;
2525 for (it1 = llNetworkAdapters.begin(); it1 != llNetworkAdapters.end(); ++it1)
2526 it1->fEnabled = false;
2527 /* Now iterate over all network entries. */
2528 std::list<VirtualSystemDescriptionEntry*> avsdeNWs = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
2529 if (avsdeNWs.size() > 0)
2530 {
2531 /* Iterate through all network adapter entries and search for the
2532 * corrosponding one in the machine config. If one is found, configure
2533 * it based on the user settings. */
2534 list<VirtualSystemDescriptionEntry*>::const_iterator itNW;
2535 for (itNW = avsdeNWs.begin();
2536 itNW != avsdeNWs.end();
2537 ++itNW)
2538 {
2539 VirtualSystemDescriptionEntry *vsdeNW = *itNW;
2540 if ( vsdeNW->strExtraConfigCurrent.startsWith("slot=", Utf8Str::CaseInsensitive)
2541 && vsdeNW->strExtraConfigCurrent.length() > 6)
2542 {
2543 uint32_t iSlot = vsdeNW->strExtraConfigCurrent.substr(5, 1).toUInt32();
2544 /* Iterate through all network adapters in the machine config. */
2545 for (it1 = llNetworkAdapters.begin();
2546 it1 != llNetworkAdapters.end();
2547 ++it1)
2548 {
2549 /* Compare the slots. */
2550 if (it1->ulSlot == iSlot)
2551 {
2552 it1->fEnabled = true;
2553 it1->type = (NetworkAdapterType_T)vsdeNW->strVboxCurrent.toUInt32();
2554 break;
2555 }
2556 }
2557 }
2558 }
2559 }
2560
2561 /* Floppy controller */
2562 bool fFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy).size() > 0;
2563 /* DVD controller */
2564 bool fDVD = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM).size() > 0;
2565 /* Iterate over all storage controller check the attachments and remove
2566 * them when necessary. */
2567 settings::StorageControllersList &llControllers = config.storageMachine.llStorageControllers;
2568 settings::StorageControllersList::iterator it3;
2569 for (it3 = llControllers.begin();
2570 it3 != llControllers.end();
2571 ++it3)
2572 {
2573 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
2574 settings::AttachedDevicesList::iterator it4;
2575 for (it4 = llAttachments.begin();
2576 it4 != llAttachments.end();
2577 ++it4)
2578 {
2579 if ( ( !fDVD
2580 && it4->deviceType == DeviceType_DVD)
2581 ||
2582 ( !fFloppy
2583 && it4->deviceType == DeviceType_Floppy))
2584 llAttachments.erase(it4++);
2585 }
2586 }
2587
2588
2589 /*
2590 *
2591 * step 2: scan the machine config for media attachments
2592 *
2593 */
2594
2595 // for each storage controller...
2596 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
2597 sit != config.storageMachine.llStorageControllers.end();
2598 ++sit)
2599 {
2600 settings::StorageController &sc = *sit;
2601
2602 // find the OVF virtual system description entry for this storage controller
2603 switch (sc.storageBus)
2604 {
2605 case StorageBus_SATA:
2606 break;
2607 case StorageBus_SCSI:
2608 break;
2609 case StorageBus_IDE:
2610 break;
2611 case StorageBus_SAS:
2612 break;
2613 }
2614
2615 /* Get all hard disk descriptions. */
2616 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2617
2618 // for each medium attachment to this controller...
2619 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
2620 dit != sc.llAttachedDevices.end();
2621 ++dit)
2622 {
2623 settings::AttachedDevice &d = *dit;
2624
2625 if (d.uuid.isEmpty())
2626 // empty DVD and floppy media
2627 continue;
2628
2629 // convert the Guid to string
2630 Utf8Str strUuid = d.uuid.toString();
2631
2632
2633 // there must be an image in the OVF disk structs with the same UUID
2634 bool fFound = false;
2635 for (ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2636 oit != stack.mapDisks.end();
2637 ++oit)
2638 {
2639 const ovf::DiskImage &di = oit->second;
2640
2641 if (di.uuidVbox == strUuid)
2642 {
2643 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
2644
2645 /* Iterate over all given disk images of the virtual system
2646 * disks description. We need to find the target disk path,
2647 * which could be changed by the user. */
2648 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2649 for (itHD = avsdeHDs.begin();
2650 itHD != avsdeHDs.end();
2651 ++itHD)
2652 {
2653 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2654 if (vsdeHD->strRef == oit->first)
2655 {
2656 vsdeTargetHD = vsdeHD;
2657 break;
2658 }
2659 }
2660 if (!vsdeTargetHD)
2661 throw setError(E_FAIL,
2662 tr("Internal inconsistency looking up disk image '%s'"),
2663 oit->first.c_str());
2664
2665 /*
2666 *
2667 * step 3: import disk
2668 *
2669 */
2670 ComObjPtr<Medium> pTargetHD;
2671 importOneDiskImage(di,
2672 vsdeTargetHD->strVboxCurrent,
2673 pTargetHD,
2674 stack,
2675 pCallbacks,
2676 pStorage);
2677
2678 // ... and replace the old UUID in the machine config with the one of
2679 // the imported disk that was just created
2680 Bstr hdId;
2681 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
2682 if (FAILED(rc)) throw rc;
2683
2684 d.uuid = hdId;
2685
2686 fFound = true;
2687 break;
2688 }
2689 }
2690
2691 // no disk with such a UUID found:
2692 if (!fFound)
2693 throw setError(E_FAIL,
2694 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s but the OVF describes no such image"),
2695 strUuid.c_str());
2696 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
2697 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
2698
2699 /*
2700 *
2701 * step 4): create the machine and have it import the config
2702 *
2703 */
2704
2705 ComObjPtr<Machine> pNewMachine;
2706 rc = pNewMachine.createObject();
2707 if (FAILED(rc)) throw rc;
2708
2709 // this magic constructor fills the new machine object with the MachineConfig
2710 // instance that we created from the vbox:Machine
2711 rc = pNewMachine->init(mVirtualBox,
2712 stack.strNameVBox, // name from OVF preparations; can be suffixed to avoid duplicates, or changed by user
2713 config); // the whole machine config
2714 if (FAILED(rc)) throw rc;
2715
2716 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
2717
2718 // and register it
2719 rc = mVirtualBox->RegisterMachine(pNewMachine);
2720 if (FAILED(rc)) throw rc;
2721
2722 // store new machine for roll-back in case of errors
2723 Bstr bstrNewMachineId;
2724 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2725 if (FAILED(rc)) throw rc;
2726 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
2727}
2728
2729void Appliance::importMachines(ImportStack &stack,
2730 PVDINTERFACEIO pCallbacks,
2731 PSHA1STORAGE pStorage)
2732{
2733 HRESULT rc = S_OK;
2734
2735 // this is safe to access because this thread only gets started
2736 // if pReader != NULL
2737 const ovf::OVFReader &reader = *m->pReader;
2738
2739 // create a session for the machine + disks we manipulate below
2740 rc = stack.pSession.createInprocObject(CLSID_Session);
2741 if (FAILED(rc)) throw rc;
2742
2743 list<ovf::VirtualSystem>::const_iterator it;
2744 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
2745 /* Iterate through all virtual systems of that appliance */
2746 size_t i = 0;
2747 for (it = reader.m_llVirtualSystems.begin(),
2748 it1 = m->virtualSystemDescriptions.begin();
2749 it != reader.m_llVirtualSystems.end();
2750 ++it, ++it1, ++i)
2751 {
2752 const ovf::VirtualSystem &vsysThis = *it;
2753 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
2754
2755 ComPtr<IMachine> pNewMachine;
2756
2757 // there are two ways in which we can create a vbox machine from OVF:
2758 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
2759 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
2760 // with all the machine config pretty-parsed;
2761 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
2762 // VirtualSystemDescriptionEntry and do import work
2763
2764 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
2765 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
2766
2767 // VM name
2768 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2769 if (vsdeName.size() < 1)
2770 throw setError(VBOX_E_FILE_ERROR,
2771 tr("Missing VM name"));
2772 stack.strNameVBox = vsdeName.front()->strVboxCurrent;
2773
2774 // have VirtualBox suggest where the filename would be placed so we can
2775 // put the disk images in the same directory
2776 Bstr bstrMachineFilename;
2777 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
2778 NULL,
2779 bstrMachineFilename.asOutParam());
2780 if (FAILED(rc)) throw rc;
2781 // and determine the machine folder from that
2782 stack.strMachineFolder = bstrMachineFilename;
2783 stack.strMachineFolder.stripFilename();
2784
2785 // guest OS type
2786 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
2787 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
2788 if (vsdeOS.size() < 1)
2789 throw setError(VBOX_E_FILE_ERROR,
2790 tr("Missing guest OS type"));
2791 stack.strOsTypeVBox = vsdeOS.front()->strVboxCurrent;
2792
2793 // CPU count
2794 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
2795 if (vsdeCPU.size() != 1)
2796 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
2797
2798 stack.cCPUs = vsdeCPU.front()->strVboxCurrent.toUInt32();
2799 // We need HWVirt & IO-APIC if more than one CPU is requested
2800 if (stack.cCPUs > 1)
2801 {
2802 stack.fForceHWVirt = true;
2803 stack.fForceIOAPIC = true;
2804 }
2805
2806 // RAM
2807 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
2808 if (vsdeRAM.size() != 1)
2809 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
2810 stack.ulMemorySizeMB = (ULONG)vsdeRAM.front()->strVboxCurrent.toUInt64();
2811
2812#ifdef VBOX_WITH_USB
2813 // USB controller
2814 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
2815 // USB support is enabled if there's at least one such entry; to disable USB support,
2816 // the type of the USB item would have been changed to "ignore"
2817 stack.fUSBEnabled = vsdeUSBController.size() > 0;
2818#endif
2819 // audio adapter
2820 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
2821 /* @todo: we support one audio adapter only */
2822 if (vsdeAudioAdapter.size() > 0)
2823 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVboxCurrent;
2824
2825 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
2826 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
2827 if (vsdeDescription.size())
2828 stack.strDescription = vsdeDescription.front()->strVboxCurrent;
2829
2830 // import vbox:machine or OVF now
2831 if (vsdescThis->m->pConfig)
2832 // vbox:Machine config
2833 importVBoxMachine(vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
2834 else
2835 // generic OVF config
2836 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
2837
2838 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
2839}
2840
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette