VirtualBox

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

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

Main: combine IVirtualBox::openHardDisk(), openDVDImage(), openFloppyImage() into new IVirtualBox::openMedium(); add new IMedium::setImageUUIDs() method for a rare use case of the old openHardDisk(); optimize client code now that code is mostly the same

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