VirtualBox

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

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

OVF: respect override of import parameters (setFinalValues) also when vbox:Machine is present, first batch (everything except storage)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 95.8 KB
Line 
1/* $Id: ApplianceImplImport.cpp 29925 2010-05-31 18:33:15Z 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)) throw rc;
154 rc = pNewDesc->init();
155 if (FAILED(rc)) throw 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)) throw 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)) throw 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)) throw 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 Utf8Str hdcController = "LsiLogic";
447 if (!hdc.strControllerType.compare("lsilogicsas", Utf8Str::CaseInsensitive))
448 hdcController = "LsiLogicSas";
449 else if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
450 hdcController = "BusLogic";
451 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
452 strControllerID,
453 hdc.strControllerType,
454 hdcController);
455 }
456 else
457 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."),
458 vsysThis.strName.c_str(),
459 hdc.strControllerType.c_str(),
460 strControllerID.c_str());
461 ++cSCSIused;
462 break;
463 }
464 }
465
466 /* Hard disks */
467 if (vsysThis.mapVirtualDisks.size() > 0)
468 {
469 ovf::VirtualDisksMap::const_iterator itVD;
470 /* Iterate through all hard disks ()*/
471 for (itVD = vsysThis.mapVirtualDisks.begin();
472 itVD != vsysThis.mapVirtualDisks.end();
473 ++itVD)
474 {
475 const ovf::VirtualDisk &hd = itVD->second;
476 /* Get the associated disk image */
477 const ovf::DiskImage &di = m->pReader->m_mapDisks[hd.strDiskId];
478
479 // @todo:
480 // - figure out all possible vmdk formats we also support
481 // - figure out if there is a url specifier for vhd already
482 // - we need a url specifier for the vdi format
483 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
484 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
485 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
486 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
487 )
488 {
489 /* If the href is empty use the VM name as filename */
490 Utf8Str strFilename = di.strHref;
491 if (!strFilename.length())
492 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
493 /* Construct a unique target path */
494 Utf8StrFmt strPath("%s%c%s",
495 strDefaultHardDiskFolder.raw(),
496 RTPATH_DELIMITER,
497 strFilename.c_str());
498 searchUniqueDiskImageFilePath(strPath);
499
500 /* find the description for the hard disk controller
501 * that has the same ID as hd.idController */
502 const VirtualSystemDescriptionEntry *pController;
503 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
504 throw setError(E_FAIL,
505 tr("Cannot find hard disk controller with OVF instance ID %RI32 to which disk \"%s\" should be attached"),
506 hd.idController,
507 di.strHref.c_str());
508
509 /* controller to attach to, and the bus within that controller */
510 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
511 pController->ulIndex,
512 hd.ulAddressOnParent);
513 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
514 hd.strDiskId,
515 di.strHref,
516 strPath,
517 di.ulSuggestedSizeMB,
518 strExtraConfig);
519 }
520 else
521 throw setError(VBOX_E_FILE_ERROR,
522 tr("Unsupported format for virtual disk image in OVF: \"%s\"", di.strFormat.c_str()));
523 }
524 }
525
526 m->virtualSystemDescriptions.push_back(pNewDesc);
527 }
528 }
529 catch (HRESULT aRC)
530 {
531 /* On error we clear the list & return */
532 m->virtualSystemDescriptions.clear();
533 rc = aRC;
534 }
535
536 // reset the appliance state
537 alock.acquire();
538 m->state = Data::ApplianceIdle;
539
540 return rc;
541}
542
543/**
544 * Public method implementation. This creates one or more new machines according to the
545 * VirtualSystemScription instances created by Appliance::Interpret().
546 * Thread implementation is in Appliance::importImpl().
547 * @param aProgress
548 * @return
549 */
550STDMETHODIMP Appliance::ImportMachines(IProgress **aProgress)
551{
552 CheckComArgOutPointerValid(aProgress);
553
554 AutoCaller autoCaller(this);
555 if (FAILED(autoCaller.rc())) return autoCaller.rc();
556
557 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
558
559 // do not allow entering this method if the appliance is busy reading or writing
560 if (!isApplianceIdle())
561 return E_ACCESSDENIED;
562
563 if (!m->pReader)
564 return setError(E_FAIL,
565 tr("Cannot import machines without reading it first (call read() before importMachines())"));
566
567 ComObjPtr<Progress> progress;
568 HRESULT rc = S_OK;
569 try
570 {
571 rc = importImpl(m->locInfo, progress);
572 }
573 catch (HRESULT aRC)
574 {
575 rc = aRC;
576 }
577
578 if (SUCCEEDED(rc))
579 /* Return progress to the caller */
580 progress.queryInterfaceTo(aProgress);
581
582 return rc;
583}
584
585////////////////////////////////////////////////////////////////////////////////
586//
587// Appliance private methods
588//
589////////////////////////////////////////////////////////////////////////////////
590
591/**
592 * Implementation for reading an OVF. This starts a new thread which will call
593 * Appliance::taskThreadImportOrExport() which will then call readFS() or readS3().
594 * This will then open the OVF with ovfreader.cpp.
595 *
596 * This is in a separate private method because it is used from two locations:
597 *
598 * 1) from the public Appliance::Read().
599 * 2) from Appliance::readS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
600 *
601 * @param aLocInfo
602 * @param aProgress
603 * @return
604 */
605HRESULT Appliance::readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
606{
607 BstrFmt bstrDesc = BstrFmt(tr("Reading appliance '%s'"),
608 aLocInfo.strPath.c_str());
609 HRESULT rc;
610 /* Create the progress object */
611 aProgress.createObject();
612 if (aLocInfo.storageType == VFSType_File)
613 /* 1 operation only */
614 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
615 bstrDesc,
616 TRUE /* aCancelable */);
617 else
618 /* 4/5 is downloading, 1/5 is reading */
619 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
620 bstrDesc,
621 TRUE /* aCancelable */,
622 2, // ULONG cOperations,
623 5, // ULONG ulTotalOperationsWeight,
624 BstrFmt(tr("Download appliance '%s'"),
625 aLocInfo.strPath.c_str()), // CBSTR bstrFirstOperationDescription,
626 4); // ULONG ulFirstOperationWeight,
627 if (FAILED(rc)) throw rc;
628
629 /* Initialize our worker task */
630 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Read, aLocInfo, aProgress));
631
632 rc = task->startThread();
633 if (FAILED(rc)) throw rc;
634
635 /* Don't destruct on success */
636 task.release();
637
638 return rc;
639}
640
641/**
642 * Actual worker code for reading an OVF from disk. This is called from Appliance::taskThreadImportOrExport()
643 * and therefore runs on the OVF read worker thread. This opens the OVF with ovfreader.cpp.
644 *
645 * This runs in two contexts:
646 *
647 * 1) in a first worker thread; in that case, Appliance::Read() called Appliance::readImpl();
648 *
649 * 2) in a second worker thread; in that case, Appliance::Read() called Appliance::readImpl(), which
650 * called Appliance::readS3(), which called Appliance::readImpl(), which then called this.
651 *
652 * @param pTask
653 * @return
654 */
655HRESULT Appliance::readFS(const LocationInfo &locInfo)
656{
657 LogFlowFuncEnter();
658 LogFlowFunc(("Appliance %p\n", this));
659
660 AutoCaller autoCaller(this);
661 if (FAILED(autoCaller.rc())) return autoCaller.rc();
662
663 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
664
665 HRESULT rc = S_OK;
666
667 try
668 {
669 /* Read & parse the XML structure of the OVF file */
670 m->pReader = new ovf::OVFReader(locInfo.strPath);
671 /* Create the SHA1 sum of the OVF file for later validation */
672 char *pszDigest;
673 int vrc = RTSha1Digest(locInfo.strPath.c_str(), &pszDigest, NULL, NULL);
674 if (RT_FAILURE(vrc))
675 throw setError(VBOX_E_FILE_ERROR,
676 tr("Couldn't calculate SHA1 digest for file '%s' (%Rrc)"),
677 RTPathFilename(locInfo.strPath.c_str()), vrc);
678 m->strOVFSHA1Digest = pszDigest;
679 RTStrFree(pszDigest);
680 }
681 catch(xml::Error &x)
682 {
683 rc = setError(VBOX_E_FILE_ERROR,
684 x.what());
685 }
686 catch(HRESULT aRC)
687 {
688 rc = aRC;
689 }
690
691 LogFlowFunc(("rc=%Rhrc\n", rc));
692 LogFlowFuncLeave();
693
694 return rc;
695}
696
697/**
698 * Worker code for reading OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
699 * in S3 mode and therefore runs on the OVF read worker thread. This then starts a second worker
700 * thread to create temporary files (see Appliance::readFS()).
701 *
702 * @param pTask
703 * @return
704 */
705HRESULT Appliance::readS3(TaskOVF *pTask)
706{
707 LogFlowFuncEnter();
708 LogFlowFunc(("Appliance %p\n", this));
709
710 AutoCaller autoCaller(this);
711 if (FAILED(autoCaller.rc())) return autoCaller.rc();
712
713 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
714
715 HRESULT rc = S_OK;
716 int vrc = VINF_SUCCESS;
717 RTS3 hS3 = NIL_RTS3;
718 char szOSTmpDir[RTPATH_MAX];
719 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
720 /* The template for the temporary directory created below */
721 char *pszTmpDir;
722 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
723 list< pair<Utf8Str, ULONG> > filesList;
724 Utf8Str strTmpOvf;
725
726 try
727 {
728 /* Extract the bucket */
729 Utf8Str tmpPath = pTask->locInfo.strPath;
730 Utf8Str bucket;
731 parseBucket(tmpPath, bucket);
732
733 /* We need a temporary directory which we can put the OVF file & all
734 * disk images in */
735 vrc = RTDirCreateTemp(pszTmpDir);
736 if (RT_FAILURE(vrc))
737 throw setError(VBOX_E_FILE_ERROR,
738 tr("Cannot create temporary directory '%s'"), pszTmpDir);
739
740 /* The temporary name of the target OVF file */
741 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
742
743 /* Next we have to download the OVF */
744 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
745 if (RT_FAILURE(vrc))
746 throw setError(VBOX_E_IPRT_ERROR,
747 tr("Cannot create S3 service handler"));
748 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
749
750 /* Get it */
751 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
752 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
753 if (RT_FAILURE(vrc))
754 {
755 if (vrc == VERR_S3_CANCELED)
756 throw S_OK; /* todo: !!!!!!!!!!!!! */
757 else if (vrc == VERR_S3_ACCESS_DENIED)
758 throw setError(E_ACCESSDENIED,
759 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
760 else if (vrc == VERR_S3_NOT_FOUND)
761 throw setError(VBOX_E_FILE_ERROR,
762 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
763 else
764 throw setError(VBOX_E_IPRT_ERROR,
765 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
766 }
767
768 /* Close the connection early */
769 RTS3Destroy(hS3);
770 hS3 = NIL_RTS3;
771
772 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")), 1);
773
774 /* Prepare the temporary reading of the OVF */
775 ComObjPtr<Progress> progress;
776 LocationInfo li;
777 li.strPath = strTmpOvf;
778 /* Start the reading from the fs */
779 rc = readImpl(li, progress);
780 if (FAILED(rc)) throw rc;
781
782 /* Unlock the appliance for the reading thread */
783 appLock.release();
784 /* Wait until the reading is done, but report the progress back to the
785 caller */
786 ComPtr<IProgress> progressInt(progress);
787 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
788
789 /* Again lock the appliance for the next steps */
790 appLock.acquire();
791 }
792 catch(HRESULT aRC)
793 {
794 rc = aRC;
795 }
796 /* Cleanup */
797 RTS3Destroy(hS3);
798 /* Delete all files which where temporary created */
799 if (RTPathExists(strTmpOvf.c_str()))
800 {
801 vrc = RTFileDelete(strTmpOvf.c_str());
802 if (RT_FAILURE(vrc))
803 rc = setError(VBOX_E_FILE_ERROR,
804 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
805 }
806 /* Delete the temporary directory */
807 if (RTPathExists(pszTmpDir))
808 {
809 vrc = RTDirRemove(pszTmpDir);
810 if (RT_FAILURE(vrc))
811 rc = setError(VBOX_E_FILE_ERROR,
812 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
813 }
814 if (pszTmpDir)
815 RTStrFree(pszTmpDir);
816
817 LogFlowFunc(("rc=%Rhrc\n", rc));
818 LogFlowFuncLeave();
819
820 return rc;
821}
822
823/**
824 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
825 * Throws HRESULT values on errors!
826 *
827 * @param hdc in: the HardDiskController structure to attach to.
828 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
829 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
830 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
831 * @param lDevice out: the device number to attach to.
832 */
833void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
834 uint32_t ulAddressOnParent,
835 Bstr &controllerType,
836 int32_t &lControllerPort,
837 int32_t &lDevice)
838{
839 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n", hdc.system, hdc.fPrimary, ulAddressOnParent));
840
841 switch (hdc.system)
842 {
843 case ovf::HardDiskController::IDE:
844 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
845 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
846 // the device number can be either 0 or 1, to specify the master or the slave device,
847 // respectively. For the secondary IDE controller, the device number is always 1 because
848 // the master device is reserved for the CD-ROM drive.
849 controllerType = Bstr("IDE Controller");
850 switch (ulAddressOnParent)
851 {
852 case 0: // master
853 if (!hdc.fPrimary)
854 {
855 // secondary master
856 lControllerPort = (long)1;
857 lDevice = (long)0;
858 }
859 else // primary master
860 {
861 lControllerPort = (long)0;
862 lDevice = (long)0;
863 }
864 break;
865
866 case 1: // slave
867 if (!hdc.fPrimary)
868 {
869 // secondary slave
870 lControllerPort = (long)1;
871 lDevice = (long)1;
872 }
873 else // primary slave
874 {
875 lControllerPort = (long)0;
876 lDevice = (long)1;
877 }
878 break;
879
880 // used by older VBox exports
881 case 2: // interpret this as secondary master
882 lControllerPort = (long)1;
883 lDevice = (long)0;
884 break;
885
886 // used by older VBox exports
887 case 3: // interpret this as secondary slave
888 lControllerPort = (long)1;
889 lDevice = (long)1;
890 break;
891
892 default:
893 throw setError(VBOX_E_NOT_SUPPORTED,
894 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"), ulAddressOnParent);
895 break;
896 }
897 break;
898
899 case ovf::HardDiskController::SATA:
900 controllerType = Bstr("SATA Controller");
901 lControllerPort = (long)ulAddressOnParent;
902 lDevice = (long)0;
903 break;
904
905 case ovf::HardDiskController::SCSI:
906 controllerType = Bstr("SCSI Controller");
907 lControllerPort = (long)ulAddressOnParent;
908 lDevice = (long)0;
909 break;
910
911 default: break;
912 }
913
914 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
915}
916
917/**
918 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
919 * Appliance::taskThreadImportOrExport().
920 *
921 * This creates one or more new machines according to the VirtualSystemScription instances created by
922 * Appliance::Interpret().
923 *
924 * This is in a separate private method because it is used from two locations:
925 *
926 * 1) from the public Appliance::ImportMachines().
927 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
928 *
929 * @param aLocInfo
930 * @param aProgress
931 * @return
932 */
933HRESULT Appliance::importImpl(const LocationInfo &aLocInfo,
934 ComObjPtr<Progress> &aProgress)
935{
936 HRESULT rc = S_OK;
937
938 SetUpProgressMode mode;
939 m->strManifestFile.setNull();
940 if (aLocInfo.storageType == VFSType_File)
941 {
942 Utf8Str strMfFile = manifestFileName(aLocInfo.strPath);
943 if (RTPathExists(strMfFile.c_str()))
944 {
945 m->strManifestFile = strMfFile;
946 mode = ImportFileWithManifest;
947 }
948 else
949 mode = ImportFileNoManifest;
950 }
951 else
952 mode = ImportS3;
953
954 rc = setUpProgress(aProgress,
955 BstrFmt(tr("Importing appliance '%s'"), aLocInfo.strPath.c_str()),
956 mode);
957 if (FAILED(rc)) throw rc;
958
959 /* Initialize our worker task */
960 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, aLocInfo, aProgress));
961
962 rc = task->startThread();
963 if (FAILED(rc)) throw rc;
964
965 /* Don't destruct on success */
966 task.release();
967
968 return rc;
969}
970
971/**
972 * Checks if a manifest file exists in the given location and, if so, verifies
973 * that the relevant files (the OVF XML and the disks referenced by it, as
974 * represented by the VirtualSystemDescription instances contained in this appliance)
975 * match it. Requires a previous read() and interpret().
976 *
977 * @param locInfo
978 * @param reader
979 * @return
980 */
981HRESULT Appliance::manifestVerify(const LocationInfo &locInfo,
982 const ovf::OVFReader &reader,
983 ComObjPtr<Progress> &pProgress)
984{
985 HRESULT rc = S_OK;
986
987 if (!m->strManifestFile.isEmpty())
988 {
989 const char *pcszManifestFileOnly = RTPathFilename(m->strManifestFile.c_str());
990 pProgress->SetNextOperation(BstrFmt(tr("Verifying manifest file '%s'"), pcszManifestFileOnly),
991 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally
992
993 list<Utf8Str> filesList;
994 Utf8Str strSrcDir(locInfo.strPath);
995 strSrcDir.stripFilename();
996 // add every disks of every virtual system to an internal list
997 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
998 for (it = m->virtualSystemDescriptions.begin();
999 it != m->virtualSystemDescriptions.end();
1000 ++it)
1001 {
1002 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1003 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1004 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1005 for (itH = avsdeHDs.begin();
1006 itH != avsdeHDs.end();
1007 ++itH)
1008 {
1009 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1010 // find the disk from the OVF's disk list
1011 ovf::DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1012 const ovf::DiskImage &di = itDiskImage->second;
1013 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1014 filesList.push_back(strSrcFilePath);
1015 }
1016 }
1017
1018 // create the test list
1019 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST) * (filesList.size() + 1));
1020 pTestList[0].pszTestFile = (char*)locInfo.strPath.c_str();
1021 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1022 int vrc = VINF_SUCCESS;
1023 size_t i = 1;
1024 list<Utf8Str>::const_iterator it1;
1025 for (it1 = filesList.begin();
1026 it1 != filesList.end();
1027 ++it1, ++i)
1028 {
1029 char* pszDigest;
1030 vrc = RTSha1Digest((*it1).c_str(), &pszDigest, NULL, NULL);
1031 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1032 pTestList[i].pszTestDigest = pszDigest;
1033 }
1034
1035 // this call can take a very long time
1036 size_t cIndexOnError;
1037 vrc = RTManifestVerify(m->strManifestFile.c_str(),
1038 pTestList,
1039 filesList.size() + 1,
1040 &cIndexOnError);
1041
1042 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1043 rc = setError(VBOX_E_FILE_ERROR,
1044 tr("The SHA1 digest of '%s' does not match the one in '%s'"),
1045 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1046 pcszManifestFileOnly);
1047 else if (RT_FAILURE(vrc))
1048 rc = setError(VBOX_E_FILE_ERROR,
1049 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1050 pcszManifestFileOnly,
1051 vrc);
1052
1053 // clean up
1054 for (size_t j = 1;
1055 j < filesList.size();
1056 ++j)
1057 RTStrFree(pTestList[j].pszTestDigest);
1058 RTMemFree(pTestList);
1059 }
1060
1061 return rc;
1062}
1063
1064/**
1065 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1066 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1067 * VirtualSystemScription instances created by Appliance::Interpret().
1068 *
1069 * This runs in two contexts:
1070 *
1071 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1072 *
1073 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1074 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this.
1075 *
1076 * @param pTask
1077 * @return
1078 */
1079HRESULT Appliance::importFS(const LocationInfo &locInfo,
1080 ComObjPtr<Progress> &pProgress)
1081{
1082 LogFlowFuncEnter();
1083 LogFlowFunc(("Appliance %p\n", this));
1084
1085 AutoCaller autoCaller(this);
1086 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1087
1088 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1089
1090 if (!isApplianceIdle())
1091 return E_ACCESSDENIED;
1092
1093 Assert(!pProgress.isNull());
1094
1095 // Change the appliance state so we can safely leave the lock while doing time-consuming
1096 // disk imports; also the below method calls do all kinds of locking which conflicts with
1097 // the appliance object lock
1098 m->state = Data::ApplianceImporting;
1099 appLock.release();
1100
1101 HRESULT rc = S_OK;
1102
1103 const ovf::OVFReader &reader = *m->pReader;
1104 // this is safe to access because this thread only gets started
1105 // if pReader != NULL
1106
1107 // rollback for errors:
1108 ImportStack stack(locInfo, reader.m_mapDisks, pProgress);
1109
1110 try
1111 {
1112 // if a manifest file exists, verify the content; we then need all files which are referenced by the OVF & the OVF itself
1113 rc = manifestVerify(locInfo, reader, pProgress);
1114 if (FAILED(rc)) throw rc;
1115
1116 // create a session for the machine + disks we manipulate below
1117 rc = stack.pSession.createInprocObject(CLSID_Session);
1118 if (FAILED(rc)) throw rc;
1119
1120 list<ovf::VirtualSystem>::const_iterator it;
1121 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1122 /* Iterate through all virtual systems of that appliance */
1123 size_t i = 0;
1124 for (it = reader.m_llVirtualSystems.begin(),
1125 it1 = m->virtualSystemDescriptions.begin();
1126 it != reader.m_llVirtualSystems.end();
1127 ++it, ++it1, ++i)
1128 {
1129 const ovf::VirtualSystem &vsysThis = *it;
1130 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1131
1132 ComPtr<IMachine> pNewMachine;
1133
1134 // there are two ways in which we can create a vbox machine from OVF:
1135 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
1136 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
1137 // with all the machine config pretty-parsed;
1138 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
1139 // VirtualSystemDescriptionEntry and do import work
1140
1141 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
1142 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
1143
1144 // VM name
1145 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1146 if (vsdeName.size() < 1)
1147 throw setError(VBOX_E_FILE_ERROR,
1148 tr("Missing VM name"));
1149 stack.strNameVBox = vsdeName.front()->strVboxCurrent;
1150
1151 // guest OS type
1152 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1153 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1154 if (vsdeOS.size() < 1)
1155 throw setError(VBOX_E_FILE_ERROR,
1156 tr("Missing guest OS type"));
1157 stack.strOsTypeVBox = vsdeOS.front()->strVboxCurrent;
1158
1159 // CPU count
1160 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
1161 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1162 const Utf8Str &cpuVBox = vsdeCPU.front()->strVboxCurrent;
1163 stack.cCPUs = (uint32_t)RTStrToUInt64(cpuVBox.c_str());
1164 // We need HWVirt & IO-APIC if more than one CPU is requested
1165 if (stack.cCPUs > 1)
1166 {
1167 stack.fForceHWVirt = true;
1168 stack.fForceIOAPIC = true;
1169 }
1170
1171 // RAM
1172 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1173 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1174 const Utf8Str &memoryVBox = vsdeRAM.front()->strVboxCurrent;
1175 stack.ulMemorySizeMB = (uint32_t)RTStrToUInt64(memoryVBox.c_str());
1176
1177 // USB controller
1178#ifdef VBOX_WITH_USB
1179 /* USB Controller */
1180 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1181 // USB support is enabled if there's at least one such entry; to disable USB support,
1182 // the type of the USB item would have been changed to "ignore"
1183 stack.fUSBEnabled = vsdeUSBController.size() > 0;
1184#endif
1185 // audio adapter
1186 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1187 /* @todo: we support one audio adapter only */
1188 if (vsdeAudioAdapter.size() > 0)
1189 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVboxCurrent;
1190
1191 // import vbox:machine or OVF now
1192 if (vsdescThis->m->pConfig)
1193 // vbox:Machine config
1194 importVBoxMachine(vsdescThis, pNewMachine, stack);
1195 else
1196 // generic OVF config
1197 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
1198
1199 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
1200 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1201 if (vsdeDescription.size())
1202 {
1203 const Utf8Str &strDescription = vsdeDescription.front()->strVboxCurrent;
1204 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1205 if (FAILED(rc)) throw rc;
1206 }
1207 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
1208 }
1209 catch (HRESULT rc2)
1210 {
1211 rc = rc2;
1212 }
1213
1214 if (FAILED(rc))
1215 {
1216 // with _whatever_ error we've had, do a complete roll-back of
1217 // machines and disks we've created; unfortunately this is
1218 // not so trivially done...
1219
1220 HRESULT rc2;
1221 // detach all hard disks from all machines we created
1222 list<MyHardDiskAttachment>::iterator itM;
1223 for (itM = stack.llHardDiskAttachments.begin();
1224 itM != stack.llHardDiskAttachments.end();
1225 ++itM)
1226 {
1227 const MyHardDiskAttachment &mhda = *itM;
1228 Bstr bstrUuid(mhda.bstrUuid); // make a copy, Windows can't handle const Bstr
1229 rc2 = mVirtualBox->OpenSession(stack.pSession, bstrUuid);
1230 if (SUCCEEDED(rc2))
1231 {
1232 ComPtr<IMachine> sMachine;
1233 rc2 = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1234 if (SUCCEEDED(rc2))
1235 {
1236 rc2 = sMachine->DetachDevice(Bstr(mhda.controllerType), mhda.lControllerPort, mhda.lDevice);
1237 rc2 = sMachine->SaveSettings();
1238 }
1239 stack.pSession->Close();
1240 }
1241 }
1242
1243 // now clean up all hard disks we created
1244 list< ComPtr<IMedium> >::iterator itHD;
1245 for (itHD = stack.llHardDisksCreated.begin();
1246 itHD != stack.llHardDisksCreated.end();
1247 ++itHD)
1248 {
1249 ComPtr<IMedium> pDisk = *itHD;
1250 ComPtr<IProgress> pProgress2;
1251 rc2 = pDisk->DeleteStorage(pProgress2.asOutParam());
1252 rc2 = pProgress2->WaitForCompletion(-1);
1253 }
1254
1255 // finally, deregister and remove all machines
1256 list<Bstr>::iterator itID;
1257 for (itID = stack.llMachinesRegistered.begin();
1258 itID != stack.llMachinesRegistered.end();
1259 ++itID)
1260 {
1261 Bstr bstrGuid = *itID; // make a copy, Windows can't handle const Bstr
1262 ComPtr<IMachine> failedMachine;
1263 rc2 = mVirtualBox->UnregisterMachine(bstrGuid, failedMachine.asOutParam());
1264 if (SUCCEEDED(rc2))
1265 rc2 = failedMachine->DeleteSettings();
1266 }
1267 }
1268
1269 // restore the appliance state
1270 appLock.acquire();
1271 m->state = Data::ApplianceIdle;
1272 appLock.release();
1273
1274 LogFlowFunc(("rc=%Rhrc\n", rc));
1275 LogFlowFuncLeave();
1276
1277 return rc;
1278}
1279
1280/**
1281 * Imports one disk image. This is common code shared between
1282 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1283 * the OVF virtual systems;
1284 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1285 * tag.
1286 *
1287 * Both ways of describing machines use the OVF disk references section, so in both cases
1288 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1289 *
1290 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1291 * spec, even though this cannot really happen in the vbox:Machine case since such data
1292 * would never have been exported.
1293 *
1294 * This advances stack.pProgress by one operation with the disk's weight.
1295 *
1296 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1297 * @param ulSizeMB Size of the disk image (for progress reporting)
1298 * @param strTargetPath Where to create the target image.
1299 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1300 * @param stack
1301 */
1302void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1303 const Utf8Str &strTargetPath,
1304 ComPtr<IMedium> &pTargetHD,
1305 ImportStack &stack)
1306{
1307 ComPtr<IMedium> pSourceHD;
1308 bool fSourceHdNeedsClosing = false;
1309
1310 try
1311 {
1312 // destination file must not exist
1313 if ( strTargetPath.isEmpty()
1314 || RTPathExists(strTargetPath.c_str())
1315 )
1316 throw setError(VBOX_E_FILE_ERROR,
1317 tr("Destination file '%s' exists"),
1318 strTargetPath.c_str());
1319
1320 const Utf8Str &strSourceOVF = di.strHref;
1321
1322 // Make sure target directory exists
1323 HRESULT rc = VirtualBox::ensureFilePathExists(strTargetPath.c_str());
1324 if (FAILED(rc))
1325 throw rc;
1326
1327 // subprogress object for hard disk
1328 ComPtr<IProgress> pProgress2;
1329
1330 /* If strHref is empty we have to create a new file */
1331 if (strSourceOVF.isEmpty())
1332 {
1333 // which format to use?
1334 Bstr srcFormat = L"VDI";
1335 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1336 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1337 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1338 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1339 )
1340 srcFormat = L"VMDK";
1341 // create an empty hard disk
1342 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1343 if (FAILED(rc)) throw rc;
1344
1345 // create a dynamic growing disk image with the given capacity
1346 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1347 if (FAILED(rc)) throw rc;
1348
1349 // advance to the next operation
1350 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()),
1351 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1352 }
1353 else
1354 {
1355 // construct source file path
1356 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1357 // source path must exist
1358 if (!RTPathExists(strSrcFilePath.c_str()))
1359 throw setError(VBOX_E_FILE_ERROR,
1360 tr("Source virtual disk image file '%s' doesn't exist"),
1361 strSrcFilePath.c_str());
1362
1363 // Clone the disk image (this is necessary cause the id has
1364 // to be recreated for the case the same hard disk is
1365 // attached already from a previous import)
1366
1367 // First open the existing disk image
1368 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1369 AccessMode_ReadOnly,
1370 false,
1371 NULL,
1372 false,
1373 NULL,
1374 pSourceHD.asOutParam());
1375 if (FAILED(rc)) throw rc;
1376 fSourceHdNeedsClosing = true;
1377
1378 /* We need the format description of the source disk image */
1379 Bstr srcFormat;
1380 rc = pSourceHD->COMGETTER(Format)(srcFormat.asOutParam());
1381 if (FAILED(rc)) throw rc;
1382 /* Create a new hard disk interface for the destination disk image */
1383 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1384 if (FAILED(rc)) throw rc;
1385 /* Clone the source disk image */
1386 rc = pSourceHD->CloneTo(pTargetHD, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1387 if (FAILED(rc)) throw rc;
1388
1389 /* Advance to the next operation */
1390 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1391 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1392 }
1393
1394 // now wait for the background disk operation to complete; this throws HRESULTs on error
1395 waitForAsyncProgress(stack.pProgress, pProgress2);
1396
1397 if (fSourceHdNeedsClosing)
1398 {
1399 rc = pSourceHD->Close();
1400 if (FAILED(rc)) throw rc;
1401 fSourceHdNeedsClosing = false;
1402 }
1403
1404 stack.llHardDisksCreated.push_back(pTargetHD);
1405 }
1406 catch (...)
1407 {
1408 if (fSourceHdNeedsClosing)
1409 pSourceHD->Close();
1410
1411 throw;
1412 }
1413}
1414
1415/**
1416 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1417 * into VirtualBox by creating an IMachine instance, which is returned.
1418 *
1419 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1420 * up any leftovers from this function. For this, the given ImportStack instance has received information
1421 * about what needs cleaning up (to support rollback).
1422 *
1423 * @param vsysThis OVF virtual system (machine) to import.
1424 * @param vsdescThis Matching virtual system description (machine) to import.
1425 * @param pNewMachine out: Newly created machine.
1426 * @param stack Cleanup stack for when this throws.
1427 */
1428void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1429 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1430 ComPtr<IMachine> &pNewMachine,
1431 ImportStack &stack)
1432{
1433 HRESULT rc;
1434
1435 // Get the instance of IGuestOSType which matches our string guest OS type so we
1436 // can use recommended defaults for the new machine where OVF doesen't provice any
1437 ComPtr<IGuestOSType> osType;
1438 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox), osType.asOutParam());
1439 if (FAILED(rc)) throw rc;
1440
1441 /* Create the machine */
1442 rc = mVirtualBox->CreateMachine(Bstr(stack.strNameVBox),
1443 Bstr(stack.strOsTypeVBox),
1444 NULL,
1445 NULL,
1446 FALSE,
1447 pNewMachine.asOutParam());
1448 if (FAILED(rc)) throw rc;
1449
1450 // set the description
1451 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1452 if (vsdeDescription.size())
1453 {
1454 const Utf8Str &strDescription = vsdeDescription.front()->strVboxCurrent;
1455 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1456 if (FAILED(rc)) throw rc;
1457 }
1458
1459 // CPU count
1460 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
1461 if (FAILED(rc)) throw rc;
1462
1463 if (stack.fForceHWVirt)
1464 {
1465 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1466 if (FAILED(rc)) throw rc;
1467 }
1468
1469 // RAM
1470 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
1471 if (FAILED(rc)) throw rc;
1472
1473 /* VRAM */
1474 /* Get the recommended VRAM for this guest OS type */
1475 ULONG vramVBox;
1476 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1477 if (FAILED(rc)) throw rc;
1478
1479 /* Set the VRAM */
1480 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1481 if (FAILED(rc)) throw rc;
1482
1483 // I/O APIC: Generic OVF has no setting for this. Enable it if we
1484 // import a Windows VM because if if Windows was installed without IOAPIC,
1485 // it will not mind finding an one later on, but if Windows was installed
1486 // _with_ an IOAPIC, it will bluescreen if it's not found
1487 if (!stack.fForceIOAPIC)
1488 {
1489 Bstr bstrFamilyId;
1490 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1491 if (FAILED(rc)) throw rc;
1492 if (bstrFamilyId == "Windows")
1493 stack.fForceIOAPIC = true;
1494 }
1495
1496 if (stack.fForceIOAPIC)
1497 {
1498 ComPtr<IBIOSSettings> pBIOSSettings;
1499 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1500 if (FAILED(rc)) throw rc;
1501
1502 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1503 if (FAILED(rc)) throw rc;
1504 }
1505
1506 if (!stack.strAudioAdapter.isEmpty())
1507 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
1508 {
1509 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
1510 ComPtr<IAudioAdapter> audioAdapter;
1511 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1512 if (FAILED(rc)) throw rc;
1513 rc = audioAdapter->COMSETTER(Enabled)(true);
1514 if (FAILED(rc)) throw rc;
1515 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1516 if (FAILED(rc)) throw rc;
1517 }
1518
1519#ifdef VBOX_WITH_USB
1520 /* USB Controller */
1521 ComPtr<IUSBController> usbController;
1522 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1523 if (FAILED(rc)) throw rc;
1524 rc = usbController->COMSETTER(Enabled)(stack.fUSBEnabled);
1525 if (FAILED(rc)) throw rc;
1526#endif /* VBOX_WITH_USB */
1527
1528 /* Change the network adapters */
1529 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1530 if (vsdeNW.size() == 0)
1531 {
1532 /* No network adapters, so we have to disable our default one */
1533 ComPtr<INetworkAdapter> nwVBox;
1534 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1535 if (FAILED(rc)) throw rc;
1536 rc = nwVBox->COMSETTER(Enabled)(false);
1537 if (FAILED(rc)) throw rc;
1538 }
1539 else if (vsdeNW.size() > SchemaDefs::NetworkAdapterCount)
1540 throw setError(VBOX_E_FILE_ERROR,
1541 tr("Too many network adapters: OVF requests %d network adapters, but VirtualBox only supports %d"),
1542 vsdeNW.size(), SchemaDefs::NetworkAdapterCount);
1543 else
1544 {
1545 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1546 size_t a = 0;
1547 for (nwIt = vsdeNW.begin();
1548 nwIt != vsdeNW.end();
1549 ++nwIt, ++a)
1550 {
1551 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1552
1553 const Utf8Str &nwTypeVBox = pvsys->strVboxCurrent;
1554 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1555 ComPtr<INetworkAdapter> pNetworkAdapter;
1556 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1557 if (FAILED(rc)) throw rc;
1558 /* Enable the network card & set the adapter type */
1559 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1560 if (FAILED(rc)) throw rc;
1561 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1562 if (FAILED(rc)) throw rc;
1563
1564 // default is NAT; change to "bridged" if extra conf says so
1565 if (!pvsys->strExtraConfigCurrent.compare("type=Bridged", Utf8Str::CaseInsensitive))
1566 {
1567 /* Attach to the right interface */
1568 rc = pNetworkAdapter->AttachToBridgedInterface();
1569 if (FAILED(rc)) throw rc;
1570 ComPtr<IHost> host;
1571 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1572 if (FAILED(rc)) throw rc;
1573 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1574 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1575 if (FAILED(rc)) throw rc;
1576 // We search for the first host network interface which
1577 // is usable for bridged networking
1578 for (size_t j = 0;
1579 j < nwInterfaces.size();
1580 ++j)
1581 {
1582 HostNetworkInterfaceType_T itype;
1583 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1584 if (FAILED(rc)) throw rc;
1585 if (itype == HostNetworkInterfaceType_Bridged)
1586 {
1587 Bstr name;
1588 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1589 if (FAILED(rc)) throw rc;
1590 /* Set the interface name to attach to */
1591 pNetworkAdapter->COMSETTER(HostInterface)(name);
1592 if (FAILED(rc)) throw rc;
1593 break;
1594 }
1595 }
1596 }
1597 /* Next test for host only interfaces */
1598 else if (!pvsys->strExtraConfigCurrent.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1599 {
1600 /* Attach to the right interface */
1601 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1602 if (FAILED(rc)) throw rc;
1603 ComPtr<IHost> host;
1604 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1605 if (FAILED(rc)) throw rc;
1606 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1607 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1608 if (FAILED(rc)) throw rc;
1609 // We search for the first host network interface which
1610 // is usable for host only networking
1611 for (size_t j = 0;
1612 j < nwInterfaces.size();
1613 ++j)
1614 {
1615 HostNetworkInterfaceType_T itype;
1616 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1617 if (FAILED(rc)) throw rc;
1618 if (itype == HostNetworkInterfaceType_HostOnly)
1619 {
1620 Bstr name;
1621 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1622 if (FAILED(rc)) throw rc;
1623 /* Set the interface name to attach to */
1624 pNetworkAdapter->COMSETTER(HostInterface)(name);
1625 if (FAILED(rc)) throw rc;
1626 break;
1627 }
1628 }
1629 }
1630 }
1631 }
1632
1633 // IDE Hard disk controller
1634 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1635 // In OVF (at least VMware's version of it), an IDE controller has two ports, so VirtualBox's single IDE controller
1636 // with two channels and two ports each counts as two OVF IDE controllers -- so we accept one or two such IDE controllers
1637 uint32_t cIDEControllers = vsdeHDCIDE.size();
1638 if (cIDEControllers > 2)
1639 throw setError(VBOX_E_FILE_ERROR,
1640 tr("Too many IDE controllers in OVF; import facility only supports two"));
1641 if (vsdeHDCIDE.size() > 0)
1642 {
1643 // one or two IDE controllers present in OVF: add one VirtualBox controller
1644 ComPtr<IStorageController> pController;
1645 rc = pNewMachine->AddStorageController(Bstr("IDE Controller"), StorageBus_IDE, pController.asOutParam());
1646 if (FAILED(rc)) throw rc;
1647
1648 const char *pcszIDEType = vsdeHDCIDE.front()->strVboxCurrent.c_str();
1649 if (!strcmp(pcszIDEType, "PIIX3"))
1650 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1651 else if (!strcmp(pcszIDEType, "PIIX4"))
1652 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1653 else if (!strcmp(pcszIDEType, "ICH6"))
1654 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1655 else
1656 throw setError(VBOX_E_FILE_ERROR,
1657 tr("Invalid IDE controller type \"%s\""),
1658 pcszIDEType);
1659 if (FAILED(rc)) throw rc;
1660 }
1661
1662 /* Hard disk controller SATA */
1663 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1664 if (vsdeHDCSATA.size() > 1)
1665 throw setError(VBOX_E_FILE_ERROR,
1666 tr("Too many SATA controllers in OVF; import facility only supports one"));
1667 if (vsdeHDCSATA.size() > 0)
1668 {
1669 ComPtr<IStorageController> pController;
1670 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVboxCurrent;
1671 if (hdcVBox == "AHCI")
1672 {
1673 rc = pNewMachine->AddStorageController(Bstr("SATA Controller"), StorageBus_SATA, pController.asOutParam());
1674 if (FAILED(rc)) throw rc;
1675 }
1676 else
1677 throw setError(VBOX_E_FILE_ERROR,
1678 tr("Invalid SATA controller type \"%s\""),
1679 hdcVBox.c_str());
1680 }
1681
1682 /* Hard disk controller SCSI */
1683 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1684 if (vsdeHDCSCSI.size() > 1)
1685 throw setError(VBOX_E_FILE_ERROR,
1686 tr("Too many SCSI controllers in OVF; import facility only supports one"));
1687 if (vsdeHDCSCSI.size() > 0)
1688 {
1689 ComPtr<IStorageController> pController;
1690 Bstr bstrName(L"SCSI Controller");
1691 StorageBus_T busType = StorageBus_SCSI;
1692 StorageControllerType_T controllerType;
1693 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVboxCurrent;
1694 if (hdcVBox == "LsiLogic")
1695 controllerType = StorageControllerType_LsiLogic;
1696 else if (hdcVBox == "LsiLogicSas")
1697 {
1698 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
1699 bstrName = L"SAS Controller";
1700 busType = StorageBus_SAS;
1701 controllerType = StorageControllerType_LsiLogicSas;
1702 }
1703 else if (hdcVBox == "BusLogic")
1704 controllerType = StorageControllerType_BusLogic;
1705 else
1706 throw setError(VBOX_E_FILE_ERROR,
1707 tr("Invalid SCSI controller type \"%s\""),
1708 hdcVBox.c_str());
1709
1710 rc = pNewMachine->AddStorageController(bstrName, busType, pController.asOutParam());
1711 if (FAILED(rc)) throw rc;
1712 rc = pController->COMSETTER(ControllerType)(controllerType);
1713 if (FAILED(rc)) throw rc;
1714 }
1715
1716 /* Now its time to register the machine before we add any hard disks */
1717 rc = mVirtualBox->RegisterMachine(pNewMachine);
1718 if (FAILED(rc)) throw rc;
1719
1720 // store new machine for roll-back in case of errors
1721 Bstr bstrNewMachineId;
1722 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
1723 if (FAILED(rc)) throw rc;
1724 stack.llMachinesRegistered.push_back(bstrNewMachineId);
1725
1726 // Add floppies and CD-ROMs to the appropriate controllers.
1727 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1728 if (vsdeFloppy.size() > 1)
1729 throw setError(VBOX_E_FILE_ERROR,
1730 tr("Too many floppy controllers in OVF; import facility only supports one"));
1731 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1732 if ( (vsdeFloppy.size() > 0)
1733 || (vsdeCDROM.size() > 0)
1734 )
1735 {
1736 // If there's an error here we need to close the session, so
1737 // we need another try/catch block.
1738
1739 try
1740 {
1741 // to attach things we need to open a session for the new machine
1742 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1743 if (FAILED(rc)) throw rc;
1744 stack.fSessionOpen = true;
1745
1746 ComPtr<IMachine> sMachine;
1747 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1748 if (FAILED(rc)) throw rc;
1749
1750 // floppy first
1751 if (vsdeFloppy.size() == 1)
1752 {
1753 ComPtr<IStorageController> pController;
1754 rc = sMachine->AddStorageController(Bstr("Floppy Controller"), StorageBus_Floppy, pController.asOutParam());
1755 if (FAILED(rc)) throw rc;
1756
1757 Bstr bstrName;
1758 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1759 if (FAILED(rc)) throw rc;
1760
1761 // this is for rollback later
1762 MyHardDiskAttachment mhda;
1763 mhda.bstrUuid = bstrNewMachineId;
1764 mhda.pMachine = pNewMachine;
1765 mhda.controllerType = bstrName;
1766 mhda.lControllerPort = 0;
1767 mhda.lDevice = 0;
1768
1769 Log(("Attaching floppy\n"));
1770
1771 rc = sMachine->AttachDevice(mhda.controllerType,
1772 mhda.lControllerPort,
1773 mhda.lDevice,
1774 DeviceType_Floppy,
1775 NULL);
1776 if (FAILED(rc)) throw rc;
1777
1778 stack.llHardDiskAttachments.push_back(mhda);
1779 }
1780
1781 // CD-ROMs next
1782 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
1783 jt != vsdeCDROM.end();
1784 ++jt)
1785 {
1786 // for now always attach to secondary master on IDE controller;
1787 // there seems to be no useful information in OVF where else to
1788 // attach it (@todo test with latest versions of OVF software)
1789
1790 // find the IDE controller
1791 const ovf::HardDiskController *pController = NULL;
1792 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
1793 kt != vsysThis.mapControllers.end();
1794 ++kt)
1795 {
1796 if (kt->second.system == ovf::HardDiskController::IDE)
1797 {
1798 pController = &kt->second;
1799 break;
1800 }
1801 }
1802
1803 if (!pController)
1804 throw setError(VBOX_E_FILE_ERROR,
1805 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
1806
1807 // this is for rollback later
1808 MyHardDiskAttachment mhda;
1809 mhda.bstrUuid = bstrNewMachineId;
1810 mhda.pMachine = pNewMachine;
1811
1812 convertDiskAttachmentValues(*pController,
1813 2, // interpreted as secondary master
1814 mhda.controllerType, // Bstr
1815 mhda.lControllerPort,
1816 mhda.lDevice);
1817
1818 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
1819
1820 rc = sMachine->AttachDevice(mhda.controllerType,
1821 mhda.lControllerPort,
1822 mhda.lDevice,
1823 DeviceType_DVD,
1824 NULL);
1825 if (FAILED(rc)) throw rc;
1826
1827 stack.llHardDiskAttachments.push_back(mhda);
1828 } // end for (itHD = avsdeHDs.begin();
1829
1830 rc = sMachine->SaveSettings();
1831 if (FAILED(rc)) throw rc;
1832
1833 // only now that we're done with all disks, close the session
1834 rc = stack.pSession->Close();
1835 if (FAILED(rc)) throw rc;
1836 stack.fSessionOpen = false;
1837 }
1838 catch(HRESULT /* aRC */)
1839 {
1840 if (stack.fSessionOpen)
1841 stack.pSession->Close();
1842
1843 throw;
1844 }
1845 }
1846
1847 // create the hard disks & connect them to the appropriate controllers
1848 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1849 if (avsdeHDs.size() > 0)
1850 {
1851 // If there's an error here we need to close the session, so
1852 // we need another try/catch block.
1853 try
1854 {
1855 // to attach things we need to open a session for the new machine
1856 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1857 if (FAILED(rc)) throw rc;
1858 stack.fSessionOpen = true;
1859
1860 /* Iterate over all given disk images */
1861 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1862 for (itHD = avsdeHDs.begin();
1863 itHD != avsdeHDs.end();
1864 ++itHD)
1865 {
1866 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1867
1868 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1869 // in the virtual system's disks map under that ID and also in the global images map
1870 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1871 // and find the disk from the OVF's disk list
1872 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
1873 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
1874 || (itDiskImage == stack.mapDisks.end())
1875 )
1876 throw setError(E_FAIL,
1877 tr("Internal inconsistency looking up disk image '%s'"),
1878 vsdeHD->strRef.c_str());
1879
1880 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
1881 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
1882
1883 ComPtr<IMedium> pTargetHD;
1884 importOneDiskImage(ovfDiskImage,
1885 vsdeHD->strVboxCurrent,
1886 pTargetHD,
1887 stack);
1888
1889 // now use the new uuid to attach the disk image to our new machine
1890 ComPtr<IMachine> sMachine;
1891 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1892 if (FAILED(rc)) throw rc;
1893 Bstr hdId;
1894 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
1895 if (FAILED(rc)) throw rc;
1896
1897 // find the hard disk controller to which we should attach
1898 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
1899
1900 // this is for rollback later
1901 MyHardDiskAttachment mhda;
1902 mhda.bstrUuid = bstrNewMachineId;
1903 mhda.pMachine = pNewMachine;
1904
1905 convertDiskAttachmentValues(hdc,
1906 ovfVdisk.ulAddressOnParent,
1907 mhda.controllerType, // Bstr
1908 mhda.lControllerPort,
1909 mhda.lDevice);
1910
1911 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVboxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
1912
1913 rc = sMachine->AttachDevice(mhda.controllerType, // wstring name
1914 mhda.lControllerPort, // long controllerPort
1915 mhda.lDevice, // long device
1916 DeviceType_HardDisk, // DeviceType_T type
1917 hdId); // uuid id
1918 if (FAILED(rc)) throw rc;
1919
1920 stack.llHardDiskAttachments.push_back(mhda);
1921
1922 rc = sMachine->SaveSettings();
1923 if (FAILED(rc)) throw rc;
1924 } // end for (itHD = avsdeHDs.begin();
1925
1926 // only now that we're done with all disks, close the session
1927 rc = stack.pSession->Close();
1928 if (FAILED(rc)) throw rc;
1929 stack.fSessionOpen = false;
1930 }
1931 catch(HRESULT /* aRC */)
1932 {
1933 if (stack.fSessionOpen)
1934 stack.pSession->Close();
1935
1936 throw;
1937 }
1938 }
1939}
1940
1941/**
1942 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
1943 * structure) into VirtualBox by creating an IMachine instance, which is returned.
1944 *
1945 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1946 * up any leftovers from this function. For this, the given ImportStack instance has received information
1947 * about what needs cleaning up (to support rollback).
1948 *
1949 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
1950 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
1951 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
1952 * will most probably work, reimporting them into the same host will cause conflicts, so we always
1953 * generate new ones on import. This involves the following:
1954 *
1955 * 1) Scan the machine config for disk attachments.
1956 *
1957 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
1958 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
1959 * replace the old UUID with the new one.
1960 *
1961 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
1962 * caller has modified them using setFinalValues().
1963 *
1964 * 4) Create the VirtualBox machine with the modfified machine config.
1965 *
1966 * @param config
1967 * @param pNewMachine
1968 * @param stack
1969 */
1970void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
1971 ComPtr<IMachine> &pReturnNewMachine,
1972 ImportStack &stack)
1973{
1974 Assert(vsdescThis->m->pConfig);
1975
1976 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
1977
1978 Utf8Str strDefaultHardDiskFolder;
1979 HRESULT rc = getDefaultHardDiskFolder(strDefaultHardDiskFolder);
1980 if (FAILED(rc)) throw rc;
1981
1982 /*
1983 *
1984 * step 1): modify machine config according to OVF config, in case the user
1985 * has modified them using setFinalValues()
1986 *
1987 */
1988
1989// std::list<VirtualSystemDescriptionEntry*> llVSDEs;
1990
1991 config.hardwareMachine.cCPUs = stack.cCPUs;
1992 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
1993 if (stack.fForceIOAPIC)
1994 config.hardwareMachine.fHardwareVirt = true;
1995 if (stack.fForceIOAPIC)
1996 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
1997
1998/*
1999 <const name="HardDiskControllerIDE" value="14" />
2000 <const name="HardDiskControllerSATA" value="15" />
2001 <const name="HardDiskControllerSCSI" value="16" />
2002 <const name="HardDiskControllerSAS" value="17" />
2003 <const name="HardDiskImage" value="18" />
2004 <const name="Floppy" value="19" />
2005 <const name="CDROM" value="20" />
2006 <const name="NetworkAdapter" value="21" />
2007*/
2008
2009#ifdef VBOX_WITH_USB
2010 // disable USB if user disabled USB
2011 config.hardwareMachine.usbController.fEnabled = stack.fUSBEnabled;
2012#endif
2013
2014 // audio adapter: only config is turning it off presently
2015 if (stack.strAudioAdapter.isEmpty())
2016 config.hardwareMachine.audioAdapter.fEnabled = false;
2017
2018 /*
2019 *
2020 * step 2: scan the machine config for media attachments
2021 *
2022 */
2023
2024 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
2025 sit != config.storageMachine.llStorageControllers.end();
2026 ++sit)
2027 {
2028 settings::StorageController &sc = *sit;
2029
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)) throw 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 throw 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.raw());
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)) throw 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)) throw rc;
2106
2107 // return the new machine as an IMachine
2108 IMachine *p;
2109 rc = pNewMachine.queryInterfaceTo(&p);
2110 if (FAILED(rc)) throw rc;
2111 pReturnNewMachine = p;
2112
2113 // and register it
2114 rc = mVirtualBox->RegisterMachine(pNewMachine);
2115 if (FAILED(rc)) throw 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)) throw rc;
2121 stack.llMachinesRegistered.push_back(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 throw 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 throw 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 throw setError(E_ACCESSDENIED,
2213 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
2214 else if (vrc == VERR_S3_NOT_FOUND)
2215 throw setError(VBOX_E_FILE_ERROR,
2216 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
2217 else
2218 throw setError(VBOX_E_IPRT_ERROR,
2219 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2220 }
2221 }
2222
2223 /* Provide a OVF file (haven't to exist) so the import routine can
2224 * figure out where the disk images/manifest file are located. */
2225 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2226 /* Now check if there is an manifest file. This is optional. */
2227 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
2228 char *pszFilename = RTPathFilename(strManifestFile.c_str());
2229 if (!pTask->pProgress.isNull())
2230 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
2231
2232 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
2233 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
2234 if (RT_SUCCESS(vrc))
2235 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
2236 else if (RT_FAILURE(vrc))
2237 {
2238 if (vrc == VERR_S3_CANCELED)
2239 throw S_OK; /* todo: !!!!!!!!!!!!! */
2240 else if (vrc == VERR_S3_NOT_FOUND)
2241 vrc = VINF_SUCCESS; /* Not found is ok */
2242 else if (vrc == VERR_S3_ACCESS_DENIED)
2243 throw setError(E_ACCESSDENIED,
2244 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
2245 else
2246 throw setError(VBOX_E_IPRT_ERROR,
2247 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2248 }
2249
2250 /* Close the connection early */
2251 RTS3Destroy(hS3);
2252 hS3 = NIL_RTS3;
2253
2254 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightForXmlOperation);
2255
2256 ComObjPtr<Progress> progress;
2257 /* Import the whole temporary OVF & the disk images */
2258 LocationInfo li;
2259 li.strPath = strTmpOvf;
2260 rc = importImpl(li, progress);
2261 if (FAILED(rc)) throw rc;
2262
2263 /* Unlock the appliance for the fs import thread */
2264 appLock.release();
2265 /* Wait until the import is done, but report the progress back to the
2266 caller */
2267 ComPtr<IProgress> progressInt(progress);
2268 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2269
2270 /* Again lock the appliance for the next steps */
2271 appLock.acquire();
2272 }
2273 catch(HRESULT aRC)
2274 {
2275 rc = aRC;
2276 }
2277 /* Cleanup */
2278 RTS3Destroy(hS3);
2279 /* Delete all files which where temporary created */
2280 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2281 {
2282 const char *pszFilePath = (*it1).first.c_str();
2283 if (RTPathExists(pszFilePath))
2284 {
2285 vrc = RTFileDelete(pszFilePath);
2286 if (RT_FAILURE(vrc))
2287 rc = setError(VBOX_E_FILE_ERROR,
2288 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2289 }
2290 }
2291 /* Delete the temporary directory */
2292 if (RTPathExists(pszTmpDir))
2293 {
2294 vrc = RTDirRemove(pszTmpDir);
2295 if (RT_FAILURE(vrc))
2296 rc = setError(VBOX_E_FILE_ERROR,
2297 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2298 }
2299 if (pszTmpDir)
2300 RTStrFree(pszTmpDir);
2301
2302 LogFlowFunc(("rc=%Rhrc\n", rc));
2303 LogFlowFuncLeave();
2304
2305 return rc;
2306}
2307
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