VirtualBox

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

Last change on this file since 33438 was 33424, checked in by vboxsync, 14 years ago

Main-OVF: Allow overriding of the target disk path when there is some vbox.xml also.

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

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