VirtualBox

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

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

Main: new VirtualBox::ComposeMachineFilename() API; remove the 'default hard disk folder' concept and related APIs; GUI wizards need fixing

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