VirtualBox

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

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

Main/OVF: fix 3.2.2 regression that OVFs with a VM description (annotation) could not be imported

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 96.9 KB
Line 
1/* $Id: ApplianceImplImport.cpp 30008 2010-06-03 11:50:39Z 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 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.raw(),
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 throw 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 throw 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)) throw 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)) throw 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 throw 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(xml::Error &x)
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 throw 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 throw 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 throw setError(E_ACCESSDENIED,
764 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);
765 else if (vrc == VERR_S3_NOT_FOUND)
766 throw setError(VBOX_E_FILE_ERROR,
767 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
768 else
769 throw setError(VBOX_E_IPRT_ERROR,
770 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
771 }
772
773 /* Close the connection early */
774 RTS3Destroy(hS3);
775 hS3 = NIL_RTS3;
776
777 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")), 1);
778
779 /* Prepare the temporary reading of the OVF */
780 ComObjPtr<Progress> progress;
781 LocationInfo li;
782 li.strPath = strTmpOvf;
783 /* Start the reading from the fs */
784 rc = readImpl(li, progress);
785 if (FAILED(rc)) throw rc;
786
787 /* Unlock the appliance for the reading thread */
788 appLock.release();
789 /* Wait until the reading is done, but report the progress back to the
790 caller */
791 ComPtr<IProgress> progressInt(progress);
792 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
793
794 /* Again lock the appliance for the next steps */
795 appLock.acquire();
796 }
797 catch(HRESULT aRC)
798 {
799 rc = aRC;
800 }
801 /* Cleanup */
802 RTS3Destroy(hS3);
803 /* Delete all files which where temporary created */
804 if (RTPathExists(strTmpOvf.c_str()))
805 {
806 vrc = RTFileDelete(strTmpOvf.c_str());
807 if (RT_FAILURE(vrc))
808 rc = setError(VBOX_E_FILE_ERROR,
809 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
810 }
811 /* Delete the temporary directory */
812 if (RTPathExists(pszTmpDir))
813 {
814 vrc = RTDirRemove(pszTmpDir);
815 if (RT_FAILURE(vrc))
816 rc = setError(VBOX_E_FILE_ERROR,
817 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
818 }
819 if (pszTmpDir)
820 RTStrFree(pszTmpDir);
821
822 LogFlowFunc(("rc=%Rhrc\n", rc));
823 LogFlowFuncLeave();
824
825 return rc;
826}
827
828/**
829 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
830 * Throws HRESULT values on errors!
831 *
832 * @param hdc in: the HardDiskController structure to attach to.
833 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
834 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
835 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
836 * @param lDevice out: the device number to attach to.
837 */
838void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
839 uint32_t ulAddressOnParent,
840 Bstr &controllerType,
841 int32_t &lControllerPort,
842 int32_t &lDevice)
843{
844 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n", hdc.system, hdc.fPrimary, ulAddressOnParent));
845
846 switch (hdc.system)
847 {
848 case ovf::HardDiskController::IDE:
849 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
850 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
851 // the device number can be either 0 or 1, to specify the master or the slave device,
852 // respectively. For the secondary IDE controller, the device number is always 1 because
853 // the master device is reserved for the CD-ROM drive.
854 controllerType = Bstr("IDE Controller");
855 switch (ulAddressOnParent)
856 {
857 case 0: // master
858 if (!hdc.fPrimary)
859 {
860 // secondary master
861 lControllerPort = (long)1;
862 lDevice = (long)0;
863 }
864 else // primary master
865 {
866 lControllerPort = (long)0;
867 lDevice = (long)0;
868 }
869 break;
870
871 case 1: // slave
872 if (!hdc.fPrimary)
873 {
874 // secondary slave
875 lControllerPort = (long)1;
876 lDevice = (long)1;
877 }
878 else // primary slave
879 {
880 lControllerPort = (long)0;
881 lDevice = (long)1;
882 }
883 break;
884
885 // used by older VBox exports
886 case 2: // interpret this as secondary master
887 lControllerPort = (long)1;
888 lDevice = (long)0;
889 break;
890
891 // used by older VBox exports
892 case 3: // interpret this as secondary slave
893 lControllerPort = (long)1;
894 lDevice = (long)1;
895 break;
896
897 default:
898 throw setError(VBOX_E_NOT_SUPPORTED,
899 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"), ulAddressOnParent);
900 break;
901 }
902 break;
903
904 case ovf::HardDiskController::SATA:
905 controllerType = Bstr("SATA Controller");
906 lControllerPort = (long)ulAddressOnParent;
907 lDevice = (long)0;
908 break;
909
910 case ovf::HardDiskController::SCSI:
911 controllerType = Bstr("SCSI Controller");
912 lControllerPort = (long)ulAddressOnParent;
913 lDevice = (long)0;
914 break;
915
916 default: break;
917 }
918
919 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
920}
921
922/**
923 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
924 * Appliance::taskThreadImportOrExport().
925 *
926 * This creates one or more new machines according to the VirtualSystemScription instances created by
927 * Appliance::Interpret().
928 *
929 * This is in a separate private method because it is used from two locations:
930 *
931 * 1) from the public Appliance::ImportMachines().
932 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
933 *
934 * @param aLocInfo
935 * @param aProgress
936 * @return
937 */
938HRESULT Appliance::importImpl(const LocationInfo &aLocInfo,
939 ComObjPtr<Progress> &aProgress)
940{
941 HRESULT rc = S_OK;
942
943 SetUpProgressMode mode;
944 m->strManifestFile.setNull();
945 if (aLocInfo.storageType == VFSType_File)
946 {
947 Utf8Str strMfFile = manifestFileName(aLocInfo.strPath);
948 if (RTPathExists(strMfFile.c_str()))
949 {
950 m->strManifestFile = strMfFile;
951 mode = ImportFileWithManifest;
952 }
953 else
954 mode = ImportFileNoManifest;
955 }
956 else
957 mode = ImportS3;
958
959 rc = setUpProgress(aProgress,
960 BstrFmt(tr("Importing appliance '%s'"), aLocInfo.strPath.c_str()),
961 mode);
962 if (FAILED(rc)) throw rc;
963
964 /* Initialize our worker task */
965 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, aLocInfo, aProgress));
966
967 rc = task->startThread();
968 if (FAILED(rc)) throw rc;
969
970 /* Don't destruct on success */
971 task.release();
972
973 return rc;
974}
975
976/**
977 * Checks if a manifest file exists in the given location and, if so, verifies
978 * that the relevant files (the OVF XML and the disks referenced by it, as
979 * represented by the VirtualSystemDescription instances contained in this appliance)
980 * match it. Requires a previous read() and interpret().
981 *
982 * @param locInfo
983 * @param reader
984 * @return
985 */
986HRESULT Appliance::manifestVerify(const LocationInfo &locInfo,
987 const ovf::OVFReader &reader,
988 ComObjPtr<Progress> &pProgress)
989{
990 HRESULT rc = S_OK;
991
992 if (!m->strManifestFile.isEmpty())
993 {
994 const char *pcszManifestFileOnly = RTPathFilename(m->strManifestFile.c_str());
995 pProgress->SetNextOperation(BstrFmt(tr("Verifying manifest file '%s'"), pcszManifestFileOnly),
996 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally
997
998 list<Utf8Str> filesList;
999 Utf8Str strSrcDir(locInfo.strPath);
1000 strSrcDir.stripFilename();
1001 // add every disks of every virtual system to an internal list
1002 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1003 for (it = m->virtualSystemDescriptions.begin();
1004 it != m->virtualSystemDescriptions.end();
1005 ++it)
1006 {
1007 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1008 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1009 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1010 for (itH = avsdeHDs.begin();
1011 itH != avsdeHDs.end();
1012 ++itH)
1013 {
1014 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1015 // find the disk from the OVF's disk list
1016 ovf::DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1017 const ovf::DiskImage &di = itDiskImage->second;
1018 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1019 filesList.push_back(strSrcFilePath);
1020 }
1021 }
1022
1023 // create the test list
1024 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST) * (filesList.size() + 1));
1025 pTestList[0].pszTestFile = (char*)locInfo.strPath.c_str();
1026 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1027 int vrc = VINF_SUCCESS;
1028 size_t i = 1;
1029 list<Utf8Str>::const_iterator it1;
1030 for (it1 = filesList.begin();
1031 it1 != filesList.end();
1032 ++it1, ++i)
1033 {
1034 char* pszDigest;
1035 vrc = RTSha1Digest((*it1).c_str(), &pszDigest, NULL, NULL);
1036 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1037 pTestList[i].pszTestDigest = pszDigest;
1038 }
1039
1040 // this call can take a very long time
1041 size_t cIndexOnError;
1042 vrc = RTManifestVerify(m->strManifestFile.c_str(),
1043 pTestList,
1044 filesList.size() + 1,
1045 &cIndexOnError);
1046
1047 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1048 rc = setError(VBOX_E_FILE_ERROR,
1049 tr("The SHA1 digest of '%s' does not match the one in '%s'"),
1050 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1051 pcszManifestFileOnly);
1052 else if (RT_FAILURE(vrc))
1053 rc = setError(VBOX_E_FILE_ERROR,
1054 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1055 pcszManifestFileOnly,
1056 vrc);
1057
1058 // clean up
1059 for (size_t j = 1;
1060 j < filesList.size();
1061 ++j)
1062 RTStrFree(pTestList[j].pszTestDigest);
1063 RTMemFree(pTestList);
1064 }
1065
1066 return rc;
1067}
1068
1069/**
1070 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1071 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1072 * VirtualSystemScription instances created by Appliance::Interpret().
1073 *
1074 * This runs in two contexts:
1075 *
1076 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1077 *
1078 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1079 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this.
1080 *
1081 * @param pTask
1082 * @return
1083 */
1084HRESULT Appliance::importFS(const LocationInfo &locInfo,
1085 ComObjPtr<Progress> &pProgress)
1086{
1087 LogFlowFuncEnter();
1088 LogFlowFunc(("Appliance %p\n", this));
1089
1090 AutoCaller autoCaller(this);
1091 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1092
1093 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1094
1095 if (!isApplianceIdle())
1096 return E_ACCESSDENIED;
1097
1098 Assert(!pProgress.isNull());
1099
1100 // Change the appliance state so we can safely leave the lock while doing time-consuming
1101 // disk imports; also the below method calls do all kinds of locking which conflicts with
1102 // the appliance object lock
1103 m->state = Data::ApplianceImporting;
1104 appLock.release();
1105
1106 HRESULT rc = S_OK;
1107
1108 const ovf::OVFReader &reader = *m->pReader;
1109 // this is safe to access because this thread only gets started
1110 // if pReader != NULL
1111
1112 // rollback for errors:
1113 ImportStack stack(locInfo, reader.m_mapDisks, pProgress);
1114
1115 try
1116 {
1117 // if a manifest file exists, verify the content; we then need all files which are referenced by the OVF & the OVF itself
1118 rc = manifestVerify(locInfo, reader, pProgress);
1119 if (FAILED(rc)) throw rc;
1120
1121 // create a session for the machine + disks we manipulate below
1122 rc = stack.pSession.createInprocObject(CLSID_Session);
1123 if (FAILED(rc)) throw rc;
1124
1125 list<ovf::VirtualSystem>::const_iterator it;
1126 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1127 /* Iterate through all virtual systems of that appliance */
1128 size_t i = 0;
1129 for (it = reader.m_llVirtualSystems.begin(),
1130 it1 = m->virtualSystemDescriptions.begin();
1131 it != reader.m_llVirtualSystems.end();
1132 ++it, ++it1, ++i)
1133 {
1134 const ovf::VirtualSystem &vsysThis = *it;
1135 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1136
1137 ComPtr<IMachine> pNewMachine;
1138
1139 // there are two ways in which we can create a vbox machine from OVF:
1140 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
1141 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
1142 // with all the machine config pretty-parsed;
1143 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
1144 // VirtualSystemDescriptionEntry and do import work
1145
1146 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
1147 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
1148
1149 // VM name
1150 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1151 if (vsdeName.size() < 1)
1152 throw setError(VBOX_E_FILE_ERROR,
1153 tr("Missing VM name"));
1154 stack.strNameVBox = vsdeName.front()->strVboxCurrent;
1155
1156 // guest OS type
1157 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1158 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1159 if (vsdeOS.size() < 1)
1160 throw setError(VBOX_E_FILE_ERROR,
1161 tr("Missing guest OS type"));
1162 stack.strOsTypeVBox = vsdeOS.front()->strVboxCurrent;
1163
1164 // CPU count
1165 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
1166 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1167 const Utf8Str &cpuVBox = vsdeCPU.front()->strVboxCurrent;
1168 stack.cCPUs = (uint32_t)RTStrToUInt64(cpuVBox.c_str());
1169 // We need HWVirt & IO-APIC if more than one CPU is requested
1170 if (stack.cCPUs > 1)
1171 {
1172 stack.fForceHWVirt = true;
1173 stack.fForceIOAPIC = true;
1174 }
1175
1176 // RAM
1177 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1178 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1179 const Utf8Str &memoryVBox = vsdeRAM.front()->strVboxCurrent;
1180 stack.ulMemorySizeMB = (uint32_t)RTStrToUInt64(memoryVBox.c_str());
1181
1182 // USB controller
1183#ifdef VBOX_WITH_USB
1184 /* USB Controller */
1185 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1186 // USB support is enabled if there's at least one such entry; to disable USB support,
1187 // the type of the USB item would have been changed to "ignore"
1188 stack.fUSBEnabled = vsdeUSBController.size() > 0;
1189#endif
1190 // audio adapter
1191 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1192 /* @todo: we support one audio adapter only */
1193 if (vsdeAudioAdapter.size() > 0)
1194 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVboxCurrent;
1195
1196 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
1197 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1198 if (vsdeDescription.size())
1199 stack.strDescription = vsdeDescription.front()->strVboxCurrent;
1200
1201 // import vbox:machine or OVF now
1202 if (vsdescThis->m->pConfig)
1203 // vbox:Machine config
1204 importVBoxMachine(vsdescThis, pNewMachine, stack);
1205 else
1206 // generic OVF config
1207 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
1208
1209 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
1210 }
1211 catch (HRESULT rc2)
1212 {
1213 rc = rc2;
1214 }
1215
1216 if (FAILED(rc))
1217 {
1218 // with _whatever_ error we've had, do a complete roll-back of
1219 // machines and disks we've created; unfortunately this is
1220 // not so trivially done...
1221
1222 HRESULT rc2;
1223 // detach all hard disks from all machines we created
1224 list<MyHardDiskAttachment>::iterator itM;
1225 for (itM = stack.llHardDiskAttachments.begin();
1226 itM != stack.llHardDiskAttachments.end();
1227 ++itM)
1228 {
1229 const MyHardDiskAttachment &mhda = *itM;
1230 Bstr bstrUuid(mhda.bstrUuid); // make a copy, Windows can't handle const Bstr
1231 rc2 = mVirtualBox->OpenSession(stack.pSession, bstrUuid);
1232 if (SUCCEEDED(rc2))
1233 {
1234 ComPtr<IMachine> sMachine;
1235 rc2 = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1236 if (SUCCEEDED(rc2))
1237 {
1238 rc2 = sMachine->DetachDevice(Bstr(mhda.controllerType), mhda.lControllerPort, mhda.lDevice);
1239 rc2 = sMachine->SaveSettings();
1240 }
1241 stack.pSession->Close();
1242 }
1243 }
1244
1245 // now clean up all hard disks we created
1246 list< ComPtr<IMedium> >::iterator itHD;
1247 for (itHD = stack.llHardDisksCreated.begin();
1248 itHD != stack.llHardDisksCreated.end();
1249 ++itHD)
1250 {
1251 ComPtr<IMedium> pDisk = *itHD;
1252 ComPtr<IProgress> pProgress2;
1253 rc2 = pDisk->DeleteStorage(pProgress2.asOutParam());
1254 rc2 = pProgress2->WaitForCompletion(-1);
1255 }
1256
1257 // finally, deregister and remove all machines
1258 list<Bstr>::iterator itID;
1259 for (itID = stack.llMachinesRegistered.begin();
1260 itID != stack.llMachinesRegistered.end();
1261 ++itID)
1262 {
1263 Bstr bstrGuid = *itID; // make a copy, Windows can't handle const Bstr
1264 ComPtr<IMachine> failedMachine;
1265 rc2 = mVirtualBox->UnregisterMachine(bstrGuid, failedMachine.asOutParam());
1266 if (SUCCEEDED(rc2))
1267 rc2 = failedMachine->DeleteSettings();
1268 }
1269 }
1270
1271 // restore the appliance state
1272 appLock.acquire();
1273 m->state = Data::ApplianceIdle;
1274 appLock.release();
1275
1276 LogFlowFunc(("rc=%Rhrc\n", rc));
1277 LogFlowFuncLeave();
1278
1279 return rc;
1280}
1281
1282/**
1283 * Imports one disk image. This is common code shared between
1284 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1285 * the OVF virtual systems;
1286 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1287 * tag.
1288 *
1289 * Both ways of describing machines use the OVF disk references section, so in both cases
1290 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1291 *
1292 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1293 * spec, even though this cannot really happen in the vbox:Machine case since such data
1294 * would never have been exported.
1295 *
1296 * This advances stack.pProgress by one operation with the disk's weight.
1297 *
1298 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1299 * @param ulSizeMB Size of the disk image (for progress reporting)
1300 * @param strTargetPath Where to create the target image.
1301 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1302 * @param stack
1303 */
1304void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1305 const Utf8Str &strTargetPath,
1306 ComPtr<IMedium> &pTargetHD,
1307 ImportStack &stack)
1308{
1309 ComPtr<IMedium> pSourceHD;
1310 bool fSourceHdNeedsClosing = false;
1311
1312 try
1313 {
1314 // destination file must not exist
1315 if ( strTargetPath.isEmpty()
1316 || RTPathExists(strTargetPath.c_str())
1317 )
1318 throw setError(VBOX_E_FILE_ERROR,
1319 tr("Destination file '%s' exists"),
1320 strTargetPath.c_str());
1321
1322 const Utf8Str &strSourceOVF = di.strHref;
1323
1324 // Make sure target directory exists
1325 HRESULT rc = VirtualBox::ensureFilePathExists(strTargetPath.c_str());
1326 if (FAILED(rc))
1327 throw rc;
1328
1329 // subprogress object for hard disk
1330 ComPtr<IProgress> pProgress2;
1331
1332 /* If strHref is empty we have to create a new file */
1333 if (strSourceOVF.isEmpty())
1334 {
1335 // which format to use?
1336 Bstr srcFormat = L"VDI";
1337 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1338 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1339 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1340 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1341 )
1342 srcFormat = L"VMDK";
1343 // create an empty hard disk
1344 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1345 if (FAILED(rc)) throw rc;
1346
1347 // create a dynamic growing disk image with the given capacity
1348 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1349 if (FAILED(rc)) throw rc;
1350
1351 // advance to the next operation
1352 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()),
1353 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1354 }
1355 else
1356 {
1357 // construct source file path
1358 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1359 // source path must exist
1360 if (!RTPathExists(strSrcFilePath.c_str()))
1361 throw setError(VBOX_E_FILE_ERROR,
1362 tr("Source virtual disk image file '%s' doesn't exist"),
1363 strSrcFilePath.c_str());
1364
1365 // Clone the disk image (this is necessary cause the id has
1366 // to be recreated for the case the same hard disk is
1367 // attached already from a previous import)
1368
1369 // First open the existing disk image
1370 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1371 AccessMode_ReadOnly,
1372 false,
1373 NULL,
1374 false,
1375 NULL,
1376 pSourceHD.asOutParam());
1377 if (FAILED(rc)) throw rc;
1378 fSourceHdNeedsClosing = true;
1379
1380 /* We need the format description of the source disk image */
1381 Bstr srcFormat;
1382 rc = pSourceHD->COMGETTER(Format)(srcFormat.asOutParam());
1383 if (FAILED(rc)) throw rc;
1384 /* Create a new hard disk interface for the destination disk image */
1385 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1386 if (FAILED(rc)) throw rc;
1387 /* Clone the source disk image */
1388 rc = pSourceHD->CloneTo(pTargetHD, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1389 if (FAILED(rc)) throw rc;
1390
1391 /* Advance to the next operation */
1392 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1393 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1394 }
1395
1396 // now wait for the background disk operation to complete; this throws HRESULTs on error
1397 waitForAsyncProgress(stack.pProgress, pProgress2);
1398
1399 if (fSourceHdNeedsClosing)
1400 {
1401 rc = pSourceHD->Close();
1402 if (FAILED(rc)) throw rc;
1403 fSourceHdNeedsClosing = false;
1404 }
1405
1406 stack.llHardDisksCreated.push_back(pTargetHD);
1407 }
1408 catch (...)
1409 {
1410 if (fSourceHdNeedsClosing)
1411 pSourceHD->Close();
1412
1413 throw;
1414 }
1415}
1416
1417/**
1418 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1419 * into VirtualBox by creating an IMachine instance, which is returned.
1420 *
1421 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1422 * up any leftovers from this function. For this, the given ImportStack instance has received information
1423 * about what needs cleaning up (to support rollback).
1424 *
1425 * @param vsysThis OVF virtual system (machine) to import.
1426 * @param vsdescThis Matching virtual system description (machine) to import.
1427 * @param pNewMachine out: Newly created machine.
1428 * @param stack Cleanup stack for when this throws.
1429 */
1430void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1431 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1432 ComPtr<IMachine> &pNewMachine,
1433 ImportStack &stack)
1434{
1435 HRESULT rc;
1436
1437 // Get the instance of IGuestOSType which matches our string guest OS type so we
1438 // can use recommended defaults for the new machine where OVF doesen't provice any
1439 ComPtr<IGuestOSType> osType;
1440 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox), osType.asOutParam());
1441 if (FAILED(rc)) throw rc;
1442
1443 /* Create the machine */
1444 rc = mVirtualBox->CreateMachine(Bstr(stack.strNameVBox),
1445 Bstr(stack.strOsTypeVBox),
1446 NULL,
1447 NULL,
1448 FALSE,
1449 pNewMachine.asOutParam());
1450 if (FAILED(rc)) throw rc;
1451
1452 // set the description
1453 if (!stack.strDescription.isEmpty())
1454 {
1455 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.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 /* Hard disk controller SAS */
1717 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
1718 if (vsdeHDCSAS.size() > 1)
1719 throw setError(VBOX_E_FILE_ERROR,
1720 tr("Too many SAS controllers in OVF; import facility only supports one"));
1721 if (vsdeHDCSAS.size() > 0)
1722 {
1723 ComPtr<IStorageController> pController;
1724 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller"), StorageBus_SAS, pController.asOutParam());
1725 if (FAILED(rc)) throw rc;
1726 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
1727 if (FAILED(rc)) throw rc;
1728 }
1729
1730 /* Now its time to register the machine before we add any hard disks */
1731 rc = mVirtualBox->RegisterMachine(pNewMachine);
1732 if (FAILED(rc)) throw rc;
1733
1734 // store new machine for roll-back in case of errors
1735 Bstr bstrNewMachineId;
1736 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
1737 if (FAILED(rc)) throw rc;
1738 stack.llMachinesRegistered.push_back(bstrNewMachineId);
1739
1740 // Add floppies and CD-ROMs to the appropriate controllers.
1741 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1742 if (vsdeFloppy.size() > 1)
1743 throw setError(VBOX_E_FILE_ERROR,
1744 tr("Too many floppy controllers in OVF; import facility only supports one"));
1745 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1746 if ( (vsdeFloppy.size() > 0)
1747 || (vsdeCDROM.size() > 0)
1748 )
1749 {
1750 // If there's an error here we need to close the session, so
1751 // we need another try/catch block.
1752
1753 try
1754 {
1755 // to attach things we need to open a session for the new machine
1756 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1757 if (FAILED(rc)) throw rc;
1758 stack.fSessionOpen = true;
1759
1760 ComPtr<IMachine> sMachine;
1761 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1762 if (FAILED(rc)) throw rc;
1763
1764 // floppy first
1765 if (vsdeFloppy.size() == 1)
1766 {
1767 ComPtr<IStorageController> pController;
1768 rc = sMachine->AddStorageController(Bstr("Floppy Controller"), StorageBus_Floppy, pController.asOutParam());
1769 if (FAILED(rc)) throw rc;
1770
1771 Bstr bstrName;
1772 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1773 if (FAILED(rc)) throw rc;
1774
1775 // this is for rollback later
1776 MyHardDiskAttachment mhda;
1777 mhda.bstrUuid = bstrNewMachineId;
1778 mhda.pMachine = pNewMachine;
1779 mhda.controllerType = bstrName;
1780 mhda.lControllerPort = 0;
1781 mhda.lDevice = 0;
1782
1783 Log(("Attaching floppy\n"));
1784
1785 rc = sMachine->AttachDevice(mhda.controllerType,
1786 mhda.lControllerPort,
1787 mhda.lDevice,
1788 DeviceType_Floppy,
1789 NULL);
1790 if (FAILED(rc)) throw rc;
1791
1792 stack.llHardDiskAttachments.push_back(mhda);
1793 }
1794
1795 // CD-ROMs next
1796 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
1797 jt != vsdeCDROM.end();
1798 ++jt)
1799 {
1800 // for now always attach to secondary master on IDE controller;
1801 // there seems to be no useful information in OVF where else to
1802 // attach it (@todo test with latest versions of OVF software)
1803
1804 // find the IDE controller
1805 const ovf::HardDiskController *pController = NULL;
1806 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
1807 kt != vsysThis.mapControllers.end();
1808 ++kt)
1809 {
1810 if (kt->second.system == ovf::HardDiskController::IDE)
1811 {
1812 pController = &kt->second;
1813 break;
1814 }
1815 }
1816
1817 if (!pController)
1818 throw setError(VBOX_E_FILE_ERROR,
1819 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
1820
1821 // this is for rollback later
1822 MyHardDiskAttachment mhda;
1823 mhda.bstrUuid = bstrNewMachineId;
1824 mhda.pMachine = pNewMachine;
1825
1826 convertDiskAttachmentValues(*pController,
1827 2, // interpreted as secondary master
1828 mhda.controllerType, // Bstr
1829 mhda.lControllerPort,
1830 mhda.lDevice);
1831
1832 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
1833
1834 rc = sMachine->AttachDevice(mhda.controllerType,
1835 mhda.lControllerPort,
1836 mhda.lDevice,
1837 DeviceType_DVD,
1838 NULL);
1839 if (FAILED(rc)) throw rc;
1840
1841 stack.llHardDiskAttachments.push_back(mhda);
1842 } // end for (itHD = avsdeHDs.begin();
1843
1844 rc = sMachine->SaveSettings();
1845 if (FAILED(rc)) throw rc;
1846
1847 // only now that we're done with all disks, close the session
1848 rc = stack.pSession->Close();
1849 if (FAILED(rc)) throw rc;
1850 stack.fSessionOpen = false;
1851 }
1852 catch(HRESULT /* aRC */)
1853 {
1854 if (stack.fSessionOpen)
1855 stack.pSession->Close();
1856
1857 throw;
1858 }
1859 }
1860
1861 // create the hard disks & connect them to the appropriate controllers
1862 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1863 if (avsdeHDs.size() > 0)
1864 {
1865 // If there's an error here we need to close the session, so
1866 // we need another try/catch block.
1867 try
1868 {
1869 // to attach things we need to open a session for the new machine
1870 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1871 if (FAILED(rc)) throw rc;
1872 stack.fSessionOpen = true;
1873
1874 /* Iterate over all given disk images */
1875 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1876 for (itHD = avsdeHDs.begin();
1877 itHD != avsdeHDs.end();
1878 ++itHD)
1879 {
1880 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1881
1882 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1883 // in the virtual system's disks map under that ID and also in the global images map
1884 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1885 // and find the disk from the OVF's disk list
1886 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
1887 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
1888 || (itDiskImage == stack.mapDisks.end())
1889 )
1890 throw setError(E_FAIL,
1891 tr("Internal inconsistency looking up disk image '%s'"),
1892 vsdeHD->strRef.c_str());
1893
1894 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
1895 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
1896
1897 ComPtr<IMedium> pTargetHD;
1898 importOneDiskImage(ovfDiskImage,
1899 vsdeHD->strVboxCurrent,
1900 pTargetHD,
1901 stack);
1902
1903 // now use the new uuid to attach the disk image to our new machine
1904 ComPtr<IMachine> sMachine;
1905 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1906 if (FAILED(rc)) throw rc;
1907 Bstr hdId;
1908 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
1909 if (FAILED(rc)) throw rc;
1910
1911 // find the hard disk controller to which we should attach
1912 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
1913
1914 // this is for rollback later
1915 MyHardDiskAttachment mhda;
1916 mhda.bstrUuid = bstrNewMachineId;
1917 mhda.pMachine = pNewMachine;
1918
1919 convertDiskAttachmentValues(hdc,
1920 ovfVdisk.ulAddressOnParent,
1921 mhda.controllerType, // Bstr
1922 mhda.lControllerPort,
1923 mhda.lDevice);
1924
1925 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVboxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
1926
1927 rc = sMachine->AttachDevice(mhda.controllerType, // wstring name
1928 mhda.lControllerPort, // long controllerPort
1929 mhda.lDevice, // long device
1930 DeviceType_HardDisk, // DeviceType_T type
1931 hdId); // uuid id
1932 if (FAILED(rc)) throw rc;
1933
1934 stack.llHardDiskAttachments.push_back(mhda);
1935
1936 rc = sMachine->SaveSettings();
1937 if (FAILED(rc)) throw rc;
1938 } // end for (itHD = avsdeHDs.begin();
1939
1940 // only now that we're done with all disks, close the session
1941 rc = stack.pSession->Close();
1942 if (FAILED(rc)) throw rc;
1943 stack.fSessionOpen = false;
1944 }
1945 catch(HRESULT /* aRC */)
1946 {
1947 if (stack.fSessionOpen)
1948 stack.pSession->Close();
1949
1950 throw;
1951 }
1952 }
1953}
1954
1955/**
1956 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
1957 * structure) into VirtualBox by creating an IMachine instance, which is returned.
1958 *
1959 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1960 * up any leftovers from this function. For this, the given ImportStack instance has received information
1961 * about what needs cleaning up (to support rollback).
1962 *
1963 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
1964 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
1965 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
1966 * will most probably work, reimporting them into the same host will cause conflicts, so we always
1967 * generate new ones on import. This involves the following:
1968 *
1969 * 1) Scan the machine config for disk attachments.
1970 *
1971 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
1972 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
1973 * replace the old UUID with the new one.
1974 *
1975 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
1976 * caller has modified them using setFinalValues().
1977 *
1978 * 4) Create the VirtualBox machine with the modfified machine config.
1979 *
1980 * @param config
1981 * @param pNewMachine
1982 * @param stack
1983 */
1984void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
1985 ComPtr<IMachine> &pReturnNewMachine,
1986 ImportStack &stack)
1987{
1988 Assert(vsdescThis->m->pConfig);
1989
1990 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
1991
1992 Utf8Str strDefaultHardDiskFolder;
1993 HRESULT rc = getDefaultHardDiskFolder(strDefaultHardDiskFolder);
1994 if (FAILED(rc)) throw rc;
1995
1996 /*
1997 *
1998 * step 1): modify machine config according to OVF config, in case the user
1999 * has modified them using setFinalValues()
2000 *
2001 */
2002
2003 config.strDescription = stack.strDescription;
2004
2005 config.hardwareMachine.cCPUs = stack.cCPUs;
2006 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
2007 if (stack.fForceIOAPIC)
2008 config.hardwareMachine.fHardwareVirt = true;
2009 if (stack.fForceIOAPIC)
2010 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
2011
2012/*
2013 <const name="HardDiskControllerIDE" value="14" />
2014 <const name="HardDiskControllerSATA" value="15" />
2015 <const name="HardDiskControllerSCSI" value="16" />
2016 <const name="HardDiskControllerSAS" value="17" />
2017 <const name="HardDiskImage" value="18" />
2018 <const name="Floppy" value="19" />
2019 <const name="CDROM" value="20" />
2020 <const name="NetworkAdapter" value="21" />
2021*/
2022
2023#ifdef VBOX_WITH_USB
2024 // disable USB if user disabled USB
2025 config.hardwareMachine.usbController.fEnabled = stack.fUSBEnabled;
2026#endif
2027
2028 // audio adapter: only config is turning it off presently
2029 if (stack.strAudioAdapter.isEmpty())
2030 config.hardwareMachine.audioAdapter.fEnabled = false;
2031
2032 /*
2033 *
2034 * step 2: scan the machine config for media attachments
2035 *
2036 */
2037
2038 // for each storage controller...
2039 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
2040 sit != config.storageMachine.llStorageControllers.end();
2041 ++sit)
2042 {
2043 settings::StorageController &sc = *sit;
2044
2045 // find the OVF virtual system description entry for this storage controller
2046 switch (sc.storageBus)
2047 {
2048 case StorageBus_SATA:
2049 break;
2050
2051 case StorageBus_SCSI:
2052 break;
2053
2054 case StorageBus_IDE:
2055 break;
2056
2057 case StorageBus_SAS:
2058 break;
2059 }
2060
2061 // for each medium attachment to this controller...
2062 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
2063 dit != sc.llAttachedDevices.end();
2064 ++dit)
2065 {
2066 settings::AttachedDevice &d = *dit;
2067
2068 if (d.uuid.isEmpty())
2069 // empty DVD and floppy media
2070 continue;
2071
2072 // convert the Guid to string
2073 Utf8Str strUuid = d.uuid.toString();
2074
2075 // there must be an image in the OVF disk structs with the same UUID
2076 bool fFound = false;
2077 for (ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2078 oit != stack.mapDisks.end();
2079 ++oit)
2080 {
2081 const ovf::DiskImage &di = oit->second;
2082
2083 if (di.uuidVbox == strUuid)
2084 {
2085 Utf8Str strTargetPath(strDefaultHardDiskFolder);
2086 strTargetPath.append(RTPATH_DELIMITER);
2087 strTargetPath.append(di.strHref);
2088 searchUniqueDiskImageFilePath(strTargetPath);
2089
2090 /*
2091 *
2092 * step 3: import disk
2093 *
2094 */
2095 ComPtr<IMedium> pTargetHD;
2096 importOneDiskImage(di,
2097 strTargetPath,
2098 pTargetHD,
2099 stack);
2100
2101 // ... and replace the old UUID in the machine config with the one of
2102 // the imported disk that was just created
2103 Bstr hdId;
2104 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
2105 if (FAILED(rc)) throw rc;
2106
2107 d.uuid = hdId;
2108
2109 fFound = true;
2110 break;
2111 }
2112 }
2113
2114 // no disk with such a UUID found:
2115 if (!fFound)
2116 throw setError(E_FAIL,
2117 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s but the OVF describes no such image"),
2118 strUuid.raw());
2119 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
2120 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
2121
2122 /*
2123 *
2124 * step 4): create the machine and have it import the config
2125 *
2126 */
2127
2128 ComObjPtr<Machine> pNewMachine;
2129 rc = pNewMachine.createObject();
2130 if (FAILED(rc)) throw rc;
2131
2132 // this magic constructor fills the new machine object with the MachineConfig
2133 // instance that we created from the vbox:Machine
2134 rc = pNewMachine->init(mVirtualBox,
2135 stack.strNameVBox, // name from OVF preparations; can be suffixed to avoid duplicates, or changed by user
2136 config); // the whole machine config
2137 if (FAILED(rc)) throw rc;
2138
2139 // return the new machine as an IMachine
2140 IMachine *p;
2141 rc = pNewMachine.queryInterfaceTo(&p);
2142 if (FAILED(rc)) throw rc;
2143 pReturnNewMachine = p;
2144
2145 // and register it
2146 rc = mVirtualBox->RegisterMachine(pNewMachine);
2147 if (FAILED(rc)) throw rc;
2148
2149 // store new machine for roll-back in case of errors
2150 Bstr bstrNewMachineId;
2151 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2152 if (FAILED(rc)) throw rc;
2153 stack.llMachinesRegistered.push_back(bstrNewMachineId);
2154}
2155
2156/**
2157 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
2158 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
2159 * thread to import from temporary files (see Appliance::importFS()).
2160 * @param pTask
2161 * @return
2162 */
2163HRESULT Appliance::importS3(TaskOVF *pTask)
2164{
2165 LogFlowFuncEnter();
2166 LogFlowFunc(("Appliance %p\n", this));
2167
2168 AutoCaller autoCaller(this);
2169 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2170
2171 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
2172
2173 int vrc = VINF_SUCCESS;
2174 RTS3 hS3 = NIL_RTS3;
2175 char szOSTmpDir[RTPATH_MAX];
2176 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
2177 /* The template for the temporary directory created below */
2178 char *pszTmpDir;
2179 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
2180 list< pair<Utf8Str, ULONG> > filesList;
2181
2182 HRESULT rc = S_OK;
2183 try
2184 {
2185 /* Extract the bucket */
2186 Utf8Str tmpPath = pTask->locInfo.strPath;
2187 Utf8Str bucket;
2188 parseBucket(tmpPath, bucket);
2189
2190 /* We need a temporary directory which we can put the all disk images
2191 * in */
2192 vrc = RTDirCreateTemp(pszTmpDir);
2193 if (RT_FAILURE(vrc))
2194 throw setError(VBOX_E_FILE_ERROR,
2195 tr("Cannot create temporary directory '%s'"), pszTmpDir);
2196
2197 /* Add every disks of every virtual system to an internal list */
2198 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2199 for (it = m->virtualSystemDescriptions.begin();
2200 it != m->virtualSystemDescriptions.end();
2201 ++it)
2202 {
2203 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2204 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2205 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2206 for (itH = avsdeHDs.begin();
2207 itH != avsdeHDs.end();
2208 ++itH)
2209 {
2210 const Utf8Str &strTargetFile = (*itH)->strOvf;
2211 if (!strTargetFile.isEmpty())
2212 {
2213 /* The temporary name of the target disk file */
2214 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
2215 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
2216 }
2217 }
2218 }
2219
2220 /* Next we have to download the disk images */
2221 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2222 if (RT_FAILURE(vrc))
2223 throw setError(VBOX_E_IPRT_ERROR,
2224 tr("Cannot create S3 service handler"));
2225 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2226
2227 /* Download all files */
2228 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2229 {
2230 const pair<Utf8Str, ULONG> &s = (*it1);
2231 const Utf8Str &strSrcFile = s.first;
2232 /* Construct the source file name */
2233 char *pszFilename = RTPathFilename(strSrcFile.c_str());
2234 /* Advance to the next operation */
2235 if (!pTask->pProgress.isNull())
2236 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), s.second);
2237
2238 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
2239 if (RT_FAILURE(vrc))
2240 {
2241 if (vrc == VERR_S3_CANCELED)
2242 throw S_OK; /* todo: !!!!!!!!!!!!! */
2243 else if (vrc == VERR_S3_ACCESS_DENIED)
2244 throw setError(E_ACCESSDENIED,
2245 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);
2246 else if (vrc == VERR_S3_NOT_FOUND)
2247 throw setError(VBOX_E_FILE_ERROR,
2248 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
2249 else
2250 throw setError(VBOX_E_IPRT_ERROR,
2251 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2252 }
2253 }
2254
2255 /* Provide a OVF file (haven't to exist) so the import routine can
2256 * figure out where the disk images/manifest file are located. */
2257 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2258 /* Now check if there is an manifest file. This is optional. */
2259 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
2260 char *pszFilename = RTPathFilename(strManifestFile.c_str());
2261 if (!pTask->pProgress.isNull())
2262 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
2263
2264 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
2265 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
2266 if (RT_SUCCESS(vrc))
2267 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
2268 else if (RT_FAILURE(vrc))
2269 {
2270 if (vrc == VERR_S3_CANCELED)
2271 throw S_OK; /* todo: !!!!!!!!!!!!! */
2272 else if (vrc == VERR_S3_NOT_FOUND)
2273 vrc = VINF_SUCCESS; /* Not found is ok */
2274 else if (vrc == VERR_S3_ACCESS_DENIED)
2275 throw setError(E_ACCESSDENIED,
2276 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);
2277 else
2278 throw setError(VBOX_E_IPRT_ERROR,
2279 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2280 }
2281
2282 /* Close the connection early */
2283 RTS3Destroy(hS3);
2284 hS3 = NIL_RTS3;
2285
2286 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightForXmlOperation);
2287
2288 ComObjPtr<Progress> progress;
2289 /* Import the whole temporary OVF & the disk images */
2290 LocationInfo li;
2291 li.strPath = strTmpOvf;
2292 rc = importImpl(li, progress);
2293 if (FAILED(rc)) throw rc;
2294
2295 /* Unlock the appliance for the fs import thread */
2296 appLock.release();
2297 /* Wait until the import is done, but report the progress back to the
2298 caller */
2299 ComPtr<IProgress> progressInt(progress);
2300 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2301
2302 /* Again lock the appliance for the next steps */
2303 appLock.acquire();
2304 }
2305 catch(HRESULT aRC)
2306 {
2307 rc = aRC;
2308 }
2309 /* Cleanup */
2310 RTS3Destroy(hS3);
2311 /* Delete all files which where temporary created */
2312 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2313 {
2314 const char *pszFilePath = (*it1).first.c_str();
2315 if (RTPathExists(pszFilePath))
2316 {
2317 vrc = RTFileDelete(pszFilePath);
2318 if (RT_FAILURE(vrc))
2319 rc = setError(VBOX_E_FILE_ERROR,
2320 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2321 }
2322 }
2323 /* Delete the temporary directory */
2324 if (RTPathExists(pszTmpDir))
2325 {
2326 vrc = RTDirRemove(pszTmpDir);
2327 if (RT_FAILURE(vrc))
2328 rc = setError(VBOX_E_FILE_ERROR,
2329 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2330 }
2331 if (pszTmpDir)
2332 RTStrFree(pszTmpDir);
2333
2334 LogFlowFunc(("rc=%Rhrc\n", rc));
2335 LogFlowFuncLeave();
2336
2337 return rc;
2338}
2339
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use