VirtualBox

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

Last change on this file since 27930 was 27918, checked in by vboxsync, 15 years ago

Main/OVF: import vbox:Machine XML within OVF, first batch (XML is parsed and machine config created, but COM Machine can't handle it yet)

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

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