VirtualBox

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

最後變更 在這個檔案從33078是 32965,由 vboxsync 提交於 14 年 前

Main-OVF: fix check of the manifest file existence on import

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette