VirtualBox

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

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

Main: don't export snapshots in OVF, separate OVF import from vbox:Machine import

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 86.2 KB
Line 
1/* $Id: ApplianceImplImport.cpp 28098 2010-04-08 15:35:38Z 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.215389.xyz. 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 * Used by Appliance::importMachineGeneric() to store
955 * input parameters and rollback information.
956 */
957struct Appliance::ImportStack
958{
959 // input pointers
960 const LocationInfo &locInfo; // ptr to location info from Appliance::importFS()
961 const ovf::DiskImagesMap &mapDisks; // ptr to disks map in OVF
962 ComObjPtr<Progress> &pProgress; // progress object passed into Appliance::importFS()
963
964 // session (not initially created)
965 ComPtr<ISession> pSession; // session opened in Appliance::importFS() for machine manipulation
966 bool fSessionOpen; // true if the pSession is currently open and needs closing
967
968 // a list of images that we created/imported; this is initially empty
969 // and will be cleaned up on errors
970 list<MyHardDiskAttachment> llHardDiskAttachments; // disks that were attached
971 list< ComPtr<IMedium> > llHardDisksCreated; // media that were created
972 list<Bstr> llMachinesRegistered; // machines that were registered; list of string UUIDs
973
974 ImportStack(const LocationInfo &aLocInfo,
975 const ovf::DiskImagesMap &aMapDisks,
976 ComObjPtr<Progress> &aProgress)
977 : locInfo(aLocInfo),
978 mapDisks(aMapDisks),
979 pProgress(aProgress),
980 fSessionOpen(false)
981 {
982 }
983};
984
985/**
986 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
987 * and therefore runs on the OVF import worker thread. This runs in two contexts:
988 *
989 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
990 *
991 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
992 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this.
993 *
994 * @param pTask
995 * @return
996 */
997HRESULT Appliance::importFS(const LocationInfo &locInfo,
998 ComObjPtr<Progress> &pProgress)
999{
1000 LogFlowFuncEnter();
1001 LogFlowFunc(("Appliance %p\n", this));
1002
1003 AutoCaller autoCaller(this);
1004 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1005
1006 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1007
1008 if (!isApplianceIdle())
1009 return E_ACCESSDENIED;
1010
1011 Assert(!pProgress.isNull());
1012
1013 // Change the appliance state so we can safely leave the lock while doing time-consuming
1014 // disk imports; also the below method calls do all kinds of locking which conflicts with
1015 // the appliance object lock
1016 m->state = Data::ApplianceImporting;
1017 appLock.release();
1018
1019 HRESULT rc = S_OK;
1020
1021 const ovf::OVFReader &reader = *m->pReader;
1022 // this is safe to access because this thread only gets started
1023 // if pReader != NULL
1024
1025 // rollback for errors:
1026 ImportStack stack(locInfo, reader.m_mapDisks, pProgress);
1027 /* If a manifest file exists, verify the content. Therefore we need all
1028 * files which are referenced by the OVF & the OVF itself */
1029 Utf8Str strMfFile = manifestFileName(locInfo.strPath);
1030 list<Utf8Str> filesList;
1031 if (RTPathExists(strMfFile.c_str()))
1032 {
1033 Utf8Str strSrcDir(locInfo.strPath);
1034 strSrcDir.stripFilename();
1035 /* Add every disks of every virtual system to an internal list */
1036 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1037 for (it = m->virtualSystemDescriptions.begin();
1038 it != m->virtualSystemDescriptions.end();
1039 ++it)
1040 {
1041 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1042 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1043 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1044 for (itH = avsdeHDs.begin();
1045 itH != avsdeHDs.end();
1046 ++itH)
1047 {
1048 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1049 /* Find the disk from the OVF's disk list */
1050 ovf::DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1051 const ovf::DiskImage &di = itDiskImage->second;
1052 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1053 filesList.push_back(strSrcFilePath);
1054 }
1055 }
1056 /* Create the test list */
1057 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST)*(filesList.size()+1));
1058 pTestList[0].pszTestFile = (char*)locInfo.strPath.c_str();
1059 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1060 int vrc = VINF_SUCCESS;
1061 size_t i = 1;
1062 list<Utf8Str>::const_iterator it1;
1063 for (it1 = filesList.begin();
1064 it1 != filesList.end();
1065 ++it1, ++i)
1066 {
1067 char* pszDigest;
1068 vrc = RTSha1Digest((*it1).c_str(), &pszDigest);
1069 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1070 pTestList[i].pszTestDigest = pszDigest;
1071 }
1072 size_t cIndexOnError;
1073 vrc = RTManifestVerify(strMfFile.c_str(), pTestList, filesList.size() + 1, &cIndexOnError);
1074 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1075 rc = setError(VBOX_E_FILE_ERROR,
1076 tr("The SHA1 digest of '%s' doesn't match to the one in '%s'"),
1077 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1078 RTPathFilename(strMfFile.c_str()));
1079 else if (RT_FAILURE(vrc))
1080 rc = setError(VBOX_E_FILE_ERROR,
1081 tr("Couldn't verify the content of '%s' against the available files (%Rrc)"),
1082 RTPathFilename(strMfFile.c_str()),
1083 vrc);
1084 /* Cleanup */
1085 for (size_t j = 1;
1086 j < filesList.size();
1087 ++j)
1088 RTStrFree(pTestList[j].pszTestDigest);
1089 RTMemFree(pTestList);
1090 if (FAILED(rc)) return rc;
1091 }
1092
1093 rc = stack.pSession.createInprocObject(CLSID_Session);
1094 if (FAILED(rc)) return rc;
1095
1096 list<ovf::VirtualSystem>::const_iterator it;
1097 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1098 /* Iterate through all virtual systems of that appliance */
1099 size_t i = 0;
1100 for (it = reader.m_llVirtualSystems.begin(),
1101 it1 = m->virtualSystemDescriptions.begin();
1102 it != reader.m_llVirtualSystems.end();
1103 ++it, ++it1, ++i)
1104 {
1105 const ovf::VirtualSystem &vsysThis = *it;
1106 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1107
1108 ComPtr<IMachine> pNewMachine;
1109
1110 /* Catch possible errors */
1111 try
1112 {
1113 // there are two ways in which we can create a vbox machine from OVF:
1114 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
1115 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
1116 // with all the machine config pretty-parsed;
1117 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
1118 // VirtualSystemDescriptionEntry and do import work
1119
1120 // @todo r=dj make this selection configurable at run-time, and from the GUI as well
1121
1122 if (vsdescThis->m->pConfig)
1123 importVBoxMachine(*vsdescThis->m->pConfig, pNewMachine, stack);
1124 else
1125 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
1126 }
1127 catch(HRESULT aRC)
1128 {
1129 rc = aRC;
1130 }
1131
1132 if (FAILED(rc))
1133 break;
1134
1135 } // for (it = pAppliance->m->llVirtualSystems.begin(),
1136
1137 if (FAILED(rc))
1138 {
1139 // with _whatever_ error we've had, do a complete roll-back of
1140 // machines and disks we've created; unfortunately this is
1141 // not so trivially done...
1142
1143 HRESULT rc2;
1144 // detach all hard disks from all machines we created
1145 list<MyHardDiskAttachment>::iterator itM;
1146 for (itM = stack.llHardDiskAttachments.begin();
1147 itM != stack.llHardDiskAttachments.end();
1148 ++itM)
1149 {
1150 const MyHardDiskAttachment &mhda = *itM;
1151 Bstr bstrUuid(mhda.bstrUuid); // make a copy, Windows can't handle const Bstr
1152 rc2 = mVirtualBox->OpenSession(stack.pSession, bstrUuid);
1153 if (SUCCEEDED(rc2))
1154 {
1155 ComPtr<IMachine> sMachine;
1156 rc2 = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1157 if (SUCCEEDED(rc2))
1158 {
1159 rc2 = sMachine->DetachDevice(Bstr(mhda.controllerType), mhda.lChannel, mhda.lDevice);
1160 rc2 = sMachine->SaveSettings();
1161 }
1162 stack.pSession->Close();
1163 }
1164 }
1165
1166 // now clean up all hard disks we created
1167 list< ComPtr<IMedium> >::iterator itHD;
1168 for (itHD = stack.llHardDisksCreated.begin();
1169 itHD != stack.llHardDisksCreated.end();
1170 ++itHD)
1171 {
1172 ComPtr<IMedium> pDisk = *itHD;
1173 ComPtr<IProgress> pProgress2;
1174 rc2 = pDisk->DeleteStorage(pProgress2.asOutParam());
1175 rc2 = pProgress2->WaitForCompletion(-1);
1176 }
1177
1178 // finally, deregister and remove all machines
1179 list<Bstr>::iterator itID;
1180 for (itID = stack.llMachinesRegistered.begin();
1181 itID != stack.llMachinesRegistered.end();
1182 ++itID)
1183 {
1184 Bstr bstrGuid = *itID; // make a copy, Windows can't handle const Bstr
1185 ComPtr<IMachine> failedMachine;
1186 rc2 = mVirtualBox->UnregisterMachine(bstrGuid, failedMachine.asOutParam());
1187 if (SUCCEEDED(rc2))
1188 rc2 = failedMachine->DeleteSettings();
1189 }
1190 }
1191
1192 // restore the appliance state
1193 appLock.acquire();
1194 m->state = Data::ApplianceIdle;
1195
1196 LogFlowFunc(("rc=%Rhrc\n", rc));
1197 LogFlowFuncLeave();
1198
1199 return rc;
1200}
1201
1202/**
1203 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1204 * into VirtualBox by creating an IMachine instance, which is returned.
1205 *
1206 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1207 * up any leftovers from this function. For this, the given ImportStack instance has received information
1208 * about what needs cleaning up (to support rollback).
1209 *
1210 * @param locInfo
1211 * @param vsysThis
1212 * @param vsdescThis
1213 * @param pNewMachine
1214 * @param stack
1215 */
1216void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1217 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1218 ComPtr<IMachine> &pNewMachine,
1219 ImportStack &stack)
1220{
1221 /* Guest OS type */
1222 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1223 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1224 if (vsdeOS.size() < 1)
1225 throw setError(VBOX_E_FILE_ERROR,
1226 tr("Missing guest OS type"));
1227 const Utf8Str &strOsTypeVBox = vsdeOS.front()->strVbox;
1228
1229 /* Now that we know the base system get our internal defaults based on that. */
1230 ComPtr<IGuestOSType> osType;
1231 HRESULT rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), osType.asOutParam());
1232 if (FAILED(rc)) throw rc;
1233
1234 /* Create the machine */
1235 /* First get the name */
1236 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1237 if (vsdeName.size() < 1)
1238 throw setError(VBOX_E_FILE_ERROR,
1239 tr("Missing VM name"));
1240 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
1241 rc = mVirtualBox->CreateMachine(Bstr(strNameVBox),
1242 Bstr(strOsTypeVBox),
1243 NULL,
1244 NULL,
1245 FALSE,
1246 pNewMachine.asOutParam());
1247 if (FAILED(rc)) throw rc;
1248
1249 // and the description
1250 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1251 if (vsdeDescription.size())
1252 {
1253 const Utf8Str &strDescription = vsdeDescription.front()->strVbox;
1254 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1255 if (FAILED(rc)) throw rc;
1256 }
1257
1258 /* CPU count */
1259 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
1260 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1261 const Utf8Str &cpuVBox = vsdeCPU.front()->strVbox;
1262 ULONG tmpCount = (ULONG)RTStrToUInt64(cpuVBox.c_str());
1263 rc = pNewMachine->COMSETTER(CPUCount)(tmpCount);
1264 if (FAILED(rc)) throw rc;
1265 bool fEnableIOApic = false;
1266 /* We need HWVirt & IO-APIC if more than one CPU is requested */
1267 if (tmpCount > 1)
1268 {
1269 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1270 if (FAILED(rc)) throw rc;
1271
1272 fEnableIOApic = true;
1273 }
1274
1275 /* RAM */
1276 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1277 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1278 const Utf8Str &memoryVBox = vsdeRAM.front()->strVbox;
1279 ULONG tt = (ULONG)RTStrToUInt64(memoryVBox.c_str());
1280 rc = pNewMachine->COMSETTER(MemorySize)(tt);
1281 if (FAILED(rc)) throw rc;
1282
1283 /* VRAM */
1284 /* Get the recommended VRAM for this guest OS type */
1285 ULONG vramVBox;
1286 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1287 if (FAILED(rc)) throw rc;
1288
1289 /* Set the VRAM */
1290 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1291 if (FAILED(rc)) throw rc;
1292
1293 /* I/O APIC: so far we have no setting for this. Enable it if we
1294 import a Windows VM because if if Windows was installed without IOAPIC,
1295 it will not mind finding an one later on, but if Windows was installed
1296 _with_ an IOAPIC, it will bluescreen if it's not found */
1297 Bstr bstrFamilyId;
1298 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1299 if (FAILED(rc)) throw rc;
1300
1301 Utf8Str strFamilyId(bstrFamilyId);
1302 if (strFamilyId == "Windows")
1303 fEnableIOApic = true;
1304
1305 /* If IP-APIC should be enabled could be have different reasons.
1306 See CPU count & the Win test above. Here we enable it if it was
1307 previously requested. */
1308 if (fEnableIOApic)
1309 {
1310 ComPtr<IBIOSSettings> pBIOSSettings;
1311 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1312 if (FAILED(rc)) throw rc;
1313
1314 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1315 if (FAILED(rc)) throw rc;
1316 }
1317
1318 /* Audio Adapter */
1319 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1320 /* @todo: we support one audio adapter only */
1321 if (vsdeAudioAdapter.size() > 0)
1322 {
1323 const Utf8Str& audioAdapterVBox = vsdeAudioAdapter.front()->strVbox;
1324 if (audioAdapterVBox.compare("null", Utf8Str::CaseInsensitive) != 0)
1325 {
1326 uint32_t audio = RTStrToUInt32(audioAdapterVBox.c_str());
1327 ComPtr<IAudioAdapter> audioAdapter;
1328 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1329 if (FAILED(rc)) throw rc;
1330 rc = audioAdapter->COMSETTER(Enabled)(true);
1331 if (FAILED(rc)) throw rc;
1332 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1333 if (FAILED(rc)) throw rc;
1334 }
1335 }
1336
1337#ifdef VBOX_WITH_USB
1338 /* USB Controller */
1339 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1340 // USB support is enabled if there's at least one such entry; to disable USB support,
1341 // the type of the USB item would have been changed to "ignore"
1342 bool fUSBEnabled = vsdeUSBController.size() > 0;
1343
1344 ComPtr<IUSBController> usbController;
1345 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1346 if (FAILED(rc)) throw rc;
1347 rc = usbController->COMSETTER(Enabled)(fUSBEnabled);
1348 if (FAILED(rc)) throw rc;
1349#endif /* VBOX_WITH_USB */
1350
1351 /* Change the network adapters */
1352 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1353 if (vsdeNW.size() == 0)
1354 {
1355 /* No network adapters, so we have to disable our default one */
1356 ComPtr<INetworkAdapter> nwVBox;
1357 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1358 if (FAILED(rc)) throw rc;
1359 rc = nwVBox->COMSETTER(Enabled)(false);
1360 if (FAILED(rc)) throw rc;
1361 }
1362 else
1363 {
1364 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1365 /* Iterate through all network cards. We support 8 network adapters
1366 * at the maximum. (@todo: warn if there are more!) */
1367 size_t a = 0;
1368 for (nwIt = vsdeNW.begin();
1369 (nwIt != vsdeNW.end() && a < SchemaDefs::NetworkAdapterCount);
1370 ++nwIt, ++a)
1371 {
1372 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1373
1374 const Utf8Str &nwTypeVBox = pvsys->strVbox;
1375 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1376 ComPtr<INetworkAdapter> pNetworkAdapter;
1377 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1378 if (FAILED(rc)) throw rc;
1379 /* Enable the network card & set the adapter type */
1380 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1381 if (FAILED(rc)) throw rc;
1382 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1383 if (FAILED(rc)) throw rc;
1384
1385 // default is NAT; change to "bridged" if extra conf says so
1386 if (!pvsys->strExtraConfig.compare("type=Bridged", Utf8Str::CaseInsensitive))
1387 {
1388 /* Attach to the right interface */
1389 rc = pNetworkAdapter->AttachToBridgedInterface();
1390 if (FAILED(rc)) throw rc;
1391 ComPtr<IHost> host;
1392 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1393 if (FAILED(rc)) throw rc;
1394 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1395 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1396 if (FAILED(rc)) throw rc;
1397 /* We search for the first host network interface which
1398 * is usable for bridged networking */
1399 for (size_t j = 0;
1400 j < nwInterfaces.size();
1401 ++j)
1402 {
1403 HostNetworkInterfaceType_T itype;
1404 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1405 if (FAILED(rc)) throw rc;
1406 if (itype == HostNetworkInterfaceType_Bridged)
1407 {
1408 Bstr name;
1409 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1410 if (FAILED(rc)) throw rc;
1411 /* Set the interface name to attach to */
1412 pNetworkAdapter->COMSETTER(HostInterface)(name);
1413 if (FAILED(rc)) throw rc;
1414 break;
1415 }
1416 }
1417 }
1418 /* Next test for host only interfaces */
1419 else if (!pvsys->strExtraConfig.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1420 {
1421 /* Attach to the right interface */
1422 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1423 if (FAILED(rc)) throw rc;
1424 ComPtr<IHost> host;
1425 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1426 if (FAILED(rc)) throw rc;
1427 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1428 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1429 if (FAILED(rc)) throw rc;
1430 /* We search for the first host network interface which
1431 * is usable for host only networking */
1432 for (size_t j = 0;
1433 j < nwInterfaces.size();
1434 ++j)
1435 {
1436 HostNetworkInterfaceType_T itype;
1437 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1438 if (FAILED(rc)) throw rc;
1439 if (itype == HostNetworkInterfaceType_HostOnly)
1440 {
1441 Bstr name;
1442 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1443 if (FAILED(rc)) throw rc;
1444 /* Set the interface name to attach to */
1445 pNetworkAdapter->COMSETTER(HostInterface)(name);
1446 if (FAILED(rc)) throw rc;
1447 break;
1448 }
1449 }
1450 }
1451 }
1452 }
1453
1454 /* Hard disk controller IDE */
1455 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1456 if (vsdeHDCIDE.size() > 1)
1457 throw setError(VBOX_E_FILE_ERROR,
1458 tr("Too many IDE controllers in OVF; import facility only supports one"));
1459 if (vsdeHDCIDE.size() == 1)
1460 {
1461 ComPtr<IStorageController> pController;
1462 rc = pNewMachine->AddStorageController(Bstr("IDE Controller"), StorageBus_IDE, pController.asOutParam());
1463 if (FAILED(rc)) throw rc;
1464
1465 const char *pcszIDEType = vsdeHDCIDE.front()->strVbox.c_str();
1466 if (!strcmp(pcszIDEType, "PIIX3"))
1467 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1468 else if (!strcmp(pcszIDEType, "PIIX4"))
1469 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1470 else if (!strcmp(pcszIDEType, "ICH6"))
1471 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1472 else
1473 throw setError(VBOX_E_FILE_ERROR,
1474 tr("Invalid IDE controller type \"%s\""),
1475 pcszIDEType);
1476 if (FAILED(rc)) throw rc;
1477 }
1478#ifdef VBOX_WITH_AHCI
1479 /* Hard disk controller SATA */
1480 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1481 if (vsdeHDCSATA.size() > 1)
1482 throw setError(VBOX_E_FILE_ERROR,
1483 tr("Too many SATA controllers in OVF; import facility only supports one"));
1484 if (vsdeHDCSATA.size() > 0)
1485 {
1486 ComPtr<IStorageController> pController;
1487 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVbox;
1488 if (hdcVBox == "AHCI")
1489 {
1490 rc = pNewMachine->AddStorageController(Bstr("SATA Controller"), StorageBus_SATA, pController.asOutParam());
1491 if (FAILED(rc)) throw rc;
1492 }
1493 else
1494 throw setError(VBOX_E_FILE_ERROR,
1495 tr("Invalid SATA controller type \"%s\""),
1496 hdcVBox.c_str());
1497 }
1498#endif /* VBOX_WITH_AHCI */
1499
1500#ifdef VBOX_WITH_LSILOGIC
1501 /* Hard disk controller SCSI */
1502 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1503 if (vsdeHDCSCSI.size() > 1)
1504 throw setError(VBOX_E_FILE_ERROR,
1505 tr("Too many SCSI controllers in OVF; import facility only supports one"));
1506 if (vsdeHDCSCSI.size() > 0)
1507 {
1508 ComPtr<IStorageController> pController;
1509 StorageControllerType_T controllerType;
1510 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVbox;
1511 if (hdcVBox == "LsiLogic")
1512 controllerType = StorageControllerType_LsiLogic;
1513 else if (hdcVBox == "BusLogic")
1514 controllerType = StorageControllerType_BusLogic;
1515 else
1516 throw setError(VBOX_E_FILE_ERROR,
1517 tr("Invalid SCSI controller type \"%s\""),
1518 hdcVBox.c_str());
1519
1520 rc = pNewMachine->AddStorageController(Bstr("SCSI Controller"), StorageBus_SCSI, pController.asOutParam());
1521 if (FAILED(rc)) throw rc;
1522 rc = pController->COMSETTER(ControllerType)(controllerType);
1523 if (FAILED(rc)) throw rc;
1524 }
1525#endif /* VBOX_WITH_LSILOGIC */
1526
1527 /* Now its time to register the machine before we add any hard disks */
1528 rc = mVirtualBox->RegisterMachine(pNewMachine);
1529 if (FAILED(rc)) throw rc;
1530
1531 Bstr bstrNewMachineId;
1532 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
1533 if (FAILED(rc)) throw rc;
1534
1535 // store new machine for roll-back in case of errors
1536 stack.llMachinesRegistered.push_back(bstrNewMachineId);
1537
1538 // Add floppies and CD-ROMs to the appropriate controllers.
1539 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1540 if (vsdeFloppy.size() > 1)
1541 throw setError(VBOX_E_FILE_ERROR,
1542 tr("Too many floppy controllers in OVF; import facility only supports one"));
1543 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1544 if ( (vsdeFloppy.size() > 0)
1545 || (vsdeCDROM.size() > 0)
1546 )
1547 {
1548 // If there's an error here we need to close the session, so
1549 // we need another try/catch block.
1550
1551 try
1552 {
1553 /* In order to attach things we need to open a session
1554 * for the new machine */
1555 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1556 if (FAILED(rc)) throw rc;
1557 stack.fSessionOpen = true;
1558
1559 ComPtr<IMachine> sMachine;
1560 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1561 if (FAILED(rc)) throw rc;
1562
1563 // floppy first
1564 if (vsdeFloppy.size() == 1)
1565 {
1566 ComPtr<IStorageController> pController;
1567 rc = sMachine->AddStorageController(Bstr("Floppy Controller"), StorageBus_Floppy, pController.asOutParam());
1568 if (FAILED(rc)) throw rc;
1569
1570 Bstr bstrName;
1571 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1572 if (FAILED(rc)) throw rc;
1573
1574 // this is for rollback later
1575 MyHardDiskAttachment mhda;
1576 mhda.bstrUuid = bstrNewMachineId;
1577 mhda.pMachine = pNewMachine;
1578 mhda.controllerType = bstrName;
1579 mhda.lChannel = 0;
1580 mhda.lDevice = 0;
1581
1582 Log(("Attaching floppy\n"));
1583
1584 rc = sMachine->AttachDevice(mhda.controllerType,
1585 mhda.lChannel,
1586 mhda.lDevice,
1587 DeviceType_Floppy,
1588 NULL);
1589 if (FAILED(rc)) throw rc;
1590
1591 stack.llHardDiskAttachments.push_back(mhda);
1592 }
1593
1594
1595 // CD-ROMs next
1596 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
1597 jt != vsdeCDROM.end();
1598 ++jt)
1599 {
1600 // for now always attach to secondary master on IDE controller;
1601 // there seems to be no useful information in OVF where else to
1602 // attach jt (@todo test with latest versions of OVF software)
1603
1604 // find the IDE controller
1605 const ovf::HardDiskController *pController = NULL;
1606 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
1607 kt != vsysThis.mapControllers.end();
1608 ++kt)
1609 {
1610 if (kt->second.system == ovf::HardDiskController::IDE)
1611 {
1612 pController = &kt->second;
1613 }
1614 }
1615
1616 if (!pController)
1617 throw setError(VBOX_E_FILE_ERROR,
1618 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
1619
1620 // this is for rollback later
1621 MyHardDiskAttachment mhda;
1622 mhda.bstrUuid = bstrNewMachineId;
1623 mhda.pMachine = pNewMachine;
1624
1625 convertDiskAttachmentValues(*pController,
1626 2, // interpreted as secondary master
1627 mhda.controllerType, // Bstr
1628 mhda.lChannel,
1629 mhda.lDevice);
1630
1631 Log(("Attaching CD-ROM to channel %d on device %d\n", mhda.lChannel, mhda.lDevice));
1632
1633 rc = sMachine->AttachDevice(mhda.controllerType,
1634 mhda.lChannel,
1635 mhda.lDevice,
1636 DeviceType_DVD,
1637 NULL);
1638 if (FAILED(rc)) throw rc;
1639
1640 stack.llHardDiskAttachments.push_back(mhda);
1641 } // end for (itHD = avsdeHDs.begin();
1642
1643 rc = sMachine->SaveSettings();
1644 if (FAILED(rc)) throw rc;
1645
1646 // only now that we're done with all disks, close the session
1647 rc = stack.pSession->Close();
1648 if (FAILED(rc)) throw rc;
1649 stack.fSessionOpen = false;
1650 }
1651 catch(HRESULT /* aRC */)
1652 {
1653 if (stack.fSessionOpen)
1654 stack.pSession->Close();
1655
1656 throw;
1657 }
1658 }
1659
1660 /* Create the hard disks & connect them to the appropriate controllers. */
1661 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1662 if (avsdeHDs.size() > 0)
1663 {
1664 // If there's an error here we need to close the session, so
1665 // we need another try/catch block.
1666 ComPtr<IMedium> srcHdVBox;
1667 bool fSourceHdNeedsClosing = false;
1668
1669 try
1670 {
1671 /* In order to attach hard disks we need to open a session
1672 * for the new machine */
1673 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1674 if (FAILED(rc)) throw rc;
1675 stack.fSessionOpen = true;
1676
1677 /* The disk image has to be on the same place as the OVF file. So
1678 * strip the filename out of the full file path. */
1679 Utf8Str strSrcDir(stack.locInfo.strPath);
1680 strSrcDir.stripFilename();
1681
1682 /* Iterate over all given disk images */
1683 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1684 for (itHD = avsdeHDs.begin();
1685 itHD != avsdeHDs.end();
1686 ++itHD)
1687 {
1688 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1689
1690 /* Check if the destination file exists already or the
1691 * destination path is empty. */
1692 if ( vsdeHD->strVbox.isEmpty()
1693 || RTPathExists(vsdeHD->strVbox.c_str())
1694 )
1695 /* This isn't allowed */
1696 throw setError(VBOX_E_FILE_ERROR,
1697 tr("Destination file '%s' exists",
1698 vsdeHD->strVbox.c_str()));
1699
1700 /* Find the disk from the OVF's disk list */
1701 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
1702 /* vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1703 in the virtual system's disks map under that ID and also in the global images map. */
1704 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1705
1706 if ( itDiskImage == stack.mapDisks.end()
1707 || itVirtualDisk == vsysThis.mapVirtualDisks.end()
1708 )
1709 throw setError(E_FAIL,
1710 tr("Internal inconsistency looking up disk images."));
1711
1712 const ovf::DiskImage &di = itDiskImage->second;
1713 const ovf::VirtualDisk &vd = itVirtualDisk->second;
1714
1715 /* Make sure all target directories exists */
1716 rc = VirtualBox::ensureFilePathExists(vsdeHD->strVbox.c_str());
1717 if (FAILED(rc))
1718 throw rc;
1719
1720 // subprogress object for hard disk
1721 ComPtr<IProgress> pProgress2;
1722
1723 ComPtr<IMedium> dstHdVBox;
1724 /* If strHref is empty we have to create a new file */
1725 if (di.strHref.isEmpty())
1726 {
1727 /* Which format to use? */
1728 Bstr srcFormat = L"VDI";
1729 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1730 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive))
1731 srcFormat = L"VMDK";
1732 /* Create an empty hard disk */
1733 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(vsdeHD->strVbox), dstHdVBox.asOutParam());
1734 if (FAILED(rc)) throw rc;
1735
1736 /* Create a dynamic growing disk image with the given capacity */
1737 rc = dstHdVBox->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1738 if (FAILED(rc)) throw rc;
1739
1740 /* Advance to the next operation */
1741 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating virtual disk image '%s'"), vsdeHD->strVbox.c_str()),
1742 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally
1743 }
1744 else
1745 {
1746 /* Construct the source file path */
1747 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1748 /* Check if the source file exists */
1749 if (!RTPathExists(strSrcFilePath.c_str()))
1750 /* This isn't allowed */
1751 throw setError(VBOX_E_FILE_ERROR,
1752 tr("Source virtual disk image file '%s' doesn't exist"),
1753 strSrcFilePath.c_str());
1754
1755 /* Clone the disk image (this is necessary cause the id has
1756 * to be recreated for the case the same hard disk is
1757 * attached already from a previous import) */
1758
1759 /* First open the existing disk image */
1760 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1761 AccessMode_ReadOnly,
1762 false,
1763 NULL,
1764 false,
1765 NULL,
1766 srcHdVBox.asOutParam());
1767 if (FAILED(rc)) throw rc;
1768 fSourceHdNeedsClosing = true;
1769
1770 /* We need the format description of the source disk image */
1771 Bstr srcFormat;
1772 rc = srcHdVBox->COMGETTER(Format)(srcFormat.asOutParam());
1773 if (FAILED(rc)) throw rc;
1774 /* Create a new hard disk interface for the destination disk image */
1775 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(vsdeHD->strVbox), dstHdVBox.asOutParam());
1776 if (FAILED(rc)) throw rc;
1777 /* Clone the source disk image */
1778 rc = srcHdVBox->CloneTo(dstHdVBox, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1779 if (FAILED(rc)) throw rc;
1780
1781 /* Advance to the next operation */
1782 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1783 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally);
1784 }
1785
1786 // now wait for the background disk operation to complete; this throws HRESULTs on error
1787 waitForAsyncProgress(stack.pProgress, pProgress2);
1788
1789 if (fSourceHdNeedsClosing)
1790 {
1791 rc = srcHdVBox->Close();
1792 if (FAILED(rc)) throw rc;
1793 fSourceHdNeedsClosing = false;
1794 }
1795
1796 stack.llHardDisksCreated.push_back(dstHdVBox);
1797 /* Now use the new uuid to attach the disk image to our new machine */
1798 ComPtr<IMachine> sMachine;
1799 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1800 if (FAILED(rc)) throw rc;
1801 Bstr hdId;
1802 rc = dstHdVBox->COMGETTER(Id)(hdId.asOutParam());
1803 if (FAILED(rc)) throw rc;
1804
1805 /* For now we assume we have one controller of every type only */
1806 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(vd.idController)).second;
1807
1808 // this is for rollback later
1809 MyHardDiskAttachment mhda;
1810 mhda.bstrUuid = bstrNewMachineId;
1811 mhda.pMachine = pNewMachine;
1812
1813 convertDiskAttachmentValues(hdc,
1814 vd.ulAddressOnParent,
1815 mhda.controllerType, // Bstr
1816 mhda.lChannel,
1817 mhda.lDevice);
1818
1819 Log(("Attaching disk %s to channel %d on device %d\n", vsdeHD->strVbox.c_str(), mhda.lChannel, mhda.lDevice));
1820
1821 rc = sMachine->AttachDevice(mhda.controllerType,
1822 mhda.lChannel,
1823 mhda.lDevice,
1824 DeviceType_HardDisk,
1825 hdId);
1826 if (FAILED(rc)) throw rc;
1827
1828 stack.llHardDiskAttachments.push_back(mhda);
1829
1830 rc = sMachine->SaveSettings();
1831 if (FAILED(rc)) throw rc;
1832 } // end for (itHD = avsdeHDs.begin();
1833
1834 // only now that we're done with all disks, close the session
1835 rc = stack.pSession->Close();
1836 if (FAILED(rc)) throw rc;
1837 stack.fSessionOpen = false;
1838 }
1839 catch(HRESULT /* aRC */)
1840 {
1841 if (fSourceHdNeedsClosing)
1842 srcHdVBox->Close();
1843
1844 if (stack.fSessionOpen)
1845 stack.pSession->Close();
1846
1847 throw;
1848 }
1849 }
1850}
1851
1852/**
1853 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
1854 * structure) into VirtualBox by creating an IMachine instance, which is returned.
1855 *
1856 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1857 * up any leftovers from this function. For this, the given ImportStack instance has received information
1858 * about what needs cleaning up (to support rollback).
1859 *
1860 * @param config
1861 * @param pNewMachine
1862 * @param stack
1863 */
1864void Appliance::importVBoxMachine(const settings::MachineConfigFile &config,
1865 ComPtr<IMachine> &pNewMachine,
1866 ImportStack &stack)
1867{
1868}
1869
1870/**
1871 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
1872 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
1873 * thread to import from temporary files (see Appliance::importFS()).
1874 * @param pTask
1875 * @return
1876 */
1877HRESULT Appliance::importS3(TaskOVF *pTask)
1878{
1879 LogFlowFuncEnter();
1880 LogFlowFunc(("Appliance %p\n", this));
1881
1882 AutoCaller autoCaller(this);
1883 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1884
1885 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1886
1887 int vrc = VINF_SUCCESS;
1888 RTS3 hS3 = NIL_RTS3;
1889 char szOSTmpDir[RTPATH_MAX];
1890 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1891 /* The template for the temporary directory created below */
1892 char *pszTmpDir;
1893 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
1894 list< pair<Utf8Str, ULONG> > filesList;
1895
1896 HRESULT rc = S_OK;
1897 try
1898 {
1899 /* Extract the bucket */
1900 Utf8Str tmpPath = pTask->locInfo.strPath;
1901 Utf8Str bucket;
1902 parseBucket(tmpPath, bucket);
1903
1904 /* We need a temporary directory which we can put the all disk images
1905 * in */
1906 vrc = RTDirCreateTemp(pszTmpDir);
1907 if (RT_FAILURE(vrc))
1908 throw setError(VBOX_E_FILE_ERROR,
1909 tr("Cannot create temporary directory '%s'"), pszTmpDir);
1910
1911 /* Add every disks of every virtual system to an internal list */
1912 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1913 for (it = m->virtualSystemDescriptions.begin();
1914 it != m->virtualSystemDescriptions.end();
1915 ++it)
1916 {
1917 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1918 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1919 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1920 for (itH = avsdeHDs.begin();
1921 itH != avsdeHDs.end();
1922 ++itH)
1923 {
1924 const Utf8Str &strTargetFile = (*itH)->strOvf;
1925 if (!strTargetFile.isEmpty())
1926 {
1927 /* The temporary name of the target disk file */
1928 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
1929 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1930 }
1931 }
1932 }
1933
1934 /* Next we have to download the disk images */
1935 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1936 if (RT_FAILURE(vrc))
1937 throw setError(VBOX_E_IPRT_ERROR,
1938 tr("Cannot create S3 service handler"));
1939 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1940
1941 /* Download all files */
1942 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1943 {
1944 const pair<Utf8Str, ULONG> &s = (*it1);
1945 const Utf8Str &strSrcFile = s.first;
1946 /* Construct the source file name */
1947 char *pszFilename = RTPathFilename(strSrcFile.c_str());
1948 /* Advance to the next operation */
1949 if (!pTask->pProgress.isNull())
1950 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), s.second);
1951
1952 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
1953 if (RT_FAILURE(vrc))
1954 {
1955 if (vrc == VERR_S3_CANCELED)
1956 throw S_OK; /* todo: !!!!!!!!!!!!! */
1957 else if (vrc == VERR_S3_ACCESS_DENIED)
1958 throw setError(E_ACCESSDENIED,
1959 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);
1960 else if (vrc == VERR_S3_NOT_FOUND)
1961 throw setError(VBOX_E_FILE_ERROR,
1962 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1963 else
1964 throw setError(VBOX_E_IPRT_ERROR,
1965 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1966 }
1967 }
1968
1969 /* Provide a OVF file (haven't to exist) so the import routine can
1970 * figure out where the disk images/manifest file are located. */
1971 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1972 /* Now check if there is an manifest file. This is optional. */
1973 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
1974 char *pszFilename = RTPathFilename(strManifestFile.c_str());
1975 if (!pTask->pProgress.isNull())
1976 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
1977
1978 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
1979 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
1980 if (RT_SUCCESS(vrc))
1981 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
1982 else if (RT_FAILURE(vrc))
1983 {
1984 if (vrc == VERR_S3_CANCELED)
1985 throw S_OK; /* todo: !!!!!!!!!!!!! */
1986 else if (vrc == VERR_S3_NOT_FOUND)
1987 vrc = VINF_SUCCESS; /* Not found is ok */
1988 else if (vrc == VERR_S3_ACCESS_DENIED)
1989 throw setError(E_ACCESSDENIED,
1990 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);
1991 else
1992 throw setError(VBOX_E_IPRT_ERROR,
1993 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1994 }
1995
1996 /* Close the connection early */
1997 RTS3Destroy(hS3);
1998 hS3 = NIL_RTS3;
1999
2000 if (!pTask->pProgress.isNull())
2001 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightPerOperation);
2002
2003 ComObjPtr<Progress> progress;
2004 /* Import the whole temporary OVF & the disk images */
2005 LocationInfo li;
2006 li.strPath = strTmpOvf;
2007 rc = importImpl(li, progress);
2008 if (FAILED(rc)) throw rc;
2009
2010 /* Unlock the appliance for the fs import thread */
2011 appLock.release();
2012 /* Wait until the import is done, but report the progress back to the
2013 caller */
2014 ComPtr<IProgress> progressInt(progress);
2015 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2016
2017 /* Again lock the appliance for the next steps */
2018 appLock.acquire();
2019 }
2020 catch(HRESULT aRC)
2021 {
2022 rc = aRC;
2023 }
2024 /* Cleanup */
2025 RTS3Destroy(hS3);
2026 /* Delete all files which where temporary created */
2027 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2028 {
2029 const char *pszFilePath = (*it1).first.c_str();
2030 if (RTPathExists(pszFilePath))
2031 {
2032 vrc = RTFileDelete(pszFilePath);
2033 if (RT_FAILURE(vrc))
2034 rc = setError(VBOX_E_FILE_ERROR,
2035 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2036 }
2037 }
2038 /* Delete the temporary directory */
2039 if (RTPathExists(pszTmpDir))
2040 {
2041 vrc = RTDirRemove(pszTmpDir);
2042 if (RT_FAILURE(vrc))
2043 rc = setError(VBOX_E_FILE_ERROR,
2044 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2045 }
2046 if (pszTmpDir)
2047 RTStrFree(pszTmpDir);
2048
2049 LogFlowFunc(("rc=%Rhrc\n", rc));
2050 LogFlowFuncLeave();
2051
2052 return rc;
2053}
2054
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