VirtualBox

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

Last change on this file since 31907 was 31676, checked in by vboxsync, 14 years ago

Main/FE/Qt4: add initial OVA support

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