VirtualBox

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

Last change on this file since 29893 was 29875, checked in by vboxsync, 15 years ago

OVF: have the progress bar notify the user when we're dealing with manifest files so that at least the user won't think the system is stuck importing/exporting image files

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 94.9 KB
Line 
1/* $Id: ApplianceImplImport.cpp 29875 2010-05-28 18:15: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);
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 * Used by Appliance::importMachineGeneric() to store
973 * input parameters and rollback information.
974 */
975struct Appliance::ImportStack
976{
977 // input pointers
978 const LocationInfo &locInfo; // ptr to location info from Appliance::importFS()
979 Utf8Str strSourceDir; // directory where source files reside
980 const ovf::DiskImagesMap &mapDisks; // ptr to disks map in OVF
981 ComObjPtr<Progress> &pProgress; // progress object passed into Appliance::importFS()
982
983 // session (not initially created)
984 ComPtr<ISession> pSession; // session opened in Appliance::importFS() for machine manipulation
985 bool fSessionOpen; // true if the pSession is currently open and needs closing
986
987 // a list of images that we created/imported; this is initially empty
988 // and will be cleaned up on errors
989 list<MyHardDiskAttachment> llHardDiskAttachments; // disks that were attached
990 list< ComPtr<IMedium> > llHardDisksCreated; // media that were created
991 list<Bstr> llMachinesRegistered; // machines that were registered; list of string UUIDs
992
993 ImportStack(const LocationInfo &aLocInfo,
994 const ovf::DiskImagesMap &aMapDisks,
995 ComObjPtr<Progress> &aProgress)
996 : locInfo(aLocInfo),
997 mapDisks(aMapDisks),
998 pProgress(aProgress),
999 fSessionOpen(false)
1000 {
1001 // disk images have to be on the same place as the OVF file. So
1002 // strip the filename out of the full file path
1003 strSourceDir = aLocInfo.strPath;
1004 strSourceDir.stripFilename();
1005 }
1006};
1007
1008/**
1009 * Checks if a manifest file exists in the given location and, if so, verifies
1010 * that the relevant files (the OVF XML and the disks referenced by it, as
1011 * represented by the VirtualSystemDescription instances contained in this appliance)
1012 * match it. Requires a previous read() and interpret().
1013 *
1014 * @param locInfo
1015 * @param reader
1016 * @return
1017 */
1018HRESULT Appliance::manifestVerify(const LocationInfo &locInfo,
1019 const ovf::OVFReader &reader,
1020 ComObjPtr<Progress> &pProgress)
1021{
1022 HRESULT rc = S_OK;
1023
1024 if (!m->strManifestFile.isEmpty())
1025 {
1026 const char *pcszManifestFileOnly = RTPathFilename(m->strManifestFile.c_str());
1027 pProgress->SetNextOperation(BstrFmt(tr("Verifying manifest file '%s'"), pcszManifestFileOnly),
1028 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally
1029
1030 list<Utf8Str> filesList;
1031 Utf8Str strSrcDir(locInfo.strPath);
1032 strSrcDir.stripFilename();
1033 // add every disks of every virtual system to an internal list
1034 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1035 for (it = m->virtualSystemDescriptions.begin();
1036 it != m->virtualSystemDescriptions.end();
1037 ++it)
1038 {
1039 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1040 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1041 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1042 for (itH = avsdeHDs.begin();
1043 itH != avsdeHDs.end();
1044 ++itH)
1045 {
1046 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1047 // find the disk from the OVF's disk list
1048 ovf::DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1049 const ovf::DiskImage &di = itDiskImage->second;
1050 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1051 filesList.push_back(strSrcFilePath);
1052 }
1053 }
1054
1055 // create the test list
1056 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST) * (filesList.size() + 1));
1057 pTestList[0].pszTestFile = (char*)locInfo.strPath.c_str();
1058 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1059 int vrc = VINF_SUCCESS;
1060 size_t i = 1;
1061 list<Utf8Str>::const_iterator it1;
1062 for (it1 = filesList.begin();
1063 it1 != filesList.end();
1064 ++it1, ++i)
1065 {
1066 char* pszDigest;
1067 vrc = RTSha1Digest((*it1).c_str(), &pszDigest);
1068 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1069 pTestList[i].pszTestDigest = pszDigest;
1070 }
1071
1072 // this call can take a very long time
1073 size_t cIndexOnError;
1074 vrc = RTManifestVerify(m->strManifestFile.c_str(),
1075 pTestList,
1076 filesList.size() + 1,
1077 &cIndexOnError);
1078
1079 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1080 rc = setError(VBOX_E_FILE_ERROR,
1081 tr("The SHA1 digest of '%s' does not match the one in '%s'"),
1082 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1083 pcszManifestFileOnly);
1084 else if (RT_FAILURE(vrc))
1085 rc = setError(VBOX_E_FILE_ERROR,
1086 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1087 pcszManifestFileOnly,
1088 vrc);
1089
1090 // clean up
1091 for (size_t j = 1;
1092 j < filesList.size();
1093 ++j)
1094 RTStrFree(pTestList[j].pszTestDigest);
1095 RTMemFree(pTestList);
1096 }
1097
1098 return rc;
1099}
1100
1101/**
1102 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1103 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1104 * VirtualSystemScription instances created by Appliance::Interpret().
1105 *
1106 * This runs in two contexts:
1107 *
1108 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1109 *
1110 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1111 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this.
1112 *
1113 * @param pTask
1114 * @return
1115 */
1116HRESULT Appliance::importFS(const LocationInfo &locInfo,
1117 ComObjPtr<Progress> &pProgress)
1118{
1119 LogFlowFuncEnter();
1120 LogFlowFunc(("Appliance %p\n", this));
1121
1122 AutoCaller autoCaller(this);
1123 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1124
1125 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1126
1127 if (!isApplianceIdle())
1128 return E_ACCESSDENIED;
1129
1130 Assert(!pProgress.isNull());
1131
1132 // Change the appliance state so we can safely leave the lock while doing time-consuming
1133 // disk imports; also the below method calls do all kinds of locking which conflicts with
1134 // the appliance object lock
1135 m->state = Data::ApplianceImporting;
1136 appLock.release();
1137
1138 HRESULT rc = S_OK;
1139
1140 const ovf::OVFReader &reader = *m->pReader;
1141 // this is safe to access because this thread only gets started
1142 // if pReader != NULL
1143
1144 // rollback for errors:
1145 ImportStack stack(locInfo, reader.m_mapDisks, pProgress);
1146
1147 try
1148 {
1149 // if a manifest file exists, verify the content; we then need all files which are referenced by the OVF & the OVF itself
1150 rc = manifestVerify(locInfo, reader, pProgress);
1151 if (FAILED(rc)) throw rc;
1152
1153 // create a session for the machine + disks we manipulate below
1154 rc = stack.pSession.createInprocObject(CLSID_Session);
1155 if (FAILED(rc)) throw rc;
1156
1157 list<ovf::VirtualSystem>::const_iterator it;
1158 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1159 /* Iterate through all virtual systems of that appliance */
1160 size_t i = 0;
1161 for (it = reader.m_llVirtualSystems.begin(),
1162 it1 = m->virtualSystemDescriptions.begin();
1163 it != reader.m_llVirtualSystems.end();
1164 ++it, ++it1, ++i)
1165 {
1166 const ovf::VirtualSystem &vsysThis = *it;
1167 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1168
1169 ComPtr<IMachine> pNewMachine;
1170
1171 // there are two ways in which we can create a vbox machine from OVF:
1172 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
1173 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
1174 // with all the machine config pretty-parsed;
1175 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
1176 // VirtualSystemDescriptionEntry and do import work
1177
1178 // @todo r=dj make this selection configurable at run-time, and from the GUI as well
1179
1180 if (vsdescThis->m->pConfig)
1181 importVBoxMachine(vsdescThis, pNewMachine, stack);
1182 else
1183 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
1184
1185 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
1186 }
1187 catch (HRESULT rc2)
1188 {
1189 rc = rc2;
1190 }
1191
1192 if (FAILED(rc))
1193 {
1194 // with _whatever_ error we've had, do a complete roll-back of
1195 // machines and disks we've created; unfortunately this is
1196 // not so trivially done...
1197
1198 HRESULT rc2;
1199 // detach all hard disks from all machines we created
1200 list<MyHardDiskAttachment>::iterator itM;
1201 for (itM = stack.llHardDiskAttachments.begin();
1202 itM != stack.llHardDiskAttachments.end();
1203 ++itM)
1204 {
1205 const MyHardDiskAttachment &mhda = *itM;
1206 Bstr bstrUuid(mhda.bstrUuid); // make a copy, Windows can't handle const Bstr
1207 rc2 = mVirtualBox->OpenSession(stack.pSession, bstrUuid);
1208 if (SUCCEEDED(rc2))
1209 {
1210 ComPtr<IMachine> sMachine;
1211 rc2 = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1212 if (SUCCEEDED(rc2))
1213 {
1214 rc2 = sMachine->DetachDevice(Bstr(mhda.controllerType), mhda.lControllerPort, mhda.lDevice);
1215 rc2 = sMachine->SaveSettings();
1216 }
1217 stack.pSession->Close();
1218 }
1219 }
1220
1221 // now clean up all hard disks we created
1222 list< ComPtr<IMedium> >::iterator itHD;
1223 for (itHD = stack.llHardDisksCreated.begin();
1224 itHD != stack.llHardDisksCreated.end();
1225 ++itHD)
1226 {
1227 ComPtr<IMedium> pDisk = *itHD;
1228 ComPtr<IProgress> pProgress2;
1229 rc2 = pDisk->DeleteStorage(pProgress2.asOutParam());
1230 rc2 = pProgress2->WaitForCompletion(-1);
1231 }
1232
1233 // finally, deregister and remove all machines
1234 list<Bstr>::iterator itID;
1235 for (itID = stack.llMachinesRegistered.begin();
1236 itID != stack.llMachinesRegistered.end();
1237 ++itID)
1238 {
1239 Bstr bstrGuid = *itID; // make a copy, Windows can't handle const Bstr
1240 ComPtr<IMachine> failedMachine;
1241 rc2 = mVirtualBox->UnregisterMachine(bstrGuid, failedMachine.asOutParam());
1242 if (SUCCEEDED(rc2))
1243 rc2 = failedMachine->DeleteSettings();
1244 }
1245 }
1246
1247 // restore the appliance state
1248 appLock.acquire();
1249 m->state = Data::ApplianceIdle;
1250
1251 LogFlowFunc(("rc=%Rhrc\n", rc));
1252 LogFlowFuncLeave();
1253
1254 return rc;
1255}
1256
1257/**
1258 * Imports one disk image. This is common code shared between
1259 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1260 * the OVF virtual systems;
1261 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1262 * tag.
1263 *
1264 * Both ways of describing machines use the OVF disk references section, so in both cases
1265 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1266 *
1267 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1268 * spec, even though this cannot really happen in the vbox:Machine case since such data
1269 * would never have been exported.
1270 *
1271 * This advances stack.pProgress by one operation with the disk's weight.
1272 *
1273 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1274 * @param ulSizeMB Size of the disk image (for progress reporting)
1275 * @param strTargetPath Where to create the target image.
1276 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1277 * @param stack
1278 */
1279void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1280 const Utf8Str &strTargetPath,
1281 ComPtr<IMedium> &pTargetHD,
1282 ImportStack &stack)
1283{
1284 ComPtr<IMedium> pSourceHD;
1285 bool fSourceHdNeedsClosing = false;
1286
1287 try
1288 {
1289 // destination file must not exist
1290 if ( strTargetPath.isEmpty()
1291 || RTPathExists(strTargetPath.c_str())
1292 )
1293 /* This isn't allowed */
1294 throw setError(VBOX_E_FILE_ERROR,
1295 tr("Destination file '%s' exists"),
1296 strTargetPath.c_str());
1297
1298 const Utf8Str &strSourceOVF = di.strHref;
1299
1300 // Make sure target directory exists
1301 HRESULT rc = VirtualBox::ensureFilePathExists(strTargetPath.c_str());
1302 if (FAILED(rc))
1303 throw rc;
1304
1305 // subprogress object for hard disk
1306 ComPtr<IProgress> pProgress2;
1307
1308 /* If strHref is empty we have to create a new file */
1309 if (strSourceOVF.isEmpty())
1310 {
1311 // which format to use?
1312 Bstr srcFormat = L"VDI";
1313 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1314 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1315 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1316 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1317 )
1318 srcFormat = L"VMDK";
1319 // create an empty hard disk
1320 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1321 if (FAILED(rc)) throw rc;
1322
1323 // create a dynamic growing disk image with the given capacity
1324 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1325 if (FAILED(rc)) throw rc;
1326
1327 // advance to the next operation
1328 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()),
1329 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1330 }
1331 else
1332 {
1333 // construct source file path
1334 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1335 // source path must exist
1336 if (!RTPathExists(strSrcFilePath.c_str()))
1337 throw setError(VBOX_E_FILE_ERROR,
1338 tr("Source virtual disk image file '%s' doesn't exist"),
1339 strSrcFilePath.c_str());
1340
1341 // Clone the disk image (this is necessary cause the id has
1342 // to be recreated for the case the same hard disk is
1343 // attached already from a previous import)
1344
1345 // First open the existing disk image
1346 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1347 AccessMode_ReadOnly,
1348 false,
1349 NULL,
1350 false,
1351 NULL,
1352 pSourceHD.asOutParam());
1353 if (FAILED(rc)) throw rc;
1354 fSourceHdNeedsClosing = true;
1355
1356 /* We need the format description of the source disk image */
1357 Bstr srcFormat;
1358 rc = pSourceHD->COMGETTER(Format)(srcFormat.asOutParam());
1359 if (FAILED(rc)) throw rc;
1360 /* Create a new hard disk interface for the destination disk image */
1361 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1362 if (FAILED(rc)) throw rc;
1363 /* Clone the source disk image */
1364 rc = pSourceHD->CloneTo(pTargetHD, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1365 if (FAILED(rc)) throw rc;
1366
1367 /* Advance to the next operation */
1368 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1369 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1370 }
1371
1372 // now wait for the background disk operation to complete; this throws HRESULTs on error
1373 waitForAsyncProgress(stack.pProgress, pProgress2);
1374
1375 if (fSourceHdNeedsClosing)
1376 {
1377 rc = pSourceHD->Close();
1378 if (FAILED(rc)) throw rc;
1379 fSourceHdNeedsClosing = false;
1380 }
1381
1382 stack.llHardDisksCreated.push_back(pTargetHD);
1383 }
1384 catch (...)
1385 {
1386 if (fSourceHdNeedsClosing)
1387 pSourceHD->Close();
1388
1389 throw;
1390 }
1391}
1392
1393/**
1394 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1395 * into VirtualBox by creating an IMachine instance, which is returned.
1396 *
1397 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1398 * up any leftovers from this function. For this, the given ImportStack instance has received information
1399 * about what needs cleaning up (to support rollback).
1400 *
1401 * @param vsysThis OVF virtual system (machine) to import.
1402 * @param vsdescThis Matching virtual system description (machine) to import.
1403 * @param pNewMachine out: Newly created machine.
1404 * @param stack Cleanup stack for when this throws.
1405 */
1406void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1407 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1408 ComPtr<IMachine> &pNewMachine,
1409 ImportStack &stack)
1410{
1411 /* Guest OS type */
1412 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1413 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1414 if (vsdeOS.size() < 1)
1415 throw setError(VBOX_E_FILE_ERROR,
1416 tr("Missing guest OS type"));
1417 const Utf8Str &strOsTypeVBox = vsdeOS.front()->strVbox;
1418
1419 /* Now that we know the base system get our internal defaults based on that. */
1420 ComPtr<IGuestOSType> osType;
1421 HRESULT rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), osType.asOutParam());
1422 if (FAILED(rc)) throw rc;
1423
1424 /* Create the machine */
1425 /* First get the name */
1426 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1427 if (vsdeName.size() < 1)
1428 throw setError(VBOX_E_FILE_ERROR,
1429 tr("Missing VM name"));
1430 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
1431 rc = mVirtualBox->CreateMachine(Bstr(strNameVBox),
1432 Bstr(strOsTypeVBox),
1433 NULL,
1434 NULL,
1435 FALSE,
1436 pNewMachine.asOutParam());
1437 if (FAILED(rc)) throw rc;
1438
1439 // and the description
1440 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1441 if (vsdeDescription.size())
1442 {
1443 const Utf8Str &strDescription = vsdeDescription.front()->strVbox;
1444 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1445 if (FAILED(rc)) throw rc;
1446 }
1447
1448 /* CPU count */
1449 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
1450 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1451 const Utf8Str &cpuVBox = vsdeCPU.front()->strVbox;
1452 ULONG tmpCount = (ULONG)RTStrToUInt64(cpuVBox.c_str());
1453 rc = pNewMachine->COMSETTER(CPUCount)(tmpCount);
1454 if (FAILED(rc)) throw rc;
1455 bool fEnableIOApic = false;
1456 /* We need HWVirt & IO-APIC if more than one CPU is requested */
1457 if (tmpCount > 1)
1458 {
1459 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1460 if (FAILED(rc)) throw rc;
1461
1462 fEnableIOApic = true;
1463 }
1464
1465 /* RAM */
1466 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1467 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1468 const Utf8Str &memoryVBox = vsdeRAM.front()->strVbox;
1469 ULONG tt = (ULONG)RTStrToUInt64(memoryVBox.c_str());
1470 rc = pNewMachine->COMSETTER(MemorySize)(tt);
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 (!fEnableIOApic)
1488 {
1489 Bstr bstrFamilyId;
1490 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1491 if (FAILED(rc)) throw rc;
1492 if (bstrFamilyId == "Windows")
1493 fEnableIOApic = true;
1494 }
1495
1496 if (fEnableIOApic)
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 /* Audio Adapter */
1507 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1508 /* @todo: we support one audio adapter only */
1509 if (vsdeAudioAdapter.size() > 0)
1510 {
1511 const Utf8Str& audioAdapterVBox = vsdeAudioAdapter.front()->strVbox;
1512 if (audioAdapterVBox.compare("null", Utf8Str::CaseInsensitive) != 0)
1513 {
1514 uint32_t audio = RTStrToUInt32(audioAdapterVBox.c_str());
1515 ComPtr<IAudioAdapter> audioAdapter;
1516 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1517 if (FAILED(rc)) throw rc;
1518 rc = audioAdapter->COMSETTER(Enabled)(true);
1519 if (FAILED(rc)) throw rc;
1520 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1521 if (FAILED(rc)) throw rc;
1522 }
1523 }
1524
1525#ifdef VBOX_WITH_USB
1526 /* USB Controller */
1527 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1528 // USB support is enabled if there's at least one such entry; to disable USB support,
1529 // the type of the USB item would have been changed to "ignore"
1530 bool fUSBEnabled = vsdeUSBController.size() > 0;
1531
1532 ComPtr<IUSBController> usbController;
1533 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1534 if (FAILED(rc)) throw rc;
1535 rc = usbController->COMSETTER(Enabled)(fUSBEnabled);
1536 if (FAILED(rc)) throw rc;
1537#endif /* VBOX_WITH_USB */
1538
1539 /* Change the network adapters */
1540 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1541 if (vsdeNW.size() == 0)
1542 {
1543 /* No network adapters, so we have to disable our default one */
1544 ComPtr<INetworkAdapter> nwVBox;
1545 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1546 if (FAILED(rc)) throw rc;
1547 rc = nwVBox->COMSETTER(Enabled)(false);
1548 if (FAILED(rc)) throw rc;
1549 }
1550 else if (vsdeNW.size() > SchemaDefs::NetworkAdapterCount)
1551 throw setError(VBOX_E_FILE_ERROR,
1552 tr("Too many network adapters: OVF requests %d network adapters, but VirtualBox only supports %d"),
1553 vsdeNW.size(), SchemaDefs::NetworkAdapterCount);
1554 else
1555 {
1556 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1557 size_t a = 0;
1558 for (nwIt = vsdeNW.begin();
1559 nwIt != vsdeNW.end();
1560 ++nwIt, ++a)
1561 {
1562 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1563
1564 const Utf8Str &nwTypeVBox = pvsys->strVbox;
1565 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1566 ComPtr<INetworkAdapter> pNetworkAdapter;
1567 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1568 if (FAILED(rc)) throw rc;
1569 /* Enable the network card & set the adapter type */
1570 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1571 if (FAILED(rc)) throw rc;
1572 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1573 if (FAILED(rc)) throw rc;
1574
1575 // default is NAT; change to "bridged" if extra conf says so
1576 if (!pvsys->strExtraConfig.compare("type=Bridged", Utf8Str::CaseInsensitive))
1577 {
1578 /* Attach to the right interface */
1579 rc = pNetworkAdapter->AttachToBridgedInterface();
1580 if (FAILED(rc)) throw rc;
1581 ComPtr<IHost> host;
1582 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1583 if (FAILED(rc)) throw rc;
1584 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1585 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1586 if (FAILED(rc)) throw rc;
1587 // We search for the first host network interface which
1588 // is usable for bridged networking
1589 for (size_t j = 0;
1590 j < nwInterfaces.size();
1591 ++j)
1592 {
1593 HostNetworkInterfaceType_T itype;
1594 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1595 if (FAILED(rc)) throw rc;
1596 if (itype == HostNetworkInterfaceType_Bridged)
1597 {
1598 Bstr name;
1599 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1600 if (FAILED(rc)) throw rc;
1601 /* Set the interface name to attach to */
1602 pNetworkAdapter->COMSETTER(HostInterface)(name);
1603 if (FAILED(rc)) throw rc;
1604 break;
1605 }
1606 }
1607 }
1608 /* Next test for host only interfaces */
1609 else if (!pvsys->strExtraConfig.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1610 {
1611 /* Attach to the right interface */
1612 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1613 if (FAILED(rc)) throw rc;
1614 ComPtr<IHost> host;
1615 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1616 if (FAILED(rc)) throw rc;
1617 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1618 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1619 if (FAILED(rc)) throw rc;
1620 // We search for the first host network interface which
1621 // is usable for host only networking
1622 for (size_t j = 0;
1623 j < nwInterfaces.size();
1624 ++j)
1625 {
1626 HostNetworkInterfaceType_T itype;
1627 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1628 if (FAILED(rc)) throw rc;
1629 if (itype == HostNetworkInterfaceType_HostOnly)
1630 {
1631 Bstr name;
1632 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1633 if (FAILED(rc)) throw rc;
1634 /* Set the interface name to attach to */
1635 pNetworkAdapter->COMSETTER(HostInterface)(name);
1636 if (FAILED(rc)) throw rc;
1637 break;
1638 }
1639 }
1640 }
1641 }
1642 }
1643
1644 // IDE Hard disk controller
1645 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1646 // In OVF (at least VMware's version of it), an IDE controller has two ports, so VirtualBox's single IDE controller
1647 // with two channels and two ports each counts as two OVF IDE controllers -- so we accept one or two such IDE controllers
1648 uint32_t cIDEControllers = vsdeHDCIDE.size();
1649 if (cIDEControllers > 2)
1650 throw setError(VBOX_E_FILE_ERROR,
1651 tr("Too many IDE controllers in OVF; import facility only supports two"));
1652 if (vsdeHDCIDE.size() > 0)
1653 {
1654 // one or two IDE controllers present in OVF: add one VirtualBox controller
1655 ComPtr<IStorageController> pController;
1656 rc = pNewMachine->AddStorageController(Bstr("IDE Controller"), StorageBus_IDE, pController.asOutParam());
1657 if (FAILED(rc)) throw rc;
1658
1659 const char *pcszIDEType = vsdeHDCIDE.front()->strVbox.c_str();
1660 if (!strcmp(pcszIDEType, "PIIX3"))
1661 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1662 else if (!strcmp(pcszIDEType, "PIIX4"))
1663 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1664 else if (!strcmp(pcszIDEType, "ICH6"))
1665 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1666 else
1667 throw setError(VBOX_E_FILE_ERROR,
1668 tr("Invalid IDE controller type \"%s\""),
1669 pcszIDEType);
1670 if (FAILED(rc)) throw rc;
1671 }
1672
1673 /* Hard disk controller SATA */
1674 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1675 if (vsdeHDCSATA.size() > 1)
1676 throw setError(VBOX_E_FILE_ERROR,
1677 tr("Too many SATA controllers in OVF; import facility only supports one"));
1678 if (vsdeHDCSATA.size() > 0)
1679 {
1680 ComPtr<IStorageController> pController;
1681 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVbox;
1682 if (hdcVBox == "AHCI")
1683 {
1684 rc = pNewMachine->AddStorageController(Bstr("SATA Controller"), StorageBus_SATA, pController.asOutParam());
1685 if (FAILED(rc)) throw rc;
1686 }
1687 else
1688 throw setError(VBOX_E_FILE_ERROR,
1689 tr("Invalid SATA controller type \"%s\""),
1690 hdcVBox.c_str());
1691 }
1692
1693 /* Hard disk controller SCSI */
1694 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1695 if (vsdeHDCSCSI.size() > 1)
1696 throw setError(VBOX_E_FILE_ERROR,
1697 tr("Too many SCSI controllers in OVF; import facility only supports one"));
1698 if (vsdeHDCSCSI.size() > 0)
1699 {
1700 ComPtr<IStorageController> pController;
1701 Bstr bstrName(L"SCSI Controller");
1702 StorageBus_T busType = StorageBus_SCSI;
1703 StorageControllerType_T controllerType;
1704 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVbox;
1705 if (hdcVBox == "LsiLogic")
1706 controllerType = StorageControllerType_LsiLogic;
1707 else if (hdcVBox == "LsiLogicSas")
1708 {
1709 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
1710 bstrName = L"SAS Controller";
1711 busType = StorageBus_SAS;
1712 controllerType = StorageControllerType_LsiLogicSas;
1713 }
1714 else if (hdcVBox == "BusLogic")
1715 controllerType = StorageControllerType_BusLogic;
1716 else
1717 throw setError(VBOX_E_FILE_ERROR,
1718 tr("Invalid SCSI controller type \"%s\""),
1719 hdcVBox.c_str());
1720
1721 rc = pNewMachine->AddStorageController(bstrName, busType, pController.asOutParam());
1722 if (FAILED(rc)) throw rc;
1723 rc = pController->COMSETTER(ControllerType)(controllerType);
1724 if (FAILED(rc)) throw rc;
1725 }
1726
1727 /* Now its time to register the machine before we add any hard disks */
1728 rc = mVirtualBox->RegisterMachine(pNewMachine);
1729 if (FAILED(rc)) throw rc;
1730
1731 // store new machine for roll-back in case of errors
1732 Bstr bstrNewMachineId;
1733 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
1734 if (FAILED(rc)) throw rc;
1735 stack.llMachinesRegistered.push_back(bstrNewMachineId);
1736
1737 // Add floppies and CD-ROMs to the appropriate controllers.
1738 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1739 if (vsdeFloppy.size() > 1)
1740 throw setError(VBOX_E_FILE_ERROR,
1741 tr("Too many floppy controllers in OVF; import facility only supports one"));
1742 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1743 if ( (vsdeFloppy.size() > 0)
1744 || (vsdeCDROM.size() > 0)
1745 )
1746 {
1747 // If there's an error here we need to close the session, so
1748 // we need another try/catch block.
1749
1750 try
1751 {
1752 // to attach things we need to open a session for the new machine
1753 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1754 if (FAILED(rc)) throw rc;
1755 stack.fSessionOpen = true;
1756
1757 ComPtr<IMachine> sMachine;
1758 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1759 if (FAILED(rc)) throw rc;
1760
1761 // floppy first
1762 if (vsdeFloppy.size() == 1)
1763 {
1764 ComPtr<IStorageController> pController;
1765 rc = sMachine->AddStorageController(Bstr("Floppy Controller"), StorageBus_Floppy, pController.asOutParam());
1766 if (FAILED(rc)) throw rc;
1767
1768 Bstr bstrName;
1769 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1770 if (FAILED(rc)) throw rc;
1771
1772 // this is for rollback later
1773 MyHardDiskAttachment mhda;
1774 mhda.bstrUuid = bstrNewMachineId;
1775 mhda.pMachine = pNewMachine;
1776 mhda.controllerType = bstrName;
1777 mhda.lControllerPort = 0;
1778 mhda.lDevice = 0;
1779
1780 Log(("Attaching floppy\n"));
1781
1782 rc = sMachine->AttachDevice(mhda.controllerType,
1783 mhda.lControllerPort,
1784 mhda.lDevice,
1785 DeviceType_Floppy,
1786 NULL);
1787 if (FAILED(rc)) throw rc;
1788
1789 stack.llHardDiskAttachments.push_back(mhda);
1790 }
1791
1792 // CD-ROMs next
1793 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
1794 jt != vsdeCDROM.end();
1795 ++jt)
1796 {
1797 // for now always attach to secondary master on IDE controller;
1798 // there seems to be no useful information in OVF where else to
1799 // attach it (@todo test with latest versions of OVF software)
1800
1801 // find the IDE controller
1802 const ovf::HardDiskController *pController = NULL;
1803 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
1804 kt != vsysThis.mapControllers.end();
1805 ++kt)
1806 {
1807 if (kt->second.system == ovf::HardDiskController::IDE)
1808 {
1809 pController = &kt->second;
1810 break;
1811 }
1812 }
1813
1814 if (!pController)
1815 throw setError(VBOX_E_FILE_ERROR,
1816 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
1817
1818 // this is for rollback later
1819 MyHardDiskAttachment mhda;
1820 mhda.bstrUuid = bstrNewMachineId;
1821 mhda.pMachine = pNewMachine;
1822
1823 convertDiskAttachmentValues(*pController,
1824 2, // interpreted as secondary master
1825 mhda.controllerType, // Bstr
1826 mhda.lControllerPort,
1827 mhda.lDevice);
1828
1829 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
1830
1831 rc = sMachine->AttachDevice(mhda.controllerType,
1832 mhda.lControllerPort,
1833 mhda.lDevice,
1834 DeviceType_DVD,
1835 NULL);
1836 if (FAILED(rc)) throw rc;
1837
1838 stack.llHardDiskAttachments.push_back(mhda);
1839 } // end for (itHD = avsdeHDs.begin();
1840
1841 rc = sMachine->SaveSettings();
1842 if (FAILED(rc)) throw rc;
1843
1844 // only now that we're done with all disks, close the session
1845 rc = stack.pSession->Close();
1846 if (FAILED(rc)) throw rc;
1847 stack.fSessionOpen = false;
1848 }
1849 catch(HRESULT /* aRC */)
1850 {
1851 if (stack.fSessionOpen)
1852 stack.pSession->Close();
1853
1854 throw;
1855 }
1856 }
1857
1858 // create the hard disks & connect them to the appropriate controllers
1859 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1860 if (avsdeHDs.size() > 0)
1861 {
1862 // If there's an error here we need to close the session, so
1863 // we need another try/catch block.
1864 try
1865 {
1866 // to attach things we need to open a session for the new machine
1867 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1868 if (FAILED(rc)) throw rc;
1869 stack.fSessionOpen = true;
1870
1871 /* Iterate over all given disk images */
1872 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1873 for (itHD = avsdeHDs.begin();
1874 itHD != avsdeHDs.end();
1875 ++itHD)
1876 {
1877 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1878
1879 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1880 // in the virtual system's disks map under that ID and also in the global images map
1881 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1882 // and find the disk from the OVF's disk list
1883 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
1884 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
1885 || (itDiskImage == stack.mapDisks.end())
1886 )
1887 throw setError(E_FAIL,
1888 tr("Internal inconsistency looking up disk image '%s'"),
1889 vsdeHD->strRef.c_str());
1890
1891 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
1892 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
1893
1894 ComPtr<IMedium> pTargetHD;
1895 importOneDiskImage(ovfDiskImage,
1896 vsdeHD->strVbox,
1897 pTargetHD,
1898 stack);
1899
1900 // now use the new uuid to attach the disk image to our new machine
1901 ComPtr<IMachine> sMachine;
1902 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1903 if (FAILED(rc)) throw rc;
1904 Bstr hdId;
1905 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
1906 if (FAILED(rc)) throw rc;
1907
1908 // find the hard disk controller to which we should attach
1909 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
1910
1911 // this is for rollback later
1912 MyHardDiskAttachment mhda;
1913 mhda.bstrUuid = bstrNewMachineId;
1914 mhda.pMachine = pNewMachine;
1915
1916 convertDiskAttachmentValues(hdc,
1917 ovfVdisk.ulAddressOnParent,
1918 mhda.controllerType, // Bstr
1919 mhda.lControllerPort,
1920 mhda.lDevice);
1921
1922 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVbox.c_str(), mhda.lControllerPort, mhda.lDevice));
1923
1924 rc = sMachine->AttachDevice(mhda.controllerType, // wstring name
1925 mhda.lControllerPort, // long controllerPort
1926 mhda.lDevice, // long device
1927 DeviceType_HardDisk, // DeviceType_T type
1928 hdId); // uuid id
1929 if (FAILED(rc)) throw rc;
1930
1931 stack.llHardDiskAttachments.push_back(mhda);
1932
1933 rc = sMachine->SaveSettings();
1934 if (FAILED(rc)) throw rc;
1935 } // end for (itHD = avsdeHDs.begin();
1936
1937 // only now that we're done with all disks, close the session
1938 rc = stack.pSession->Close();
1939 if (FAILED(rc)) throw rc;
1940 stack.fSessionOpen = false;
1941 }
1942 catch(HRESULT /* aRC */)
1943 {
1944 if (stack.fSessionOpen)
1945 stack.pSession->Close();
1946
1947 throw;
1948 }
1949 }
1950}
1951
1952/**
1953 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
1954 * structure) into VirtualBox by creating an IMachine instance, which is returned.
1955 *
1956 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1957 * up any leftovers from this function. For this, the given ImportStack instance has received information
1958 * about what needs cleaning up (to support rollback).
1959 *
1960 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
1961 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
1962 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
1963 * will most probably work, reimporting them into the same host will cause conflicts, so we always
1964 * generate new ones on import. This involves the following:
1965 *
1966 * 1) Scan the machine config for disk attachments.
1967 *
1968 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
1969 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
1970 * replace the old UUID with the new one.
1971 *
1972 * 3) Create the VirtualBox machine with the modfified machine config.
1973 *
1974 * @param config
1975 * @param pNewMachine
1976 * @param stack
1977 */
1978void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
1979 ComPtr<IMachine> &pReturnNewMachine,
1980 ImportStack &stack)
1981{
1982 Assert(vsdescThis->m->pConfig);
1983
1984 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
1985
1986 Utf8Str strDefaultHardDiskFolder;
1987 HRESULT rc = getDefaultHardDiskFolder(strDefaultHardDiskFolder);
1988 if (FAILED(rc)) throw rc;
1989
1990 // step 1): scan the machine config for attachments
1991 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
1992 sit != config.storageMachine.llStorageControllers.end();
1993 ++sit)
1994 {
1995 settings::StorageController &sc = *sit;
1996
1997 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
1998 dit != sc.llAttachedDevices.end();
1999 ++dit)
2000 {
2001 settings::AttachedDevice &d = *dit;
2002
2003 if (d.uuid.isEmpty())
2004 // empty DVD and floppy media
2005 continue;
2006
2007 // convert the Guid to string
2008 Utf8Str strUuid = d.uuid.toString();
2009
2010 // there must be an image in the OVF disk structs with the same UUID
2011 bool fFound = false;
2012 for (ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2013 oit != stack.mapDisks.end();
2014 ++oit)
2015 {
2016 const ovf::DiskImage &di = oit->second;
2017
2018 if (di.uuidVbox == strUuid)
2019 {
2020 Utf8Str strTargetPath(strDefaultHardDiskFolder);
2021 strTargetPath.append(RTPATH_DELIMITER);
2022 strTargetPath.append(di.strHref);
2023 searchUniqueDiskImageFilePath(strTargetPath);
2024
2025 // step 2): for each attachment, import the disk...
2026 ComPtr<IMedium> pTargetHD;
2027 importOneDiskImage(di,
2028 strTargetPath,
2029 pTargetHD,
2030 stack);
2031
2032 // ... and replace the old UUID in the machine config with the one of
2033 // the imported disk that was just created
2034 Bstr hdId;
2035 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
2036 if (FAILED(rc)) throw rc;
2037
2038 d.uuid = hdId;
2039
2040 fFound = true;
2041 break;
2042 }
2043 }
2044
2045 // no disk with such a UUID found:
2046 if (!fFound)
2047 throw setError(E_FAIL,
2048 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s but the OVF describes no such image"),
2049 strUuid.raw());
2050 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
2051 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
2052
2053 // step 3): create the machine and have it import the config
2054
2055 // use the name that we computed in the OVF fields to avoid duplicates
2056 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2057 if (vsdeName.size() < 1)
2058 throw setError(VBOX_E_FILE_ERROR,
2059 tr("Missing VM name"));
2060 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
2061
2062 ComObjPtr<Machine> pNewMachine;
2063 rc = pNewMachine.createObject();
2064 if (FAILED(rc)) throw rc;
2065
2066 // this magic constructor fills the new machine object with the MachineConfig
2067 // instance that we created from the vbox:Machine
2068 rc = pNewMachine->init(mVirtualBox,
2069 strNameVBox, // name from just above (can be suffixed to avoid duplicates)
2070 config); // the whole machine config
2071 if (FAILED(rc)) throw rc;
2072
2073 // return the new machine as an IMachine
2074 IMachine *p;
2075 rc = pNewMachine.queryInterfaceTo(&p);
2076 if (FAILED(rc)) throw rc;
2077 pReturnNewMachine = p;
2078
2079 // and register it
2080 rc = mVirtualBox->RegisterMachine(pNewMachine);
2081 if (FAILED(rc)) throw rc;
2082
2083 // store new machine for roll-back in case of errors
2084 Bstr bstrNewMachineId;
2085 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2086 if (FAILED(rc)) throw rc;
2087 stack.llMachinesRegistered.push_back(bstrNewMachineId);
2088}
2089
2090/**
2091 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
2092 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
2093 * thread to import from temporary files (see Appliance::importFS()).
2094 * @param pTask
2095 * @return
2096 */
2097HRESULT Appliance::importS3(TaskOVF *pTask)
2098{
2099 LogFlowFuncEnter();
2100 LogFlowFunc(("Appliance %p\n", this));
2101
2102 AutoCaller autoCaller(this);
2103 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2104
2105 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
2106
2107 int vrc = VINF_SUCCESS;
2108 RTS3 hS3 = NIL_RTS3;
2109 char szOSTmpDir[RTPATH_MAX];
2110 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
2111 /* The template for the temporary directory created below */
2112 char *pszTmpDir;
2113 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
2114 list< pair<Utf8Str, ULONG> > filesList;
2115
2116 HRESULT rc = S_OK;
2117 try
2118 {
2119 /* Extract the bucket */
2120 Utf8Str tmpPath = pTask->locInfo.strPath;
2121 Utf8Str bucket;
2122 parseBucket(tmpPath, bucket);
2123
2124 /* We need a temporary directory which we can put the all disk images
2125 * in */
2126 vrc = RTDirCreateTemp(pszTmpDir);
2127 if (RT_FAILURE(vrc))
2128 throw setError(VBOX_E_FILE_ERROR,
2129 tr("Cannot create temporary directory '%s'"), pszTmpDir);
2130
2131 /* Add every disks of every virtual system to an internal list */
2132 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2133 for (it = m->virtualSystemDescriptions.begin();
2134 it != m->virtualSystemDescriptions.end();
2135 ++it)
2136 {
2137 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2138 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2139 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2140 for (itH = avsdeHDs.begin();
2141 itH != avsdeHDs.end();
2142 ++itH)
2143 {
2144 const Utf8Str &strTargetFile = (*itH)->strOvf;
2145 if (!strTargetFile.isEmpty())
2146 {
2147 /* The temporary name of the target disk file */
2148 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
2149 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
2150 }
2151 }
2152 }
2153
2154 /* Next we have to download the disk images */
2155 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2156 if (RT_FAILURE(vrc))
2157 throw setError(VBOX_E_IPRT_ERROR,
2158 tr("Cannot create S3 service handler"));
2159 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2160
2161 /* Download all files */
2162 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2163 {
2164 const pair<Utf8Str, ULONG> &s = (*it1);
2165 const Utf8Str &strSrcFile = s.first;
2166 /* Construct the source file name */
2167 char *pszFilename = RTPathFilename(strSrcFile.c_str());
2168 /* Advance to the next operation */
2169 if (!pTask->pProgress.isNull())
2170 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), s.second);
2171
2172 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
2173 if (RT_FAILURE(vrc))
2174 {
2175 if (vrc == VERR_S3_CANCELED)
2176 throw S_OK; /* todo: !!!!!!!!!!!!! */
2177 else if (vrc == VERR_S3_ACCESS_DENIED)
2178 throw setError(E_ACCESSDENIED,
2179 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);
2180 else if (vrc == VERR_S3_NOT_FOUND)
2181 throw setError(VBOX_E_FILE_ERROR,
2182 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
2183 else
2184 throw setError(VBOX_E_IPRT_ERROR,
2185 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2186 }
2187 }
2188
2189 /* Provide a OVF file (haven't to exist) so the import routine can
2190 * figure out where the disk images/manifest file are located. */
2191 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2192 /* Now check if there is an manifest file. This is optional. */
2193 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
2194 char *pszFilename = RTPathFilename(strManifestFile.c_str());
2195 if (!pTask->pProgress.isNull())
2196 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
2197
2198 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
2199 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
2200 if (RT_SUCCESS(vrc))
2201 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
2202 else if (RT_FAILURE(vrc))
2203 {
2204 if (vrc == VERR_S3_CANCELED)
2205 throw S_OK; /* todo: !!!!!!!!!!!!! */
2206 else if (vrc == VERR_S3_NOT_FOUND)
2207 vrc = VINF_SUCCESS; /* Not found is ok */
2208 else if (vrc == VERR_S3_ACCESS_DENIED)
2209 throw setError(E_ACCESSDENIED,
2210 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);
2211 else
2212 throw setError(VBOX_E_IPRT_ERROR,
2213 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2214 }
2215
2216 /* Close the connection early */
2217 RTS3Destroy(hS3);
2218 hS3 = NIL_RTS3;
2219
2220 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightForXmlOperation);
2221
2222 ComObjPtr<Progress> progress;
2223 /* Import the whole temporary OVF & the disk images */
2224 LocationInfo li;
2225 li.strPath = strTmpOvf;
2226 rc = importImpl(li, progress);
2227 if (FAILED(rc)) throw rc;
2228
2229 /* Unlock the appliance for the fs import thread */
2230 appLock.release();
2231 /* Wait until the import is done, but report the progress back to the
2232 caller */
2233 ComPtr<IProgress> progressInt(progress);
2234 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2235
2236 /* Again lock the appliance for the next steps */
2237 appLock.acquire();
2238 }
2239 catch(HRESULT aRC)
2240 {
2241 rc = aRC;
2242 }
2243 /* Cleanup */
2244 RTS3Destroy(hS3);
2245 /* Delete all files which where temporary created */
2246 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2247 {
2248 const char *pszFilePath = (*it1).first.c_str();
2249 if (RTPathExists(pszFilePath))
2250 {
2251 vrc = RTFileDelete(pszFilePath);
2252 if (RT_FAILURE(vrc))
2253 rc = setError(VBOX_E_FILE_ERROR,
2254 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2255 }
2256 }
2257 /* Delete the temporary directory */
2258 if (RTPathExists(pszTmpDir))
2259 {
2260 vrc = RTDirRemove(pszTmpDir);
2261 if (RT_FAILURE(vrc))
2262 rc = setError(VBOX_E_FILE_ERROR,
2263 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2264 }
2265 if (pszTmpDir)
2266 RTStrFree(pszTmpDir);
2267
2268 LogFlowFunc(("rc=%Rhrc\n", rc));
2269 LogFlowFuncLeave();
2270
2271 return rc;
2272}
2273
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