VirtualBox

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

Last change on this file since 32953 was 32751, checked in by vboxsync, 14 years ago

Runtime: initial VFS support for tar

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 105.3 KB
Line 
1/* $Id: ApplianceImplImport.cpp 32751 2010-09-24 09:34:18Z 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)) throw rc;
157 rc = pNewDesc->init();
158 if (FAILED(rc)) throw rc;
159
160 // if the virtual system in OVF had a <vbox:Machine> element, have the
161 // VirtualBox settings code parse that XML now
162 if (vsysThis.pelmVboxMachine)
163 pNewDesc->importVboxMachineXML(*vsysThis.pelmVboxMachine);
164
165 /* Guest OS type */
166 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).raw(), pGuestOSType.asOutParam());
238 if (FAILED(rc)) throw 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)) throw 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)) throw 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 throw 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 throw 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.raw(),
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.raw(),
633 TRUE /* aCancelable */,
634 2, // ULONG cOperations,
635 5, // ULONG ulTotalOperationsWeight,
636 BstrFmt(tr("Download appliance '%s'"),
637 aLocInfo.strPath.c_str()).raw(), // CBSTR bstrFirstOperationDescription,
638 4); // ULONG ulFirstOperationWeight,
639 if (FAILED(rc)) throw 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)) throw 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 = RTSha1DigestFromFile(locInfo.strPath.c_str(), &pszDigest, NULL, NULL);
694 if (RT_FAILURE(vrc))
695 throw 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 HRESULT rc = S_OK;
727 void *pvBuf = 0;
728
729 try
730 {
731 Utf8Str tmpPath = locInfo.strPath;
732 /* Remove the ova extension */
733 tmpPath.stripExt();
734 /* add the ovf extension. */
735 tmpPath += ".ovf";
736 char* pcszOVFName = RTPathFilename(tmpPath.c_str());
737
738 /* Read the OVF into a memory buffer */
739 size_t cbSize;
740 int vrc = RTTarExtractFileToBuf(locInfo.strPath.c_str(), &pvBuf, &cbSize, pcszOVFName, 0, 0);
741 if (RT_FAILURE(vrc))
742 {
743 if (vrc == VERR_FILE_NOT_FOUND)
744 throw setError(VBOX_E_IPRT_ERROR,
745 tr("Can't find ovf file '%s' in archive '%s' (%Rrc)"), pcszOVFName, locInfo.strPath.c_str(), vrc);
746 else
747 throw setError(VBOX_E_IPRT_ERROR,
748 tr("Can't unpack the archive file '%s' (%Rrc)"), locInfo.strPath.c_str(), vrc);
749 }
750
751 /* Read & parse the XML structure of the OVF file */
752 m->pReader = new ovf::OVFReader(pvBuf, cbSize, locInfo.strPath);
753 /* Create the SHA1 sum of the OVF file for later validation */
754 char *pszDigest;
755 vrc = RTSha1Digest(pvBuf, cbSize, &pszDigest, 0, 0);
756 if (RT_FAILURE(vrc))
757 throw setError(VBOX_E_FILE_ERROR,
758 tr("Couldn't calculate SHA1 digest for file '%s' (%Rrc)"),
759 RTPathFilename(locInfo.strPath.c_str()), vrc);
760 m->strOVFSHA1Digest = pszDigest;
761 RTStrFree(pszDigest);
762
763 }
764 catch (iprt::Error &x) // includes all XML exceptions
765 {
766 rc = setError(VBOX_E_FILE_ERROR,
767 x.what());
768 }
769 catch (HRESULT aRC)
770 {
771 rc = aRC;
772 }
773
774 /* Cleanup the OVF memory buffer */
775 if (pvBuf)
776 RTMemFree(pvBuf);
777
778 LogFlowFunc(("rc=%Rhrc\n", rc));
779 LogFlowFuncLeave();
780
781 return rc;
782}
783
784/**
785 * Worker code for reading OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
786 * in S3 mode and therefore runs on the OVF read worker thread. This then starts a second worker
787 * thread to create temporary files (see Appliance::readFS()).
788 *
789 * @param pTask
790 * @return
791 */
792HRESULT Appliance::readS3(TaskOVF *pTask)
793{
794 LogFlowFuncEnter();
795 LogFlowFunc(("Appliance %p\n", this));
796
797 AutoCaller autoCaller(this);
798 if (FAILED(autoCaller.rc())) return autoCaller.rc();
799
800 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
801
802 HRESULT rc = S_OK;
803 int vrc = VINF_SUCCESS;
804 RTS3 hS3 = NIL_RTS3;
805 char szOSTmpDir[RTPATH_MAX];
806 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
807 /* The template for the temporary directory created below */
808 char *pszTmpDir;
809 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
810 list< pair<Utf8Str, ULONG> > filesList;
811 Utf8Str strTmpOvf;
812
813 try
814 {
815 /* Extract the bucket */
816 Utf8Str tmpPath = pTask->locInfo.strPath;
817 Utf8Str bucket;
818 parseBucket(tmpPath, bucket);
819
820 /* We need a temporary directory which we can put the OVF file & all
821 * disk images in */
822 vrc = RTDirCreateTemp(pszTmpDir);
823 if (RT_FAILURE(vrc))
824 throw setError(VBOX_E_FILE_ERROR,
825 tr("Cannot create temporary directory '%s'"), pszTmpDir);
826
827 /* The temporary name of the target OVF file */
828 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
829
830 /* Next we have to download the OVF */
831 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
832 if (RT_FAILURE(vrc))
833 throw setError(VBOX_E_IPRT_ERROR,
834 tr("Cannot create S3 service handler"));
835 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
836
837 /* Get it */
838 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
839 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
840 if (RT_FAILURE(vrc))
841 {
842 if (vrc == VERR_S3_CANCELED)
843 throw S_OK; /* todo: !!!!!!!!!!!!! */
844 else if (vrc == VERR_S3_ACCESS_DENIED)
845 throw setError(E_ACCESSDENIED,
846 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right."
847 "Also check that your host clock is properly synced"),
848 pszFilename);
849 else if (vrc == VERR_S3_NOT_FOUND)
850 throw setError(VBOX_E_FILE_ERROR,
851 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
852 else
853 throw setError(VBOX_E_IPRT_ERROR,
854 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
855 }
856
857 /* Close the connection early */
858 RTS3Destroy(hS3);
859 hS3 = NIL_RTS3;
860
861 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")).raw(), 1);
862
863 /* Prepare the temporary reading of the OVF */
864 ComObjPtr<Progress> progress;
865 LocationInfo li;
866 li.strPath = strTmpOvf;
867 /* Start the reading from the fs */
868 rc = readImpl(li, progress);
869 if (FAILED(rc)) throw rc;
870
871 /* Unlock the appliance for the reading thread */
872 appLock.release();
873 /* Wait until the reading is done, but report the progress back to the
874 caller */
875 ComPtr<IProgress> progressInt(progress);
876 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
877
878 /* Again lock the appliance for the next steps */
879 appLock.acquire();
880 }
881 catch(HRESULT aRC)
882 {
883 rc = aRC;
884 }
885 /* Cleanup */
886 RTS3Destroy(hS3);
887 /* Delete all files which where temporary created */
888 if (RTPathExists(strTmpOvf.c_str()))
889 {
890 vrc = RTFileDelete(strTmpOvf.c_str());
891 if (RT_FAILURE(vrc))
892 rc = setError(VBOX_E_FILE_ERROR,
893 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
894 }
895 /* Delete the temporary directory */
896 if (RTPathExists(pszTmpDir))
897 {
898 vrc = RTDirRemove(pszTmpDir);
899 if (RT_FAILURE(vrc))
900 rc = setError(VBOX_E_FILE_ERROR,
901 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
902 }
903 if (pszTmpDir)
904 RTStrFree(pszTmpDir);
905
906 LogFlowFunc(("rc=%Rhrc\n", rc));
907 LogFlowFuncLeave();
908
909 return rc;
910}
911
912/**
913 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
914 * Throws HRESULT values on errors!
915 *
916 * @param hdc in: the HardDiskController structure to attach to.
917 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
918 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
919 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
920 * @param lDevice out: the device number to attach to.
921 */
922void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
923 uint32_t ulAddressOnParent,
924 Bstr &controllerType,
925 int32_t &lControllerPort,
926 int32_t &lDevice)
927{
928 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n", hdc.system, hdc.fPrimary, ulAddressOnParent));
929
930 switch (hdc.system)
931 {
932 case ovf::HardDiskController::IDE:
933 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
934 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
935 // the device number can be either 0 or 1, to specify the master or the slave device,
936 // respectively. For the secondary IDE controller, the device number is always 1 because
937 // the master device is reserved for the CD-ROM drive.
938 controllerType = Bstr("IDE Controller");
939 switch (ulAddressOnParent)
940 {
941 case 0: // master
942 if (!hdc.fPrimary)
943 {
944 // secondary master
945 lControllerPort = (long)1;
946 lDevice = (long)0;
947 }
948 else // primary master
949 {
950 lControllerPort = (long)0;
951 lDevice = (long)0;
952 }
953 break;
954
955 case 1: // slave
956 if (!hdc.fPrimary)
957 {
958 // secondary slave
959 lControllerPort = (long)1;
960 lDevice = (long)1;
961 }
962 else // primary slave
963 {
964 lControllerPort = (long)0;
965 lDevice = (long)1;
966 }
967 break;
968
969 // used by older VBox exports
970 case 2: // interpret this as secondary master
971 lControllerPort = (long)1;
972 lDevice = (long)0;
973 break;
974
975 // used by older VBox exports
976 case 3: // interpret this as secondary slave
977 lControllerPort = (long)1;
978 lDevice = (long)1;
979 break;
980
981 default:
982 throw setError(VBOX_E_NOT_SUPPORTED,
983 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
984 ulAddressOnParent);
985 break;
986 }
987 break;
988
989 case ovf::HardDiskController::SATA:
990 controllerType = Bstr("SATA Controller");
991 lControllerPort = (long)ulAddressOnParent;
992 lDevice = (long)0;
993 break;
994
995 case ovf::HardDiskController::SCSI:
996 controllerType = Bstr("SCSI Controller");
997 lControllerPort = (long)ulAddressOnParent;
998 lDevice = (long)0;
999 break;
1000
1001 default: break;
1002 }
1003
1004 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
1005}
1006
1007/**
1008 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
1009 * Appliance::taskThreadImportOrExport().
1010 *
1011 * This creates one or more new machines according to the VirtualSystemScription instances created by
1012 * Appliance::Interpret().
1013 *
1014 * This is in a separate private method because it is used from two locations:
1015 *
1016 * 1) from the public Appliance::ImportMachines().
1017 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
1018 *
1019 * @param aLocInfo
1020 * @param aProgress
1021 * @return
1022 */
1023HRESULT Appliance::importImpl(const LocationInfo &locInfo,
1024 ComObjPtr<Progress> &progress)
1025{
1026 HRESULT rc = S_OK;
1027
1028 SetUpProgressMode mode;
1029 if (locInfo.storageType == VFSType_File)
1030 {
1031 mode = ImportFileNoManifest;
1032 Utf8Str strMfFile = manifestFileName(locInfo.strPath);
1033 if (!locInfo.strPath.endsWith(".ova", Utf8Str::CaseInsensitive))
1034 {
1035 if (RTPathExists(strMfFile.c_str()))
1036 mode = ImportFileWithManifest;
1037 }
1038 else
1039 {
1040 if (RTTarFileExists(locInfo.strPath.c_str(), RTPathFilename(strMfFile.c_str())) == VINF_SUCCESS)
1041 mode = ImportFileWithManifest;
1042 }
1043 }
1044 else
1045 mode = ImportS3;
1046
1047 rc = setUpProgress(locInfo,
1048 progress,
1049 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1050 mode);
1051 if (FAILED(rc)) throw rc;
1052
1053 /* Initialize our worker task */
1054 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, locInfo, progress));
1055
1056 rc = task->startThread();
1057 if (FAILED(rc)) throw rc;
1058
1059 /* Don't destruct on success */
1060 task.release();
1061
1062 return rc;
1063}
1064
1065/**
1066 * Checks if a manifest file exists in the given location and, if so, verifies
1067 * that the relevant files (the OVF XML and the disks referenced by it, as
1068 * represented by the VirtualSystemDescription instances contained in this appliance)
1069 * match it. Requires a previous read() and interpret().
1070 *
1071 * @param locInfo
1072 * @param reader
1073 * @return
1074 */
1075HRESULT Appliance::manifestVerify(const LocationInfo &locInfo,
1076 const ovf::OVFReader &reader,
1077 ComObjPtr<Progress> &pProgress)
1078{
1079 HRESULT rc = S_OK;
1080
1081 Utf8Str strManifestFile = manifestFileName(locInfo.strPath);
1082 if (!strManifestFile.isEmpty())
1083 {
1084 const char *pcszManifestFileOnly = RTPathFilename(strManifestFile.c_str());
1085 pProgress->SetNextOperation(BstrFmt(tr("Verifying manifest file '%s'"), pcszManifestFileOnly).raw(),
1086 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally
1087
1088 list<Utf8Str> filesList;
1089 Utf8Str strSrcDir(locInfo.strPath);
1090 strSrcDir.stripFilename();
1091 // add every disks of every virtual system to an internal list
1092 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1093 for (it = m->virtualSystemDescriptions.begin();
1094 it != m->virtualSystemDescriptions.end();
1095 ++it)
1096 {
1097 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1098 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1099 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1100 for (itH = avsdeHDs.begin();
1101 itH != avsdeHDs.end();
1102 ++itH)
1103 {
1104 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1105 // find the disk from the OVF's disk list
1106 ovf::DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1107 const ovf::DiskImage &di = itDiskImage->second;
1108 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1109 filesList.push_back(strSrcFilePath);
1110 }
1111 }
1112
1113 // create the test list
1114 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST) * (filesList.size() + 1));
1115 pTestList[0].pszTestFile = (char*)locInfo.strPath.c_str();
1116 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1117 int vrc = VINF_SUCCESS;
1118 size_t i = 1;
1119 list<Utf8Str>::const_iterator it1;
1120 for (it1 = filesList.begin();
1121 it1 != filesList.end();
1122 ++it1, ++i)
1123 {
1124 char* pszDigest;
1125 vrc = RTSha1DigestFromFile((*it1).c_str(), &pszDigest, NULL, NULL);
1126 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1127 pTestList[i].pszTestDigest = pszDigest;
1128 }
1129
1130 // this call can take a very long time
1131 size_t cIndexOnError;
1132 vrc = RTManifestVerify(strManifestFile.c_str(),
1133 pTestList,
1134 filesList.size() + 1,
1135 &cIndexOnError);
1136
1137 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1138 rc = setError(VBOX_E_FILE_ERROR,
1139 tr("The SHA1 digest of '%s' does not match the one in '%s'"),
1140 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1141 pcszManifestFileOnly);
1142 else if (RT_FAILURE(vrc))
1143 rc = setError(VBOX_E_FILE_ERROR,
1144 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1145 pcszManifestFileOnly,
1146 vrc);
1147
1148 // clean up
1149 for (size_t j = 1;
1150 j < filesList.size();
1151 ++j)
1152 RTStrFree(pTestList[j].pszTestDigest);
1153 RTMemFree(pTestList);
1154 }
1155
1156 return rc;
1157}
1158
1159/**
1160 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1161 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1162 * VirtualSystemScription instances created by Appliance::Interpret().
1163 *
1164 * This runs in three contexts:
1165 *
1166 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1167 *
1168 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1169 * called Appliance::importFSOVA(), which called Appliance::importImpl(), which then called this again.
1170 *
1171 * 3) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1172 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this again.
1173 *
1174 * @param pTask
1175 * @return
1176 */
1177HRESULT Appliance::importFS(TaskOVF *pTask)
1178{
1179 if (!Utf8Str(RTPathExt(pTask->locInfo.strPath.c_str())).compare(".ovf", Utf8Str::CaseInsensitive))
1180 return importFSOVF(pTask);
1181 else
1182 return importFSOVA(pTask);
1183}
1184
1185HRESULT Appliance::importFSOVF(TaskOVF *pTask)
1186{
1187 LogFlowFuncEnter();
1188 LogFlowFunc(("Appliance %p\n", this));
1189
1190 AutoCaller autoCaller(this);
1191 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1192
1193 Assert(!pTask->pProgress.isNull());
1194
1195 // Change the appliance state so we can safely leave the lock while doing time-consuming
1196 // disk imports; also the below method calls do all kinds of locking which conflicts with
1197 // the appliance object lock
1198 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1199 if (!isApplianceIdle())
1200 return E_ACCESSDENIED;
1201 m->state = Data::ApplianceImporting;
1202 appLock.release();
1203
1204 HRESULT rc = S_OK;
1205
1206 const ovf::OVFReader &reader = *m->pReader;
1207 // this is safe to access because this thread only gets started
1208 // if pReader != NULL
1209
1210 // rollback for errors:
1211 ImportStack stack(pTask->locInfo, reader.m_mapDisks, pTask->pProgress);
1212
1213 // clear the list of imported machines, if any
1214 m->llGuidsMachinesCreated.clear();
1215
1216 try
1217 {
1218 // if a manifest file exists, verify the content; we then need all files which are referenced by the OVF & the OVF itself
1219 rc = manifestVerify(pTask->locInfo, reader, pTask->pProgress);
1220 if (FAILED(rc)) throw rc;
1221
1222 // create a session for the machine + disks we manipulate below
1223 rc = stack.pSession.createInprocObject(CLSID_Session);
1224 if (FAILED(rc)) throw rc;
1225
1226 list<ovf::VirtualSystem>::const_iterator it;
1227 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1228 /* Iterate through all virtual systems of that appliance */
1229 size_t i = 0;
1230 for (it = reader.m_llVirtualSystems.begin(),
1231 it1 = m->virtualSystemDescriptions.begin();
1232 it != reader.m_llVirtualSystems.end();
1233 ++it, ++it1, ++i)
1234 {
1235 const ovf::VirtualSystem &vsysThis = *it;
1236 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1237
1238 ComPtr<IMachine> pNewMachine;
1239
1240 // there are two ways in which we can create a vbox machine from OVF:
1241 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
1242 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
1243 // with all the machine config pretty-parsed;
1244 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
1245 // VirtualSystemDescriptionEntry and do import work
1246
1247 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
1248 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
1249
1250 // VM name
1251 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1252 if (vsdeName.size() < 1)
1253 throw setError(VBOX_E_FILE_ERROR,
1254 tr("Missing VM name"));
1255 stack.strNameVBox = vsdeName.front()->strVboxCurrent;
1256
1257 // guest OS type
1258 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1259 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1260 if (vsdeOS.size() < 1)
1261 throw setError(VBOX_E_FILE_ERROR,
1262 tr("Missing guest OS type"));
1263 stack.strOsTypeVBox = vsdeOS.front()->strVboxCurrent;
1264
1265 // CPU count
1266 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
1267 if (vsdeCPU.size() != 1)
1268 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
1269
1270 const Utf8Str &cpuVBox = vsdeCPU.front()->strVboxCurrent;
1271 stack.cCPUs = (uint32_t)RTStrToUInt64(cpuVBox.c_str());
1272 // We need HWVirt & IO-APIC if more than one CPU is requested
1273 if (stack.cCPUs > 1)
1274 {
1275 stack.fForceHWVirt = true;
1276 stack.fForceIOAPIC = true;
1277 }
1278
1279 // RAM
1280 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1281 if (vsdeRAM.size() != 1)
1282 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
1283 const Utf8Str &memoryVBox = vsdeRAM.front()->strVboxCurrent;
1284 stack.ulMemorySizeMB = (uint32_t)RTStrToUInt64(memoryVBox.c_str());
1285
1286#ifdef VBOX_WITH_USB
1287 // USB controller
1288 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1289 // USB support is enabled if there's at least one such entry; to disable USB support,
1290 // the type of the USB item would have been changed to "ignore"
1291 stack.fUSBEnabled = vsdeUSBController.size() > 0;
1292#endif
1293 // audio adapter
1294 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1295 /* @todo: we support one audio adapter only */
1296 if (vsdeAudioAdapter.size() > 0)
1297 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVboxCurrent;
1298
1299 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
1300 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1301 if (vsdeDescription.size())
1302 stack.strDescription = vsdeDescription.front()->strVboxCurrent;
1303
1304 // import vbox:machine or OVF now
1305 if (vsdescThis->m->pConfig)
1306 // vbox:Machine config
1307 importVBoxMachine(vsdescThis, pNewMachine, stack);
1308 else
1309 // generic OVF config
1310 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
1311
1312 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
1313 }
1314 catch (HRESULT rc2)
1315 {
1316 rc = rc2;
1317 }
1318
1319 if (FAILED(rc))
1320 {
1321 // with _whatever_ error we've had, do a complete roll-back of
1322 // machines and disks we've created
1323
1324 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
1325 itID != m->llGuidsMachinesCreated.end();
1326 ++itID)
1327 {
1328 Guid guid = *itID;
1329 Bstr bstrGuid = guid.toUtf16();
1330 ComPtr<IMachine> failedMachine;
1331 HRESULT rc2 = mVirtualBox->GetMachine(bstrGuid.raw(), failedMachine.asOutParam());
1332 if (SUCCEEDED(rc2))
1333 {
1334 SafeIfaceArray<IMedium> aMedia;
1335 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
1336 ComPtr<IProgress> pProgress2;
1337 rc2 = failedMachine->Delete(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
1338 pProgress2->WaitForCompletion(-1);
1339 }
1340 }
1341 }
1342
1343 // restore the appliance state
1344 appLock.acquire();
1345 m->state = Data::ApplianceIdle;
1346 appLock.release();
1347
1348 LogFlowFunc(("rc=%Rhrc\n", rc));
1349 LogFlowFuncLeave();
1350
1351 return rc;
1352}
1353
1354HRESULT Appliance::importFSOVA(TaskOVF *pTask)
1355{
1356 LogFlowFuncEnter();
1357 LogFlowFunc(("Appliance %p\n", this));
1358
1359 AutoCaller autoCaller(this);
1360 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1361
1362 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1363
1364 int vrc = VINF_SUCCESS;
1365 char szOSTmpDir[RTPATH_MAX];
1366 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1367 /* The template for the temporary directory created below */
1368 char *pszTmpDir;
1369 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
1370 list< pair<Utf8Str, ULONG> > filesList;
1371 const char** paFiles = 0;
1372
1373 HRESULT rc = S_OK;
1374 try
1375 {
1376 /* Extract the path */
1377 Utf8Str tmpPath = pTask->locInfo.strPath;
1378 /* Remove the ova extension */
1379 tmpPath.stripExt();
1380 tmpPath += ".ovf";
1381
1382 /* We need a temporary directory which we can put the all disk images
1383 * in */
1384 vrc = RTDirCreateTemp(pszTmpDir);
1385 if (RT_FAILURE(vrc))
1386 throw setError(VBOX_E_FILE_ERROR,
1387 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1388
1389 /* Provide a OVF file (haven't to exist) so the import routine can
1390 * figure out where the disk images/manifest file are located. */
1391 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1392 /* Add the manifest file to the list of files to extract, but only if
1393 one is in the archive. */
1394 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
1395 vrc = RTTarFileExists(pTask->locInfo.strPath.c_str(), RTPathFilename(strManifestFile.c_str()));
1396 if (RT_SUCCESS(vrc))
1397 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile.c_str(), 1));
1398
1399 ULONG ulWeight = m->ulWeightForXmlOperation;
1400 /* Add every disks of every virtual system to an internal list */
1401 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1402 for (it = m->virtualSystemDescriptions.begin();
1403 it != m->virtualSystemDescriptions.end();
1404 ++it)
1405 {
1406 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1407 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1408 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1409 for (itH = avsdeHDs.begin();
1410 itH != avsdeHDs.end();
1411 ++itH)
1412 {
1413 const Utf8Str &strTargetFile = (*itH)->strOvf;
1414 if (!strTargetFile.isEmpty())
1415 {
1416 /* The temporary name of the target disk file */
1417 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
1418 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1419 ulWeight += (*itH)->ulSizeMB;
1420 }
1421 }
1422 }
1423
1424 /* Download all files */
1425 paFiles = (const char**)RTMemAlloc(sizeof(char*) * filesList.size());
1426 int i = 0;
1427 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1, ++i)
1428 paFiles[i] = RTPathFilename((*it1).first.c_str());
1429 if (!pTask->pProgress.isNull())
1430 pTask->pProgress->SetNextOperation(BstrFmt(tr("Unpacking file '%s'"), RTPathFilename(pTask->locInfo.strPath.c_str())).raw(), ulWeight);
1431 vrc = RTTarExtractFiles(pTask->locInfo.strPath.c_str(), pszTmpDir, paFiles, filesList.size(), pTask->updateProgress, &pTask);
1432 if (RT_FAILURE(vrc))
1433 throw setError(VBOX_E_FILE_ERROR,
1434 tr("Cannot unpack archive file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1435
1436// if (!pTask->pProgress.isNull())
1437// pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightForXmlOperation);
1438
1439 ComObjPtr<Progress> progress;
1440 /* Import the whole temporary OVF & the disk images */
1441 LocationInfo li;
1442 li.strPath = strTmpOvf;
1443 rc = importImpl(li, progress);
1444 if (FAILED(rc)) throw rc;
1445
1446 /* Unlock the appliance for the fs import thread */
1447 appLock.release();
1448 /* Wait until the import is done, but report the progress back to the
1449 caller */
1450 ComPtr<IProgress> progressInt(progress);
1451 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1452
1453 /* Again lock the appliance for the next steps */
1454 appLock.acquire();
1455 }
1456 catch(HRESULT aRC)
1457 {
1458 rc = aRC;
1459 }
1460 /* Delete the temporary files list */
1461 if (paFiles)
1462 RTMemFree(paFiles);
1463 /* Delete all files which where temporary created */
1464 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1465 {
1466 const char *pszFilePath = (*it1).first.c_str();
1467 if (RTPathExists(pszFilePath))
1468 {
1469 vrc = RTFileDelete(pszFilePath);
1470 if (RT_FAILURE(vrc))
1471 rc = setError(VBOX_E_FILE_ERROR,
1472 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
1473 }
1474 }
1475 /* Delete the temporary directory */
1476 if (RTPathExists(pszTmpDir))
1477 {
1478 vrc = RTDirRemove(pszTmpDir);
1479 if (RT_FAILURE(vrc))
1480 rc = setError(VBOX_E_FILE_ERROR,
1481 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1482 }
1483 if (pszTmpDir)
1484 RTStrFree(pszTmpDir);
1485
1486 LogFlowFunc(("rc=%Rhrc\n", rc));
1487 LogFlowFuncLeave();
1488
1489 return rc;
1490}
1491
1492/**
1493 * Imports one disk image. This is common code shared between
1494 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1495 * the OVF virtual systems;
1496 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1497 * tag.
1498 *
1499 * Both ways of describing machines use the OVF disk references section, so in both cases
1500 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1501 *
1502 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1503 * spec, even though this cannot really happen in the vbox:Machine case since such data
1504 * would never have been exported.
1505 *
1506 * This advances stack.pProgress by one operation with the disk's weight.
1507 *
1508 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1509 * @param ulSizeMB Size of the disk image (for progress reporting)
1510 * @param strTargetPath Where to create the target image.
1511 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1512 * @param stack
1513 */
1514void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1515 const Utf8Str &strTargetPath,
1516 ComPtr<IMedium> &pTargetHD,
1517 ImportStack &stack)
1518{
1519 ComPtr<IMedium> pSourceHD;
1520 bool fSourceHdNeedsClosing = false;
1521
1522 try
1523 {
1524 // destination file must not exist
1525 if ( strTargetPath.isEmpty()
1526 || RTPathExists(strTargetPath.c_str())
1527 )
1528 throw setError(VBOX_E_FILE_ERROR,
1529 tr("Destination file '%s' exists"),
1530 strTargetPath.c_str());
1531
1532 const Utf8Str &strSourceOVF = di.strHref;
1533
1534 // Make sure target directory exists
1535 HRESULT rc = VirtualBox::ensureFilePathExists(strTargetPath.c_str());
1536 if (FAILED(rc)) throw rc;
1537
1538 // subprogress object for hard disk
1539 ComPtr<IProgress> pProgress2;
1540
1541 /* If strHref is empty we have to create a new file */
1542 if (strSourceOVF.isEmpty())
1543 {
1544 // which format to use?
1545 Bstr srcFormat = L"VDI";
1546 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1547 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1548 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1549 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1550 )
1551 srcFormat = L"VMDK";
1552 // create an empty hard disk
1553 rc = mVirtualBox->CreateHardDisk(srcFormat.raw(),
1554 Bstr(strTargetPath).raw(),
1555 pTargetHD.asOutParam());
1556 if (FAILED(rc)) throw rc;
1557
1558 // create a dynamic growing disk image with the given capacity
1559 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1560 if (FAILED(rc)) throw rc;
1561
1562 // advance to the next operation
1563 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()).raw(),
1564 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1565 }
1566 else
1567 {
1568 // construct source file path
1569 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1570 // source path must exist
1571 if (!RTPathExists(strSrcFilePath.c_str()))
1572 throw setError(VBOX_E_FILE_ERROR,
1573 tr("Source virtual disk image file '%s' doesn't exist"),
1574 strSrcFilePath.c_str());
1575
1576 // Clone the disk image (this is necessary cause the id has
1577 // to be recreated for the case the same hard disk is
1578 // attached already from a previous import)
1579
1580 // First open the existing disk image
1581 rc = mVirtualBox->OpenMedium(Bstr(strSrcFilePath).raw(),
1582 DeviceType_HardDisk,
1583 AccessMode_ReadOnly,
1584 pSourceHD.asOutParam());
1585 if (FAILED(rc)) throw rc;
1586 fSourceHdNeedsClosing = true;
1587
1588 /* We need the format description of the source disk image */
1589 Bstr srcFormat;
1590 rc = pSourceHD->COMGETTER(Format)(srcFormat.asOutParam());
1591 if (FAILED(rc)) throw rc;
1592 /* Create a new hard disk interface for the destination disk image */
1593 rc = mVirtualBox->CreateHardDisk(srcFormat.raw(),
1594 Bstr(strTargetPath).raw(),
1595 pTargetHD.asOutParam());
1596 if (FAILED(rc)) throw rc;
1597 /* Clone the source disk image */
1598 rc = pSourceHD->CloneTo(pTargetHD, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1599 if (FAILED(rc)) throw rc;
1600
1601 /* Advance to the next operation */
1602 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), RTPathFilename(strSrcFilePath.c_str())).raw(),
1603 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1604 }
1605
1606 // now wait for the background disk operation to complete; this throws HRESULTs on error
1607 waitForAsyncProgress(stack.pProgress, pProgress2);
1608
1609 if (fSourceHdNeedsClosing)
1610 {
1611 rc = pSourceHD->Close();
1612 if (FAILED(rc)) throw rc;
1613 fSourceHdNeedsClosing = false;
1614 }
1615
1616 stack.llHardDisksCreated.push_back(pTargetHD);
1617 }
1618 catch (...)
1619 {
1620 if (fSourceHdNeedsClosing)
1621 pSourceHD->Close();
1622
1623 throw;
1624 }
1625}
1626
1627/**
1628 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1629 * into VirtualBox by creating an IMachine instance, which is returned.
1630 *
1631 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1632 * up any leftovers from this function. For this, the given ImportStack instance has received information
1633 * about what needs cleaning up (to support rollback).
1634 *
1635 * @param vsysThis OVF virtual system (machine) to import.
1636 * @param vsdescThis Matching virtual system description (machine) to import.
1637 * @param pNewMachine out: Newly created machine.
1638 * @param stack Cleanup stack for when this throws.
1639 */
1640void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1641 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1642 ComPtr<IMachine> &pNewMachine,
1643 ImportStack &stack)
1644{
1645 HRESULT rc;
1646
1647 // Get the instance of IGuestOSType which matches our string guest OS type so we
1648 // can use recommended defaults for the new machine where OVF doesen't provice any
1649 ComPtr<IGuestOSType> osType;
1650 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
1651 if (FAILED(rc)) throw rc;
1652
1653 /* Create the machine */
1654 rc = mVirtualBox->CreateMachine(Bstr(stack.strNameVBox).raw(),
1655 Bstr(stack.strOsTypeVBox).raw(),
1656 NULL,
1657 NULL,
1658 FALSE,
1659 pNewMachine.asOutParam());
1660 if (FAILED(rc)) throw rc;
1661
1662 // set the description
1663 if (!stack.strDescription.isEmpty())
1664 {
1665 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
1666 if (FAILED(rc)) throw rc;
1667 }
1668
1669 // CPU count
1670 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
1671 if (FAILED(rc)) throw rc;
1672
1673 if (stack.fForceHWVirt)
1674 {
1675 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1676 if (FAILED(rc)) throw rc;
1677 }
1678
1679 // RAM
1680 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
1681 if (FAILED(rc)) throw rc;
1682
1683 /* VRAM */
1684 /* Get the recommended VRAM for this guest OS type */
1685 ULONG vramVBox;
1686 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1687 if (FAILED(rc)) throw rc;
1688
1689 /* Set the VRAM */
1690 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1691 if (FAILED(rc)) throw rc;
1692
1693 // I/O APIC: Generic OVF has no setting for this. Enable it if we
1694 // import a Windows VM because if if Windows was installed without IOAPIC,
1695 // it will not mind finding an one later on, but if Windows was installed
1696 // _with_ an IOAPIC, it will bluescreen if it's not found
1697 if (!stack.fForceIOAPIC)
1698 {
1699 Bstr bstrFamilyId;
1700 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1701 if (FAILED(rc)) throw rc;
1702 if (bstrFamilyId == "Windows")
1703 stack.fForceIOAPIC = true;
1704 }
1705
1706 if (stack.fForceIOAPIC)
1707 {
1708 ComPtr<IBIOSSettings> pBIOSSettings;
1709 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1710 if (FAILED(rc)) throw rc;
1711
1712 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1713 if (FAILED(rc)) throw rc;
1714 }
1715
1716 if (!stack.strAudioAdapter.isEmpty())
1717 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
1718 {
1719 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
1720 ComPtr<IAudioAdapter> audioAdapter;
1721 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1722 if (FAILED(rc)) throw rc;
1723 rc = audioAdapter->COMSETTER(Enabled)(true);
1724 if (FAILED(rc)) throw rc;
1725 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1726 if (FAILED(rc)) throw rc;
1727 }
1728
1729#ifdef VBOX_WITH_USB
1730 /* USB Controller */
1731 ComPtr<IUSBController> usbController;
1732 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1733 if (FAILED(rc)) throw rc;
1734 rc = usbController->COMSETTER(Enabled)(stack.fUSBEnabled);
1735 if (FAILED(rc)) throw rc;
1736#endif /* VBOX_WITH_USB */
1737
1738 /* Change the network adapters */
1739 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1740 if (vsdeNW.size() == 0)
1741 {
1742 /* No network adapters, so we have to disable our default one */
1743 ComPtr<INetworkAdapter> nwVBox;
1744 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1745 if (FAILED(rc)) throw rc;
1746 rc = nwVBox->COMSETTER(Enabled)(false);
1747 if (FAILED(rc)) throw rc;
1748 }
1749 else if (vsdeNW.size() > SchemaDefs::NetworkAdapterCount)
1750 throw setError(VBOX_E_FILE_ERROR,
1751 tr("Too many network adapters: OVF requests %d network adapters, but VirtualBox only supports %d"),
1752 vsdeNW.size(), SchemaDefs::NetworkAdapterCount);
1753 else
1754 {
1755 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1756 size_t a = 0;
1757 for (nwIt = vsdeNW.begin();
1758 nwIt != vsdeNW.end();
1759 ++nwIt, ++a)
1760 {
1761 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1762
1763 const Utf8Str &nwTypeVBox = pvsys->strVboxCurrent;
1764 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1765 ComPtr<INetworkAdapter> pNetworkAdapter;
1766 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1767 if (FAILED(rc)) throw rc;
1768 /* Enable the network card & set the adapter type */
1769 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1770 if (FAILED(rc)) throw rc;
1771 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1772 if (FAILED(rc)) throw rc;
1773
1774 // default is NAT; change to "bridged" if extra conf says so
1775 if (!pvsys->strExtraConfigCurrent.compare("type=Bridged", Utf8Str::CaseInsensitive))
1776 {
1777 /* Attach to the right interface */
1778 rc = pNetworkAdapter->AttachToBridgedInterface();
1779 if (FAILED(rc)) throw rc;
1780 ComPtr<IHost> host;
1781 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1782 if (FAILED(rc)) throw rc;
1783 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1784 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1785 if (FAILED(rc)) throw rc;
1786 // We search for the first host network interface which
1787 // is usable for bridged networking
1788 for (size_t j = 0;
1789 j < nwInterfaces.size();
1790 ++j)
1791 {
1792 HostNetworkInterfaceType_T itype;
1793 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1794 if (FAILED(rc)) throw rc;
1795 if (itype == HostNetworkInterfaceType_Bridged)
1796 {
1797 Bstr name;
1798 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1799 if (FAILED(rc)) throw rc;
1800 /* Set the interface name to attach to */
1801 pNetworkAdapter->COMSETTER(HostInterface)(name.raw());
1802 if (FAILED(rc)) throw rc;
1803 break;
1804 }
1805 }
1806 }
1807 /* Next test for host only interfaces */
1808 else if (!pvsys->strExtraConfigCurrent.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1809 {
1810 /* Attach to the right interface */
1811 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1812 if (FAILED(rc)) throw rc;
1813 ComPtr<IHost> host;
1814 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1815 if (FAILED(rc)) throw rc;
1816 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1817 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1818 if (FAILED(rc)) throw rc;
1819 // We search for the first host network interface which
1820 // is usable for host only networking
1821 for (size_t j = 0;
1822 j < nwInterfaces.size();
1823 ++j)
1824 {
1825 HostNetworkInterfaceType_T itype;
1826 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1827 if (FAILED(rc)) throw rc;
1828 if (itype == HostNetworkInterfaceType_HostOnly)
1829 {
1830 Bstr name;
1831 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1832 if (FAILED(rc)) throw rc;
1833 /* Set the interface name to attach to */
1834 pNetworkAdapter->COMSETTER(HostInterface)(name.raw());
1835 if (FAILED(rc)) throw rc;
1836 break;
1837 }
1838 }
1839 }
1840 }
1841 }
1842
1843 // IDE Hard disk controller
1844 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1845 // In OVF (at least VMware's version of it), an IDE controller has two ports, so VirtualBox's single IDE controller
1846 // with two channels and two ports each counts as two OVF IDE controllers -- so we accept one or two such IDE controllers
1847 uint32_t cIDEControllers = vsdeHDCIDE.size();
1848 if (cIDEControllers > 2)
1849 throw setError(VBOX_E_FILE_ERROR,
1850 tr("Too many IDE controllers in OVF; import facility only supports two"));
1851 if (vsdeHDCIDE.size() > 0)
1852 {
1853 // one or two IDE controllers present in OVF: add one VirtualBox controller
1854 ComPtr<IStorageController> pController;
1855 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
1856 if (FAILED(rc)) throw rc;
1857
1858 const char *pcszIDEType = vsdeHDCIDE.front()->strVboxCurrent.c_str();
1859 if (!strcmp(pcszIDEType, "PIIX3"))
1860 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1861 else if (!strcmp(pcszIDEType, "PIIX4"))
1862 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1863 else if (!strcmp(pcszIDEType, "ICH6"))
1864 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1865 else
1866 throw setError(VBOX_E_FILE_ERROR,
1867 tr("Invalid IDE controller type \"%s\""),
1868 pcszIDEType);
1869 if (FAILED(rc)) throw rc;
1870 }
1871
1872 /* Hard disk controller SATA */
1873 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1874 if (vsdeHDCSATA.size() > 1)
1875 throw setError(VBOX_E_FILE_ERROR,
1876 tr("Too many SATA controllers in OVF; import facility only supports one"));
1877 if (vsdeHDCSATA.size() > 0)
1878 {
1879 ComPtr<IStorageController> pController;
1880 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVboxCurrent;
1881 if (hdcVBox == "AHCI")
1882 {
1883 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(), StorageBus_SATA, pController.asOutParam());
1884 if (FAILED(rc)) throw rc;
1885 }
1886 else
1887 throw setError(VBOX_E_FILE_ERROR,
1888 tr("Invalid SATA controller type \"%s\""),
1889 hdcVBox.c_str());
1890 }
1891
1892 /* Hard disk controller SCSI */
1893 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1894 if (vsdeHDCSCSI.size() > 1)
1895 throw setError(VBOX_E_FILE_ERROR,
1896 tr("Too many SCSI controllers in OVF; import facility only supports one"));
1897 if (vsdeHDCSCSI.size() > 0)
1898 {
1899 ComPtr<IStorageController> pController;
1900 Bstr bstrName(L"SCSI Controller");
1901 StorageBus_T busType = StorageBus_SCSI;
1902 StorageControllerType_T controllerType;
1903 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVboxCurrent;
1904 if (hdcVBox == "LsiLogic")
1905 controllerType = StorageControllerType_LsiLogic;
1906 else if (hdcVBox == "LsiLogicSas")
1907 {
1908 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
1909 bstrName = L"SAS Controller";
1910 busType = StorageBus_SAS;
1911 controllerType = StorageControllerType_LsiLogicSas;
1912 }
1913 else if (hdcVBox == "BusLogic")
1914 controllerType = StorageControllerType_BusLogic;
1915 else
1916 throw setError(VBOX_E_FILE_ERROR,
1917 tr("Invalid SCSI controller type \"%s\""),
1918 hdcVBox.c_str());
1919
1920 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
1921 if (FAILED(rc)) throw rc;
1922 rc = pController->COMSETTER(ControllerType)(controllerType);
1923 if (FAILED(rc)) throw rc;
1924 }
1925
1926 /* Hard disk controller SAS */
1927 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
1928 if (vsdeHDCSAS.size() > 1)
1929 throw setError(VBOX_E_FILE_ERROR,
1930 tr("Too many SAS controllers in OVF; import facility only supports one"));
1931 if (vsdeHDCSAS.size() > 0)
1932 {
1933 ComPtr<IStorageController> pController;
1934 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(), StorageBus_SAS, pController.asOutParam());
1935 if (FAILED(rc)) throw rc;
1936 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
1937 if (FAILED(rc)) throw rc;
1938 }
1939
1940 /* Now its time to register the machine before we add any hard disks */
1941 rc = mVirtualBox->RegisterMachine(pNewMachine);
1942 if (FAILED(rc)) throw rc;
1943
1944 // store new machine for roll-back in case of errors
1945 Bstr bstrNewMachineId;
1946 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
1947 if (FAILED(rc)) throw rc;
1948 Guid uuidNewMachine(bstrNewMachineId);
1949 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
1950
1951 // Add floppies and CD-ROMs to the appropriate controllers.
1952 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1953 if (vsdeFloppy.size() > 1)
1954 throw setError(VBOX_E_FILE_ERROR,
1955 tr("Too many floppy controllers in OVF; import facility only supports one"));
1956 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1957 if ( (vsdeFloppy.size() > 0)
1958 || (vsdeCDROM.size() > 0)
1959 )
1960 {
1961 // If there's an error here we need to close the session, so
1962 // we need another try/catch block.
1963
1964 try
1965 {
1966 // to attach things we need to open a session for the new machine
1967 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
1968 if (FAILED(rc)) throw rc;
1969 stack.fSessionOpen = true;
1970
1971 ComPtr<IMachine> sMachine;
1972 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1973 if (FAILED(rc)) throw rc;
1974
1975 // floppy first
1976 if (vsdeFloppy.size() == 1)
1977 {
1978 ComPtr<IStorageController> pController;
1979 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(), StorageBus_Floppy, pController.asOutParam());
1980 if (FAILED(rc)) throw rc;
1981
1982 Bstr bstrName;
1983 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1984 if (FAILED(rc)) throw rc;
1985
1986 // this is for rollback later
1987 MyHardDiskAttachment mhda;
1988 mhda.pMachine = pNewMachine;
1989 mhda.controllerType = bstrName;
1990 mhda.lControllerPort = 0;
1991 mhda.lDevice = 0;
1992
1993 Log(("Attaching floppy\n"));
1994
1995 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
1996 mhda.lControllerPort,
1997 mhda.lDevice,
1998 DeviceType_Floppy,
1999 NULL);
2000 if (FAILED(rc)) throw rc;
2001
2002 stack.llHardDiskAttachments.push_back(mhda);
2003 }
2004
2005 // CD-ROMs next
2006 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
2007 jt != vsdeCDROM.end();
2008 ++jt)
2009 {
2010 // for now always attach to secondary master on IDE controller;
2011 // there seems to be no useful information in OVF where else to
2012 // attach it (@todo test with latest versions of OVF software)
2013
2014 // find the IDE controller
2015 const ovf::HardDiskController *pController = NULL;
2016 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
2017 kt != vsysThis.mapControllers.end();
2018 ++kt)
2019 {
2020 if (kt->second.system == ovf::HardDiskController::IDE)
2021 {
2022 pController = &kt->second;
2023 break;
2024 }
2025 }
2026
2027 if (!pController)
2028 throw setError(VBOX_E_FILE_ERROR,
2029 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
2030
2031 // this is for rollback later
2032 MyHardDiskAttachment mhda;
2033 mhda.pMachine = pNewMachine;
2034
2035 convertDiskAttachmentValues(*pController,
2036 2, // interpreted as secondary master
2037 mhda.controllerType, // Bstr
2038 mhda.lControllerPort,
2039 mhda.lDevice);
2040
2041 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
2042
2043 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2044 mhda.lControllerPort,
2045 mhda.lDevice,
2046 DeviceType_DVD,
2047 NULL);
2048 if (FAILED(rc)) throw rc;
2049
2050 stack.llHardDiskAttachments.push_back(mhda);
2051 } // end for (itHD = avsdeHDs.begin();
2052
2053 rc = sMachine->SaveSettings();
2054 if (FAILED(rc)) throw rc;
2055
2056 // only now that we're done with all disks, close the session
2057 rc = stack.pSession->UnlockMachine();
2058 if (FAILED(rc)) throw rc;
2059 stack.fSessionOpen = false;
2060 }
2061 catch(HRESULT /* aRC */)
2062 {
2063 if (stack.fSessionOpen)
2064 stack.pSession->UnlockMachine();
2065
2066 throw;
2067 }
2068 }
2069
2070 // create the hard disks & connect them to the appropriate controllers
2071 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2072 if (avsdeHDs.size() > 0)
2073 {
2074 // If there's an error here we need to close the session, so
2075 // we need another try/catch block.
2076 try
2077 {
2078 // to attach things we need to open a session for the new machine
2079 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2080 if (FAILED(rc)) throw rc;
2081 stack.fSessionOpen = true;
2082
2083 /* Iterate over all given disk images */
2084 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2085 for (itHD = avsdeHDs.begin();
2086 itHD != avsdeHDs.end();
2087 ++itHD)
2088 {
2089 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2090
2091 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
2092 // in the virtual system's disks map under that ID and also in the global images map
2093 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
2094 // and find the disk from the OVF's disk list
2095 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
2096 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
2097 || (itDiskImage == stack.mapDisks.end())
2098 )
2099 throw setError(E_FAIL,
2100 tr("Internal inconsistency looking up disk image '%s'"),
2101 vsdeHD->strRef.c_str());
2102
2103 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
2104 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
2105
2106 ComPtr<IMedium> pTargetHD;
2107 importOneDiskImage(ovfDiskImage,
2108 vsdeHD->strVboxCurrent,
2109 pTargetHD,
2110 stack);
2111
2112 // now use the new uuid to attach the disk image to our new machine
2113 ComPtr<IMachine> sMachine;
2114 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2115 if (FAILED(rc)) throw rc;
2116
2117 // find the hard disk controller to which we should attach
2118 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
2119
2120 // this is for rollback later
2121 MyHardDiskAttachment mhda;
2122 mhda.pMachine = pNewMachine;
2123
2124 convertDiskAttachmentValues(hdc,
2125 ovfVdisk.ulAddressOnParent,
2126 mhda.controllerType, // Bstr
2127 mhda.lControllerPort,
2128 mhda.lDevice);
2129
2130 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVboxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
2131
2132 rc = sMachine->AttachDevice(mhda.controllerType.raw(), // wstring name
2133 mhda.lControllerPort, // long controllerPort
2134 mhda.lDevice, // long device
2135 DeviceType_HardDisk, // DeviceType_T type
2136 pTargetHD);
2137 if (FAILED(rc)) throw rc;
2138
2139 stack.llHardDiskAttachments.push_back(mhda);
2140
2141 rc = sMachine->SaveSettings();
2142 if (FAILED(rc)) throw rc;
2143 } // end for (itHD = avsdeHDs.begin();
2144
2145 // only now that we're done with all disks, close the session
2146 rc = stack.pSession->UnlockMachine();
2147 if (FAILED(rc)) throw rc;
2148 stack.fSessionOpen = false;
2149 }
2150 catch(HRESULT /* aRC */)
2151 {
2152 if (stack.fSessionOpen)
2153 stack.pSession->UnlockMachine();
2154
2155 throw;
2156 }
2157 }
2158}
2159
2160/**
2161 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
2162 * structure) into VirtualBox by creating an IMachine instance, which is returned.
2163 *
2164 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2165 * up any leftovers from this function. For this, the given ImportStack instance has received information
2166 * about what needs cleaning up (to support rollback).
2167 *
2168 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
2169 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
2170 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
2171 * will most probably work, reimporting them into the same host will cause conflicts, so we always
2172 * generate new ones on import. This involves the following:
2173 *
2174 * 1) Scan the machine config for disk attachments.
2175 *
2176 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
2177 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
2178 * replace the old UUID with the new one.
2179 *
2180 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
2181 * caller has modified them using setFinalValues().
2182 *
2183 * 4) Create the VirtualBox machine with the modfified machine config.
2184 *
2185 * @param config
2186 * @param pNewMachine
2187 * @param stack
2188 */
2189void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
2190 ComPtr<IMachine> &pReturnNewMachine,
2191 ImportStack &stack)
2192{
2193 Assert(vsdescThis->m->pConfig);
2194
2195 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
2196
2197 Utf8Str strDefaultHardDiskFolder;
2198 HRESULT rc = getDefaultHardDiskFolder(strDefaultHardDiskFolder);
2199 if (FAILED(rc)) throw rc;
2200
2201 /*
2202 *
2203 * step 1): modify machine config according to OVF config, in case the user
2204 * has modified them using setFinalValues()
2205 *
2206 */
2207
2208 config.machineUserData.strDescription = stack.strDescription;
2209
2210 config.hardwareMachine.cCPUs = stack.cCPUs;
2211 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
2212 if (stack.fForceIOAPIC)
2213 config.hardwareMachine.fHardwareVirt = true;
2214 if (stack.fForceIOAPIC)
2215 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
2216
2217/*
2218 <const name="HardDiskControllerIDE" value="14" />
2219 <const name="HardDiskControllerSATA" value="15" />
2220 <const name="HardDiskControllerSCSI" value="16" />
2221 <const name="HardDiskControllerSAS" value="17" />
2222 <const name="HardDiskImage" value="18" />
2223 <const name="Floppy" value="19" />
2224 <const name="CDROM" value="20" />
2225 <const name="NetworkAdapter" value="21" />
2226*/
2227
2228#ifdef VBOX_WITH_USB
2229 // disable USB if user disabled USB
2230 config.hardwareMachine.usbController.fEnabled = stack.fUSBEnabled;
2231#endif
2232
2233 // audio adapter: only config is turning it off presently
2234 if (stack.strAudioAdapter.isEmpty())
2235 config.hardwareMachine.audioAdapter.fEnabled = false;
2236
2237 /*
2238 *
2239 * step 2: scan the machine config for media attachments
2240 *
2241 */
2242
2243 // for each storage controller...
2244 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
2245 sit != config.storageMachine.llStorageControllers.end();
2246 ++sit)
2247 {
2248 settings::StorageController &sc = *sit;
2249
2250 // find the OVF virtual system description entry for this storage controller
2251 switch (sc.storageBus)
2252 {
2253 case StorageBus_SATA:
2254 break;
2255
2256 case StorageBus_SCSI:
2257 break;
2258
2259 case StorageBus_IDE:
2260 break;
2261
2262 case StorageBus_SAS:
2263 break;
2264 }
2265
2266 // for each medium attachment to this controller...
2267 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
2268 dit != sc.llAttachedDevices.end();
2269 ++dit)
2270 {
2271 settings::AttachedDevice &d = *dit;
2272
2273 if (d.uuid.isEmpty())
2274 // empty DVD and floppy media
2275 continue;
2276
2277 // convert the Guid to string
2278 Utf8Str strUuid = d.uuid.toString();
2279
2280 // there must be an image in the OVF disk structs with the same UUID
2281 bool fFound = false;
2282 for (ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2283 oit != stack.mapDisks.end();
2284 ++oit)
2285 {
2286 const ovf::DiskImage &di = oit->second;
2287
2288 if (di.uuidVbox == strUuid)
2289 {
2290 Utf8Str strTargetPath(strDefaultHardDiskFolder);
2291 strTargetPath.append(RTPATH_DELIMITER);
2292 strTargetPath.append(di.strHref);
2293 searchUniqueDiskImageFilePath(strTargetPath);
2294
2295 /*
2296 *
2297 * step 3: import disk
2298 *
2299 */
2300 ComPtr<IMedium> pTargetHD;
2301 importOneDiskImage(di,
2302 strTargetPath,
2303 pTargetHD,
2304 stack);
2305
2306 // ... and replace the old UUID in the machine config with the one of
2307 // the imported disk that was just created
2308 Bstr hdId;
2309 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
2310 if (FAILED(rc)) throw rc;
2311
2312 d.uuid = hdId;
2313
2314 fFound = true;
2315 break;
2316 }
2317 }
2318
2319 // no disk with such a UUID found:
2320 if (!fFound)
2321 throw setError(E_FAIL,
2322 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s but the OVF describes no such image"),
2323 strUuid.c_str());
2324 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
2325 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
2326
2327 /*
2328 *
2329 * step 4): create the machine and have it import the config
2330 *
2331 */
2332
2333 ComObjPtr<Machine> pNewMachine;
2334 rc = pNewMachine.createObject();
2335 if (FAILED(rc)) throw rc;
2336
2337 // this magic constructor fills the new machine object with the MachineConfig
2338 // instance that we created from the vbox:Machine
2339 rc = pNewMachine->init(mVirtualBox,
2340 stack.strNameVBox, // name from OVF preparations; can be suffixed to avoid duplicates, or changed by user
2341 config); // the whole machine config
2342 if (FAILED(rc)) throw rc;
2343
2344 // return the new machine as an IMachine
2345 IMachine *p;
2346 rc = pNewMachine.queryInterfaceTo(&p);
2347 if (FAILED(rc)) throw rc;
2348 pReturnNewMachine = p;
2349
2350 // and register it
2351 rc = mVirtualBox->RegisterMachine(pNewMachine);
2352 if (FAILED(rc)) throw rc;
2353
2354 // store new machine for roll-back in case of errors
2355 Bstr bstrNewMachineId;
2356 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2357 if (FAILED(rc)) throw rc;
2358 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
2359}
2360
2361/**
2362 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
2363 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
2364 * thread to import from temporary files (see Appliance::importFS()).
2365 * @param pTask
2366 * @return
2367 */
2368HRESULT Appliance::importS3(TaskOVF *pTask)
2369{
2370 LogFlowFuncEnter();
2371 LogFlowFunc(("Appliance %p\n", this));
2372
2373 AutoCaller autoCaller(this);
2374 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2375
2376 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
2377
2378 int vrc = VINF_SUCCESS;
2379 RTS3 hS3 = NIL_RTS3;
2380 char szOSTmpDir[RTPATH_MAX];
2381 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
2382 /* The template for the temporary directory created below */
2383 char *pszTmpDir;
2384 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
2385 list< pair<Utf8Str, ULONG> > filesList;
2386
2387 HRESULT rc = S_OK;
2388 try
2389 {
2390 /* Extract the bucket */
2391 Utf8Str tmpPath = pTask->locInfo.strPath;
2392 Utf8Str bucket;
2393 parseBucket(tmpPath, bucket);
2394
2395 /* We need a temporary directory which we can put the all disk images
2396 * in */
2397 vrc = RTDirCreateTemp(pszTmpDir);
2398 if (RT_FAILURE(vrc))
2399 throw setError(VBOX_E_FILE_ERROR,
2400 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2401
2402 /* Add every disks of every virtual system to an internal list */
2403 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2404 for (it = m->virtualSystemDescriptions.begin();
2405 it != m->virtualSystemDescriptions.end();
2406 ++it)
2407 {
2408 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2409 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2410 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2411 for (itH = avsdeHDs.begin();
2412 itH != avsdeHDs.end();
2413 ++itH)
2414 {
2415 const Utf8Str &strTargetFile = (*itH)->strOvf;
2416 if (!strTargetFile.isEmpty())
2417 {
2418 /* The temporary name of the target disk file */
2419 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
2420 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
2421 }
2422 }
2423 }
2424
2425 /* Next we have to download the disk images */
2426 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2427 if (RT_FAILURE(vrc))
2428 throw setError(VBOX_E_IPRT_ERROR,
2429 tr("Cannot create S3 service handler"));
2430 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2431
2432 /* Download all files */
2433 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2434 {
2435 const pair<Utf8Str, ULONG> &s = (*it1);
2436 const Utf8Str &strSrcFile = s.first;
2437 /* Construct the source file name */
2438 char *pszFilename = RTPathFilename(strSrcFile.c_str());
2439 /* Advance to the next operation */
2440 if (!pTask->pProgress.isNull())
2441 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), s.second);
2442
2443 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
2444 if (RT_FAILURE(vrc))
2445 {
2446 if (vrc == VERR_S3_CANCELED)
2447 throw S_OK; /* todo: !!!!!!!!!!!!! */
2448 else if (vrc == VERR_S3_ACCESS_DENIED)
2449 throw setError(E_ACCESSDENIED,
2450 tr("Cannot download file '%s' from S3 storage server (Access denied). "
2451 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
2452 pszFilename);
2453 else if (vrc == VERR_S3_NOT_FOUND)
2454 throw setError(VBOX_E_FILE_ERROR,
2455 tr("Cannot download file '%s' from S3 storage server (File not found)"),
2456 pszFilename);
2457 else
2458 throw setError(VBOX_E_IPRT_ERROR,
2459 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
2460 pszFilename, vrc);
2461 }
2462 }
2463
2464 /* Provide a OVF file (haven't to exist) so the import routine can
2465 * figure out where the disk images/manifest file are located. */
2466 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2467 /* Now check if there is an manifest file. This is optional. */
2468 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
2469 char *pszFilename = RTPathFilename(strManifestFile.c_str());
2470 if (!pTask->pProgress.isNull())
2471 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), 1);
2472
2473 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
2474 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
2475 if (RT_SUCCESS(vrc))
2476 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
2477 else if (RT_FAILURE(vrc))
2478 {
2479 if (vrc == VERR_S3_CANCELED)
2480 throw S_OK; /* todo: !!!!!!!!!!!!! */
2481 else if (vrc == VERR_S3_NOT_FOUND)
2482 vrc = VINF_SUCCESS; /* Not found is ok */
2483 else if (vrc == VERR_S3_ACCESS_DENIED)
2484 throw setError(E_ACCESSDENIED,
2485 tr("Cannot download file '%s' from S3 storage server (Access denied)."
2486 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
2487 pszFilename);
2488 else
2489 throw setError(VBOX_E_IPRT_ERROR,
2490 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
2491 pszFilename, vrc);
2492 }
2493
2494 /* Close the connection early */
2495 RTS3Destroy(hS3);
2496 hS3 = NIL_RTS3;
2497
2498 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")).raw(), m->ulWeightForXmlOperation);
2499
2500 ComObjPtr<Progress> progress;
2501 /* Import the whole temporary OVF & the disk images */
2502 LocationInfo li;
2503 li.strPath = strTmpOvf;
2504 rc = importImpl(li, progress);
2505 if (FAILED(rc)) throw rc;
2506
2507 /* Unlock the appliance for the fs import thread */
2508 appLock.release();
2509 /* Wait until the import is done, but report the progress back to the
2510 caller */
2511 ComPtr<IProgress> progressInt(progress);
2512 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2513
2514 /* Again lock the appliance for the next steps */
2515 appLock.acquire();
2516 }
2517 catch(HRESULT aRC)
2518 {
2519 rc = aRC;
2520 }
2521 /* Cleanup */
2522 RTS3Destroy(hS3);
2523 /* Delete all files which where temporary created */
2524 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2525 {
2526 const char *pszFilePath = (*it1).first.c_str();
2527 if (RTPathExists(pszFilePath))
2528 {
2529 vrc = RTFileDelete(pszFilePath);
2530 if (RT_FAILURE(vrc))
2531 rc = setError(VBOX_E_FILE_ERROR,
2532 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2533 }
2534 }
2535 /* Delete the temporary directory */
2536 if (RTPathExists(pszTmpDir))
2537 {
2538 vrc = RTDirRemove(pszTmpDir);
2539 if (RT_FAILURE(vrc))
2540 rc = setError(VBOX_E_FILE_ERROR,
2541 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2542 }
2543 if (pszTmpDir)
2544 RTStrFree(pszTmpDir);
2545
2546 LogFlowFunc(("rc=%Rhrc\n", rc));
2547 LogFlowFuncLeave();
2548
2549 return rc;
2550}
2551
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