VirtualBox

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

Last change on this file since 33595 was 33567, checked in by vboxsync, 14 years ago

VD: Move the generic virtual disk framework + backends to src/VBox/Storage and rename the files to get rid of the HDD part because it supports floppy and DVD images too

  • 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 33567 2010-10-28 15:37:21Z 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/vd.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 = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
877 list< pair<Utf8Str, ULONG> > filesList;
878 Utf8Str strTmpOvf;
879
880 try
881 {
882 /* Extract the bucket */
883 Utf8Str tmpPath = pTask->locInfo.strPath;
884 Utf8Str bucket;
885 parseBucket(tmpPath, bucket);
886
887 /* We need a temporary directory which we can put the OVF file & all
888 * disk images in */
889 vrc = RTDirCreateTemp(pszTmpDir);
890 if (RT_FAILURE(vrc))
891 throw setError(VBOX_E_FILE_ERROR,
892 tr("Cannot create temporary directory '%s'"), pszTmpDir);
893
894 /* The temporary name of the target OVF file */
895 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
896
897 /* Next we have to download the OVF */
898 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
899 if (RT_FAILURE(vrc))
900 throw setError(VBOX_E_IPRT_ERROR,
901 tr("Cannot create S3 service handler"));
902 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
903
904 /* Get it */
905 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
906 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
907 if (RT_FAILURE(vrc))
908 {
909 if (vrc == VERR_S3_CANCELED)
910 throw S_OK; /* todo: !!!!!!!!!!!!! */
911 else if (vrc == VERR_S3_ACCESS_DENIED)
912 throw setError(E_ACCESSDENIED,
913 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right."
914 "Also check that your host clock is properly synced"),
915 pszFilename);
916 else if (vrc == VERR_S3_NOT_FOUND)
917 throw setError(VBOX_E_FILE_ERROR,
918 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
919 else
920 throw setError(VBOX_E_IPRT_ERROR,
921 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
922 }
923
924 /* Close the connection early */
925 RTS3Destroy(hS3);
926 hS3 = NIL_RTS3;
927
928 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")).raw(), 1);
929
930 /* Prepare the temporary reading of the OVF */
931 ComObjPtr<Progress> progress;
932 LocationInfo li;
933 li.strPath = strTmpOvf;
934 /* Start the reading from the fs */
935 rc = readImpl(li, progress);
936 if (FAILED(rc)) throw rc;
937
938 /* Unlock the appliance for the reading thread */
939 appLock.release();
940 /* Wait until the reading is done, but report the progress back to the
941 caller */
942 ComPtr<IProgress> progressInt(progress);
943 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
944
945 /* Again lock the appliance for the next steps */
946 appLock.acquire();
947 }
948 catch(HRESULT aRC)
949 {
950 rc = aRC;
951 }
952 /* Cleanup */
953 RTS3Destroy(hS3);
954 /* Delete all files which where temporary created */
955 if (RTPathExists(strTmpOvf.c_str()))
956 {
957 vrc = RTFileDelete(strTmpOvf.c_str());
958 if (RT_FAILURE(vrc))
959 rc = setError(VBOX_E_FILE_ERROR,
960 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
961 }
962 /* Delete the temporary directory */
963 if (RTPathExists(pszTmpDir))
964 {
965 vrc = RTDirRemove(pszTmpDir);
966 if (RT_FAILURE(vrc))
967 rc = setError(VBOX_E_FILE_ERROR,
968 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
969 }
970 if (pszTmpDir)
971 RTStrFree(pszTmpDir);
972
973 LogFlowFunc(("rc=%Rhrc\n", rc));
974 LogFlowFuncLeave();
975
976 return rc;
977}
978
979/*******************************************************************************
980 * Import stuff
981 ******************************************************************************/
982
983/**
984 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
985 * Appliance::taskThreadImportOrExport().
986 *
987 * This creates one or more new machines according to the VirtualSystemScription instances created by
988 * Appliance::Interpret().
989 *
990 * This is in a separate private method because it is used from two locations:
991 *
992 * 1) from the public Appliance::ImportMachines().
993 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
994 *
995 * @param aLocInfo
996 * @param aProgress
997 * @return
998 */
999HRESULT Appliance::importImpl(const LocationInfo &locInfo,
1000 ComObjPtr<Progress> &progress)
1001{
1002 HRESULT rc = S_OK;
1003
1004 SetUpProgressMode mode;
1005 if (locInfo.storageType == VFSType_File)
1006 mode = ImportFile;
1007 else
1008 mode = ImportS3;
1009
1010 rc = setUpProgress(progress,
1011 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1012 mode);
1013 if (FAILED(rc)) throw rc;
1014
1015 /* Initialize our worker task */
1016 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, locInfo, progress));
1017
1018 rc = task->startThread();
1019 if (FAILED(rc)) throw rc;
1020
1021 /* Don't destruct on success */
1022 task.release();
1023
1024 return rc;
1025}
1026
1027/**
1028 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1029 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1030 * VirtualSystemScription instances created by Appliance::Interpret().
1031 *
1032 * This runs in three contexts:
1033 *
1034 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1035 *
1036 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1037 * called Appliance::importFSOVA(), which called Appliance::importImpl(), which then called this again.
1038 *
1039 * 3) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1040 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this again.
1041 *
1042 * @param pTask
1043 * @return
1044 */
1045HRESULT Appliance::importFS(TaskOVF *pTask)
1046{
1047
1048 LogFlowFuncEnter();
1049 LogFlowFunc(("Appliance %p\n", this));
1050
1051 AutoCaller autoCaller(this);
1052 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1053
1054 /* Change the appliance state so we can safely leave the lock while doing
1055 * time-consuming disk imports; also the below method calls do all kinds of
1056 * locking which conflicts with the appliance object lock. */
1057 AutoWriteLock writeLock(this COMMA_LOCKVAL_SRC_POS);
1058 /* Check if the appliance is currently busy. */
1059 if (!isApplianceIdle())
1060 return E_ACCESSDENIED;
1061 /* Set the internal state to importing. */
1062 m->state = Data::ApplianceImporting;
1063
1064 HRESULT rc = S_OK;
1065
1066 /* Clear the list of imported machines, if any */
1067 m->llGuidsMachinesCreated.clear();
1068
1069 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1070 rc = importFSOVF(pTask, writeLock);
1071 else
1072 rc = importFSOVA(pTask, writeLock);
1073
1074 if (FAILED(rc))
1075 {
1076 /* With _whatever_ error we've had, do a complete roll-back of
1077 * machines and disks we've created */
1078 writeLock.release();
1079 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
1080 itID != m->llGuidsMachinesCreated.end();
1081 ++itID)
1082 {
1083 Guid guid = *itID;
1084 Bstr bstrGuid = guid.toUtf16();
1085 ComPtr<IMachine> failedMachine;
1086 HRESULT rc2 = mVirtualBox->FindMachine(bstrGuid.raw(), failedMachine.asOutParam());
1087 if (SUCCEEDED(rc2))
1088 {
1089 SafeIfaceArray<IMedium> aMedia;
1090 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
1091 ComPtr<IProgress> pProgress2;
1092 rc2 = failedMachine->Delete(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
1093 pProgress2->WaitForCompletion(-1);
1094 }
1095 }
1096 writeLock.acquire();
1097 }
1098
1099 /* Reset the state so others can call methods again */
1100 m->state = Data::ApplianceIdle;
1101
1102 LogFlowFunc(("rc=%Rhrc\n", rc));
1103 LogFlowFuncLeave();
1104
1105 return rc;
1106}
1107
1108HRESULT Appliance::importFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1109{
1110 LogFlowFuncEnter();
1111
1112 HRESULT rc = S_OK;
1113
1114 PVDINTERFACEIO pSha1Callbacks = 0;
1115 PVDINTERFACEIO pRTFileCallbacks = 0;
1116 void *pvMfBuf = 0;
1117 writeLock.release();
1118 try
1119 {
1120 /* Create the necessary file access interfaces. */
1121 pSha1Callbacks = Sha1CreateInterface();
1122 if (!pSha1Callbacks)
1123 throw E_OUTOFMEMORY;
1124 pRTFileCallbacks = RTFileCreateInterface();
1125 if (!pRTFileCallbacks)
1126 throw E_OUTOFMEMORY;
1127
1128 VDINTERFACE VDInterfaceIO;
1129 SHA1STORAGE storage;
1130 RT_ZERO(storage);
1131 storage.fCreateDigest = true;
1132 int vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IORTFile",
1133 VDINTERFACETYPE_IO, pRTFileCallbacks,
1134 0, &storage.pVDImageIfaces);
1135 if (RT_FAILURE(vrc))
1136 throw E_FAIL;
1137
1138 size_t cbMfSize = 0;
1139 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1140 /* Create the import stack for the rollback on errors. */
1141 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1142 /* Do we need the digest information? */
1143 storage.fCreateDigest = RTFileExists(strMfFile.c_str());
1144 /* Now import the appliance. */
1145 importMachines(stack, pSha1Callbacks, &storage);
1146 /* Read & verify the manifest file, if there is one. */
1147 if (storage.fCreateDigest)
1148 {
1149 /* Add the ovf file to the digest list. */
1150 stack.llSrcDisksDigest.push_front(STRPAIR(pTask->locInfo.strPath, m->strOVFSHA1Digest));
1151 rc = readManifestFile(strMfFile, &pvMfBuf, &cbMfSize, pSha1Callbacks, &storage);
1152 if (FAILED(rc)) throw rc;
1153 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1154 if (FAILED(rc)) throw rc;
1155 }
1156 }
1157 catch (HRESULT rc2)
1158 {
1159 rc = rc2;
1160 }
1161 writeLock.acquire();
1162
1163 /* Cleanup */
1164 if (pvMfBuf)
1165 RTMemFree(pvMfBuf);
1166 if (pSha1Callbacks)
1167 RTMemFree(pSha1Callbacks);
1168 if (pRTFileCallbacks)
1169 RTMemFree(pRTFileCallbacks);
1170
1171 LogFlowFunc(("rc=%Rhrc\n", rc));
1172 LogFlowFuncLeave();
1173
1174 return rc;
1175}
1176
1177HRESULT Appliance::importFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1178{
1179 LogFlowFuncEnter();
1180
1181 RTTAR tar;
1182 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, true);
1183 if (RT_FAILURE(vrc))
1184 return setError(VBOX_E_FILE_ERROR,
1185 tr("Could not open OVA file '%s' (%Rrc)"),
1186 pTask->locInfo.strPath.c_str(), vrc);
1187
1188 HRESULT rc = S_OK;
1189
1190 PVDINTERFACEIO pSha1Callbacks = 0;
1191 PVDINTERFACEIO pRTTarCallbacks = 0;
1192 void *pvMfBuf = 0;
1193 writeLock.release();
1194 try
1195 {
1196 /* Create the necessary file access interfaces. */
1197 pSha1Callbacks = Sha1CreateInterface();
1198 if (!pSha1Callbacks)
1199 throw E_OUTOFMEMORY;
1200 pRTTarCallbacks = RTTarCreateInterface();
1201 if (!pRTTarCallbacks)
1202 throw E_OUTOFMEMORY;
1203
1204 VDINTERFACE VDInterfaceIO;
1205 SHA1STORAGE storage;
1206 RT_ZERO(storage);
1207 vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IORTTar",
1208 VDINTERFACETYPE_IO, pRTTarCallbacks,
1209 tar, &storage.pVDImageIfaces);
1210 if (RT_FAILURE(vrc))
1211 throw E_FAIL;
1212
1213 /* Skip the OVF file, cause this was read in IAppliance::Read already. */
1214 vrc = RTTarSeekNextFile(tar);
1215 if (RT_FAILURE(vrc))
1216 /* Better error .... no unusual error */
1217 throw E_FAIL;
1218
1219 PVDINTERFACEIO pCallbacks = pSha1Callbacks;
1220 PSHA1STORAGE pStorage = &storage;
1221
1222 /* We always need to create the digest, cause we didn't know if there
1223 * is a manifest file in the stream. */
1224 pStorage->fCreateDigest = true;
1225
1226 size_t cbMfSize = 0;
1227 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1228 /* Create the import stack for the rollback on errors. */
1229 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1230 /*
1231 * Try to read the manifest file. First try.
1232 *
1233 * Note: This isn't fatal if the file is not found. The standard
1234 * defines 3 cases.
1235 * 1. no manifest file
1236 * 2. manifest file after the OVF file
1237 * 3. manifest file after all disk files
1238 * If we want streaming capabilities, we can't check if it is there by
1239 * searching for it. We have to try to open it on all possible places.
1240 * If it fails here, we will try it again after all disks where read.
1241 */
1242 rc = readTarManifestFile(tar, strMfFile, &pvMfBuf, &cbMfSize, pCallbacks, pStorage);
1243 if (FAILED(rc)) throw rc;
1244 /* Now import the appliance. */
1245 importMachines(stack, pCallbacks, pStorage);
1246 /* Try to read the manifest file. Second try. */
1247 if (!pvMfBuf)
1248 {
1249 rc = readTarManifestFile(tar, strMfFile, &pvMfBuf, &cbMfSize, pCallbacks, pStorage);
1250 if (FAILED(rc)) throw rc;
1251 }
1252 /* If we were able to read a manifest file we can check it now. */
1253 if (pvMfBuf)
1254 {
1255 /* Add the ovf file to the digest list. */
1256 stack.llSrcDisksDigest.push_front(STRPAIR(Utf8Str(pTask->locInfo.strPath).stripExt().append(".ovf"), m->strOVFSHA1Digest));
1257 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1258 if (FAILED(rc)) throw rc;
1259 }
1260 }
1261 catch (HRESULT rc2)
1262 {
1263 rc = rc2;
1264 }
1265 writeLock.acquire();
1266
1267 RTTarClose(tar);
1268
1269 /* Cleanup */
1270 if (pvMfBuf)
1271 RTMemFree(pvMfBuf);
1272 if (pSha1Callbacks)
1273 RTMemFree(pSha1Callbacks);
1274 if (pRTTarCallbacks)
1275 RTMemFree(pRTTarCallbacks);
1276
1277 LogFlowFunc(("rc=%Rhrc\n", rc));
1278 LogFlowFuncLeave();
1279
1280 return rc;
1281}
1282
1283/**
1284 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
1285 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
1286 * thread to import from temporary files (see Appliance::importFS()).
1287 * @param pTask
1288 * @return
1289 */
1290HRESULT Appliance::importS3(TaskOVF *pTask)
1291{
1292 LogFlowFuncEnter();
1293 LogFlowFunc(("Appliance %p\n", this));
1294
1295 AutoCaller autoCaller(this);
1296 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1297
1298 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1299
1300 int vrc = VINF_SUCCESS;
1301 RTS3 hS3 = NIL_RTS3;
1302 char szOSTmpDir[RTPATH_MAX];
1303 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1304 /* The template for the temporary directory created below */
1305 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1306 list< pair<Utf8Str, ULONG> > filesList;
1307
1308 HRESULT rc = S_OK;
1309 try
1310 {
1311 /* Extract the bucket */
1312 Utf8Str tmpPath = pTask->locInfo.strPath;
1313 Utf8Str bucket;
1314 parseBucket(tmpPath, bucket);
1315
1316 /* We need a temporary directory which we can put the all disk images
1317 * in */
1318 vrc = RTDirCreateTemp(pszTmpDir);
1319 if (RT_FAILURE(vrc))
1320 throw setError(VBOX_E_FILE_ERROR,
1321 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1322
1323 /* Add every disks of every virtual system to an internal list */
1324 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1325 for (it = m->virtualSystemDescriptions.begin();
1326 it != m->virtualSystemDescriptions.end();
1327 ++it)
1328 {
1329 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1330 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1331 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1332 for (itH = avsdeHDs.begin();
1333 itH != avsdeHDs.end();
1334 ++itH)
1335 {
1336 const Utf8Str &strTargetFile = (*itH)->strOvf;
1337 if (!strTargetFile.isEmpty())
1338 {
1339 /* The temporary name of the target disk file */
1340 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
1341 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1342 }
1343 }
1344 }
1345
1346 /* Next we have to download the disk images */
1347 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1348 if (RT_FAILURE(vrc))
1349 throw setError(VBOX_E_IPRT_ERROR,
1350 tr("Cannot create S3 service handler"));
1351 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1352
1353 /* Download all files */
1354 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1355 {
1356 const pair<Utf8Str, ULONG> &s = (*it1);
1357 const Utf8Str &strSrcFile = s.first;
1358 /* Construct the source file name */
1359 char *pszFilename = RTPathFilename(strSrcFile.c_str());
1360 /* Advance to the next operation */
1361 if (!pTask->pProgress.isNull())
1362 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), s.second);
1363
1364 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
1365 if (RT_FAILURE(vrc))
1366 {
1367 if (vrc == VERR_S3_CANCELED)
1368 throw S_OK; /* todo: !!!!!!!!!!!!! */
1369 else if (vrc == VERR_S3_ACCESS_DENIED)
1370 throw setError(E_ACCESSDENIED,
1371 tr("Cannot download file '%s' from S3 storage server (Access denied). "
1372 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
1373 pszFilename);
1374 else if (vrc == VERR_S3_NOT_FOUND)
1375 throw setError(VBOX_E_FILE_ERROR,
1376 tr("Cannot download file '%s' from S3 storage server (File not found)"),
1377 pszFilename);
1378 else
1379 throw setError(VBOX_E_IPRT_ERROR,
1380 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1381 pszFilename, vrc);
1382 }
1383 }
1384
1385 /* Provide a OVF file (haven't to exist) so the import routine can
1386 * figure out where the disk images/manifest file are located. */
1387 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1388 /* Now check if there is an manifest file. This is optional. */
1389 Utf8Str strManifestFile; //= queryManifestFileName(strTmpOvf);
1390// Utf8Str strManifestFile = queryManifestFileName(strTmpOvf);
1391 char *pszFilename = RTPathFilename(strManifestFile.c_str());
1392 if (!pTask->pProgress.isNull())
1393 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), 1);
1394
1395 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
1396 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
1397 if (RT_SUCCESS(vrc))
1398 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
1399 else if (RT_FAILURE(vrc))
1400 {
1401 if (vrc == VERR_S3_CANCELED)
1402 throw S_OK; /* todo: !!!!!!!!!!!!! */
1403 else if (vrc == VERR_S3_NOT_FOUND)
1404 vrc = VINF_SUCCESS; /* Not found is ok */
1405 else if (vrc == VERR_S3_ACCESS_DENIED)
1406 throw setError(E_ACCESSDENIED,
1407 tr("Cannot download file '%s' from S3 storage server (Access denied)."
1408 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
1409 pszFilename);
1410 else
1411 throw setError(VBOX_E_IPRT_ERROR,
1412 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1413 pszFilename, vrc);
1414 }
1415
1416 /* Close the connection early */
1417 RTS3Destroy(hS3);
1418 hS3 = NIL_RTS3;
1419
1420 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")).raw(), m->ulWeightForXmlOperation);
1421
1422 ComObjPtr<Progress> progress;
1423 /* Import the whole temporary OVF & the disk images */
1424 LocationInfo li;
1425 li.strPath = strTmpOvf;
1426 rc = importImpl(li, progress);
1427 if (FAILED(rc)) throw rc;
1428
1429 /* Unlock the appliance for the fs import thread */
1430 appLock.release();
1431 /* Wait until the import is done, but report the progress back to the
1432 caller */
1433 ComPtr<IProgress> progressInt(progress);
1434 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1435
1436 /* Again lock the appliance for the next steps */
1437 appLock.acquire();
1438 }
1439 catch(HRESULT aRC)
1440 {
1441 rc = aRC;
1442 }
1443 /* Cleanup */
1444 RTS3Destroy(hS3);
1445 /* Delete all files which where temporary created */
1446 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1447 {
1448 const char *pszFilePath = (*it1).first.c_str();
1449 if (RTPathExists(pszFilePath))
1450 {
1451 vrc = RTFileDelete(pszFilePath);
1452 if (RT_FAILURE(vrc))
1453 rc = setError(VBOX_E_FILE_ERROR,
1454 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
1455 }
1456 }
1457 /* Delete the temporary directory */
1458 if (RTPathExists(pszTmpDir))
1459 {
1460 vrc = RTDirRemove(pszTmpDir);
1461 if (RT_FAILURE(vrc))
1462 rc = setError(VBOX_E_FILE_ERROR,
1463 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1464 }
1465 if (pszTmpDir)
1466 RTStrFree(pszTmpDir);
1467
1468 LogFlowFunc(("rc=%Rhrc\n", rc));
1469 LogFlowFuncLeave();
1470
1471 return rc;
1472}
1473
1474HRESULT Appliance::readManifestFile(const Utf8Str &strFile, void **ppvBuf, size_t *pcbSize, PVDINTERFACEIO pCallbacks, PSHA1STORAGE pStorage)
1475{
1476 HRESULT rc = S_OK;
1477
1478 bool fOldDigest = pStorage->fCreateDigest;
1479 pStorage->fCreateDigest = false; /* No digest for the manifest file */
1480 int vrc = Sha1ReadBuf(strFile.c_str(), ppvBuf, pcbSize, pCallbacks, pStorage);
1481 if ( RT_FAILURE(vrc)
1482 && vrc != VERR_FILE_NOT_FOUND)
1483 rc = setError(VBOX_E_FILE_ERROR,
1484 tr("Could not read manifest file '%s' (%Rrc)"),
1485 RTPathFilename(strFile.c_str()), vrc);
1486 pStorage->fCreateDigest = fOldDigest; /* Restore the old digest creation behavior again. */
1487
1488 return rc;
1489}
1490
1491HRESULT Appliance::readTarManifestFile(RTTAR tar, const Utf8Str &strFile, void **ppvBuf, size_t *pcbSize, PVDINTERFACEIO pCallbacks, PSHA1STORAGE pStorage)
1492{
1493 HRESULT rc = S_OK;
1494
1495 char *pszCurFile;
1496 int vrc = RTTarCurrentFile(tar, &pszCurFile);
1497 if (RT_SUCCESS(vrc))
1498 {
1499 if (!strcmp(pszCurFile, RTPathFilename(strFile.c_str())))
1500 rc = readManifestFile(strFile, ppvBuf, pcbSize, pCallbacks, pStorage);
1501 RTStrFree(pszCurFile);
1502 }
1503 else if (vrc != VERR_TAR_END_OF_FILE)
1504 rc = E_FAIL;
1505
1506 return rc;
1507}
1508
1509HRESULT Appliance::verifyManifestFile(const Utf8Str &strFile, ImportStack &stack, void *pvBuf, size_t cbSize)
1510{
1511 HRESULT rc = S_OK;
1512
1513 PRTMANIFESTTEST paTests = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * stack.llSrcDisksDigest.size());
1514 if (!paTests)
1515 return E_OUTOFMEMORY;
1516
1517 size_t i = 0;
1518 list<STRPAIR>::const_iterator it1;
1519 for (it1 = stack.llSrcDisksDigest.begin();
1520 it1 != stack.llSrcDisksDigest.end();
1521 ++it1, ++i)
1522 {
1523 paTests[i].pszTestFile = (*it1).first.c_str();
1524 paTests[i].pszTestDigest = (*it1).second.c_str();
1525 }
1526 size_t iFailed;
1527 int vrc = RTManifestVerifyFilesBuf(pvBuf, cbSize, paTests, stack.llSrcDisksDigest.size(), &iFailed);
1528 if (RT_UNLIKELY(vrc == VERR_MANIFEST_DIGEST_MISMATCH))
1529 rc = setError(VBOX_E_FILE_ERROR,
1530 tr("The SHA1 digest of '%s' does not match the one in '%s' (%Rrc)"),
1531 RTPathFilename(paTests[iFailed].pszTestFile), RTPathFilename(strFile.c_str()), vrc);
1532 else if (RT_FAILURE(vrc))
1533 rc = setError(VBOX_E_FILE_ERROR,
1534 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1535 RTPathFilename(strFile.c_str()), vrc);
1536
1537 RTMemFree(paTests);
1538
1539 return rc;
1540}
1541
1542
1543/**
1544 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
1545 * Throws HRESULT values on errors!
1546 *
1547 * @param hdc in: the HardDiskController structure to attach to.
1548 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
1549 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
1550 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
1551 * @param lDevice out: the device number to attach to.
1552 */
1553void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
1554 uint32_t ulAddressOnParent,
1555 Bstr &controllerType,
1556 int32_t &lControllerPort,
1557 int32_t &lDevice)
1558{
1559 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n", hdc.system, hdc.fPrimary, ulAddressOnParent));
1560
1561 switch (hdc.system)
1562 {
1563 case ovf::HardDiskController::IDE:
1564 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
1565 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
1566 // the device number can be either 0 or 1, to specify the master or the slave device,
1567 // respectively. For the secondary IDE controller, the device number is always 1 because
1568 // the master device is reserved for the CD-ROM drive.
1569 controllerType = Bstr("IDE Controller");
1570 switch (ulAddressOnParent)
1571 {
1572 case 0: // master
1573 if (!hdc.fPrimary)
1574 {
1575 // secondary master
1576 lControllerPort = (long)1;
1577 lDevice = (long)0;
1578 }
1579 else // primary master
1580 {
1581 lControllerPort = (long)0;
1582 lDevice = (long)0;
1583 }
1584 break;
1585
1586 case 1: // slave
1587 if (!hdc.fPrimary)
1588 {
1589 // secondary slave
1590 lControllerPort = (long)1;
1591 lDevice = (long)1;
1592 }
1593 else // primary slave
1594 {
1595 lControllerPort = (long)0;
1596 lDevice = (long)1;
1597 }
1598 break;
1599
1600 // used by older VBox exports
1601 case 2: // interpret this as secondary master
1602 lControllerPort = (long)1;
1603 lDevice = (long)0;
1604 break;
1605
1606 // used by older VBox exports
1607 case 3: // interpret this as secondary slave
1608 lControllerPort = (long)1;
1609 lDevice = (long)1;
1610 break;
1611
1612 default:
1613 throw setError(VBOX_E_NOT_SUPPORTED,
1614 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
1615 ulAddressOnParent);
1616 break;
1617 }
1618 break;
1619
1620 case ovf::HardDiskController::SATA:
1621 controllerType = Bstr("SATA Controller");
1622 lControllerPort = (long)ulAddressOnParent;
1623 lDevice = (long)0;
1624 break;
1625
1626 case ovf::HardDiskController::SCSI:
1627 controllerType = Bstr("SCSI Controller");
1628 lControllerPort = (long)ulAddressOnParent;
1629 lDevice = (long)0;
1630 break;
1631
1632 default: break;
1633 }
1634
1635 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
1636}
1637
1638/**
1639 * Imports one disk image. This is common code shared between
1640 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1641 * the OVF virtual systems;
1642 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1643 * tag.
1644 *
1645 * Both ways of describing machines use the OVF disk references section, so in both cases
1646 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1647 *
1648 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1649 * spec, even though this cannot really happen in the vbox:Machine case since such data
1650 * would never have been exported.
1651 *
1652 * This advances stack.pProgress by one operation with the disk's weight.
1653 *
1654 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1655 * @param ulSizeMB Size of the disk image (for progress reporting)
1656 * @param strTargetPath Where to create the target image.
1657 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1658 * @param stack
1659 */
1660void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1661 const Utf8Str &strTargetPath,
1662 ComObjPtr<Medium> &pTargetHD,
1663 ImportStack &stack,
1664 PVDINTERFACEIO pCallbacks,
1665 PSHA1STORAGE pStorage)
1666{
1667 ComObjPtr<Progress> pProgress;
1668 pProgress.createObject();
1669 HRESULT rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetPath.c_str()).raw(), TRUE);
1670 if (FAILED(rc)) throw rc;
1671
1672 /* Get the system properties. */
1673 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
1674
1675 /* First of all check if the path is an UUID. If so, the user like to
1676 * import the disk into an existing path. This is useful for iSCSI for
1677 * example. */
1678 RTUUID uuid;
1679 int vrc = RTUuidFromStr(&uuid, strTargetPath.c_str());
1680 if (vrc == VINF_SUCCESS)
1681 {
1682 rc = mVirtualBox->findHardDiskById(Guid(uuid), true, &pTargetHD);
1683 if (FAILED(rc)) throw rc;
1684 }
1685 else
1686 {
1687 Utf8Str strTrgFormat = "VMDK";
1688 if (RTPathHaveExt(strTargetPath.c_str()))
1689 {
1690 char *pszExt = RTPathExt(strTargetPath.c_str());
1691 /* Figure out which format the user like to have. Default is VMDK. */
1692 ComObjPtr<MediumFormat> trgFormat = pSysProps->mediumFormatFromExtension(&pszExt[1]);
1693 if (trgFormat.isNull())
1694 throw setError(VBOX_E_NOT_SUPPORTED,
1695 tr("Could not find a valid medium format for the target disk '%s'"),
1696 strTargetPath.c_str());
1697 /* Check the capabilities. We need create capabilities. */
1698 ULONG lCabs = 0;
1699 rc = trgFormat->COMGETTER(Capabilities)(&lCabs);
1700 if (FAILED(rc)) throw rc;
1701 if (!( ((lCabs & MediumFormatCapabilities_CreateFixed) == MediumFormatCapabilities_CreateFixed)
1702 || ((lCabs & MediumFormatCapabilities_CreateDynamic) == MediumFormatCapabilities_CreateDynamic)))
1703 throw setError(VBOX_E_NOT_SUPPORTED,
1704 tr("Could not find a valid medium format for the target disk '%s'"),
1705 strTargetPath.c_str());
1706 Bstr bstrFormatName;
1707 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
1708 if (FAILED(rc)) throw rc;
1709 strTrgFormat = Utf8Str(bstrFormatName);
1710 }
1711
1712 bool fNeedsGlobalSaveSettings;
1713 /* Create an IMedium object. */
1714 pTargetHD.createObject();
1715 rc = pTargetHD->init(mVirtualBox,
1716 strTrgFormat,
1717 strTargetPath,
1718 Guid::Empty, // media registry
1719 &fNeedsGlobalSaveSettings);
1720 if (FAILED(rc)) throw rc;
1721
1722 /* Now create an empty hard disk. */
1723 rc = mVirtualBox->CreateHardDisk(NULL,
1724 Bstr(strTargetPath).raw(),
1725 ComPtr<IMedium>(pTargetHD).asOutParam());
1726 if (FAILED(rc)) throw rc;
1727 }
1728
1729 const Utf8Str &strSourceOVF = di.strHref;
1730 /* Construct source file path */
1731 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1732
1733 /* If strHref is empty we have to create a new file. */
1734 if (strSourceOVF.isEmpty())
1735 {
1736 /* Create a dynamic growing disk image with the given capacity. */
1737 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, ComPtr<IProgress>(pProgress).asOutParam());
1738 if (FAILED(rc)) throw rc;
1739
1740 /* Advance to the next operation. */
1741 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()).raw(),
1742 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1743 }
1744 else
1745 {
1746 /* We need a proper source format description */
1747 ComObjPtr<MediumFormat> srcFormat;
1748 /* Which format to use? */
1749 Utf8Str strSrcFormat = "VDI";
1750 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1751 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1752 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1753 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1754 )
1755 strSrcFormat = "VMDK";
1756 srcFormat = pSysProps->mediumFormat(strSrcFormat);
1757 if (srcFormat.isNull())
1758 throw setError(VBOX_E_NOT_SUPPORTED,
1759 tr("Could not find a valid medium format for the source disk '%s'"),
1760 RTPathFilename(strSrcFilePath.c_str()));
1761
1762 /* Clone the source disk image */
1763 ComObjPtr<Medium> nullParent;
1764 rc = pTargetHD->importFile(strSrcFilePath.c_str(),
1765 srcFormat,
1766 MediumVariant_Standard,
1767 pCallbacks, pStorage,
1768 nullParent,
1769 pProgress);
1770 if (FAILED(rc)) throw rc;
1771
1772 /* Advance to the next operation. */
1773 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), RTPathFilename(strSrcFilePath.c_str())).raw(),
1774 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1775 }
1776
1777 /* Now wait for the background disk operation to complete; this throws
1778 * HRESULTs on error. */
1779 ComPtr<IProgress> pp(pProgress);
1780 waitForAsyncProgress(stack.pProgress, pp);
1781
1782 /* Add the newly create disk path + a corresponding digest the our list for
1783 * later manifest verification. */
1784 stack.llSrcDisksDigest.push_back(STRPAIR(strSrcFilePath, pStorage->strDigest));
1785}
1786
1787/**
1788 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1789 * into VirtualBox by creating an IMachine instance, which is returned.
1790 *
1791 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1792 * up any leftovers from this function. For this, the given ImportStack instance has received information
1793 * about what needs cleaning up (to support rollback).
1794 *
1795 * @param vsysThis OVF virtual system (machine) to import.
1796 * @param vsdescThis Matching virtual system description (machine) to import.
1797 * @param pNewMachine out: Newly created machine.
1798 * @param stack Cleanup stack for when this throws.
1799 */
1800void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1801 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1802 ComPtr<IMachine> &pNewMachine,
1803 ImportStack &stack,
1804 PVDINTERFACEIO pCallbacks,
1805 PSHA1STORAGE pStorage)
1806{
1807 HRESULT rc;
1808
1809 // Get the instance of IGuestOSType which matches our string guest OS type so we
1810 // can use recommended defaults for the new machine where OVF doesn't provide any
1811 ComPtr<IGuestOSType> osType;
1812 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
1813 if (FAILED(rc)) throw rc;
1814
1815 /* Create the machine */
1816 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
1817 Bstr(stack.strNameVBox).raw(),
1818 Bstr(stack.strOsTypeVBox).raw(),
1819 NULL, /* uuid */
1820 FALSE, /* fForceOverwrite */
1821 pNewMachine.asOutParam());
1822 if (FAILED(rc)) throw rc;
1823
1824 // set the description
1825 if (!stack.strDescription.isEmpty())
1826 {
1827 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
1828 if (FAILED(rc)) throw rc;
1829 }
1830
1831 // CPU count
1832 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
1833 if (FAILED(rc)) throw rc;
1834
1835 if (stack.fForceHWVirt)
1836 {
1837 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1838 if (FAILED(rc)) throw rc;
1839 }
1840
1841 // RAM
1842 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
1843 if (FAILED(rc)) throw rc;
1844
1845 /* VRAM */
1846 /* Get the recommended VRAM for this guest OS type */
1847 ULONG vramVBox;
1848 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1849 if (FAILED(rc)) throw rc;
1850
1851 /* Set the VRAM */
1852 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1853 if (FAILED(rc)) throw rc;
1854
1855 // I/O APIC: Generic OVF has no setting for this. Enable it if we
1856 // import a Windows VM because if if Windows was installed without IOAPIC,
1857 // it will not mind finding an one later on, but if Windows was installed
1858 // _with_ an IOAPIC, it will bluescreen if it's not found
1859 if (!stack.fForceIOAPIC)
1860 {
1861 Bstr bstrFamilyId;
1862 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1863 if (FAILED(rc)) throw rc;
1864 if (bstrFamilyId == "Windows")
1865 stack.fForceIOAPIC = true;
1866 }
1867
1868 if (stack.fForceIOAPIC)
1869 {
1870 ComPtr<IBIOSSettings> pBIOSSettings;
1871 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1872 if (FAILED(rc)) throw rc;
1873
1874 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1875 if (FAILED(rc)) throw rc;
1876 }
1877
1878 if (!stack.strAudioAdapter.isEmpty())
1879 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
1880 {
1881 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
1882 ComPtr<IAudioAdapter> audioAdapter;
1883 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1884 if (FAILED(rc)) throw rc;
1885 rc = audioAdapter->COMSETTER(Enabled)(true);
1886 if (FAILED(rc)) throw rc;
1887 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1888 if (FAILED(rc)) throw rc;
1889 }
1890
1891#ifdef VBOX_WITH_USB
1892 /* USB Controller */
1893 ComPtr<IUSBController> usbController;
1894 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1895 if (FAILED(rc)) throw rc;
1896 rc = usbController->COMSETTER(Enabled)(stack.fUSBEnabled);
1897 if (FAILED(rc)) throw rc;
1898#endif /* VBOX_WITH_USB */
1899
1900 /* Change the network adapters */
1901 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1902 if (vsdeNW.size() == 0)
1903 {
1904 /* No network adapters, so we have to disable our default one */
1905 ComPtr<INetworkAdapter> nwVBox;
1906 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1907 if (FAILED(rc)) throw rc;
1908 rc = nwVBox->COMSETTER(Enabled)(false);
1909 if (FAILED(rc)) throw rc;
1910 }
1911 else if (vsdeNW.size() > SchemaDefs::NetworkAdapterCount)
1912 throw setError(VBOX_E_FILE_ERROR,
1913 tr("Too many network adapters: OVF requests %d network adapters, but VirtualBox only supports %d"),
1914 vsdeNW.size(), SchemaDefs::NetworkAdapterCount);
1915 else
1916 {
1917 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1918 size_t a = 0;
1919 for (nwIt = vsdeNW.begin();
1920 nwIt != vsdeNW.end();
1921 ++nwIt, ++a)
1922 {
1923 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1924
1925 const Utf8Str &nwTypeVBox = pvsys->strVboxCurrent;
1926 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1927 ComPtr<INetworkAdapter> pNetworkAdapter;
1928 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1929 if (FAILED(rc)) throw rc;
1930 /* Enable the network card & set the adapter type */
1931 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1932 if (FAILED(rc)) throw rc;
1933 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1934 if (FAILED(rc)) throw rc;
1935
1936 // default is NAT; change to "bridged" if extra conf says so
1937 if (!pvsys->strExtraConfigCurrent.compare("type=Bridged", Utf8Str::CaseInsensitive))
1938 {
1939 /* Attach to the right interface */
1940 rc = pNetworkAdapter->AttachToBridgedInterface();
1941 if (FAILED(rc)) throw rc;
1942 ComPtr<IHost> host;
1943 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1944 if (FAILED(rc)) throw rc;
1945 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1946 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1947 if (FAILED(rc)) throw rc;
1948 // We search for the first host network interface which
1949 // is usable for bridged networking
1950 for (size_t j = 0;
1951 j < nwInterfaces.size();
1952 ++j)
1953 {
1954 HostNetworkInterfaceType_T itype;
1955 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1956 if (FAILED(rc)) throw rc;
1957 if (itype == HostNetworkInterfaceType_Bridged)
1958 {
1959 Bstr name;
1960 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1961 if (FAILED(rc)) throw rc;
1962 /* Set the interface name to attach to */
1963 pNetworkAdapter->COMSETTER(HostInterface)(name.raw());
1964 if (FAILED(rc)) throw rc;
1965 break;
1966 }
1967 }
1968 }
1969 /* Next test for host only interfaces */
1970 else if (!pvsys->strExtraConfigCurrent.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1971 {
1972 /* Attach to the right interface */
1973 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1974 if (FAILED(rc)) throw rc;
1975 ComPtr<IHost> host;
1976 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1977 if (FAILED(rc)) throw rc;
1978 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1979 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1980 if (FAILED(rc)) throw rc;
1981 // We search for the first host network interface which
1982 // is usable for host only networking
1983 for (size_t j = 0;
1984 j < nwInterfaces.size();
1985 ++j)
1986 {
1987 HostNetworkInterfaceType_T itype;
1988 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1989 if (FAILED(rc)) throw rc;
1990 if (itype == HostNetworkInterfaceType_HostOnly)
1991 {
1992 Bstr name;
1993 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1994 if (FAILED(rc)) throw rc;
1995 /* Set the interface name to attach to */
1996 pNetworkAdapter->COMSETTER(HostInterface)(name.raw());
1997 if (FAILED(rc)) throw rc;
1998 break;
1999 }
2000 }
2001 }
2002 }
2003 }
2004
2005 // IDE Hard disk controller
2006 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2007 // In OVF (at least VMware's version of it), an IDE controller has two ports, so VirtualBox's single IDE controller
2008 // with two channels and two ports each counts as two OVF IDE controllers -- so we accept one or two such IDE controllers
2009 uint32_t cIDEControllers = vsdeHDCIDE.size();
2010 if (cIDEControllers > 2)
2011 throw setError(VBOX_E_FILE_ERROR,
2012 tr("Too many IDE controllers in OVF; import facility only supports two"));
2013 if (vsdeHDCIDE.size() > 0)
2014 {
2015 // one or two IDE controllers present in OVF: add one VirtualBox controller
2016 ComPtr<IStorageController> pController;
2017 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2018 if (FAILED(rc)) throw rc;
2019
2020 const char *pcszIDEType = vsdeHDCIDE.front()->strVboxCurrent.c_str();
2021 if (!strcmp(pcszIDEType, "PIIX3"))
2022 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2023 else if (!strcmp(pcszIDEType, "PIIX4"))
2024 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2025 else if (!strcmp(pcszIDEType, "ICH6"))
2026 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2027 else
2028 throw setError(VBOX_E_FILE_ERROR,
2029 tr("Invalid IDE controller type \"%s\""),
2030 pcszIDEType);
2031 if (FAILED(rc)) throw rc;
2032 }
2033
2034 /* Hard disk controller SATA */
2035 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2036 if (vsdeHDCSATA.size() > 1)
2037 throw setError(VBOX_E_FILE_ERROR,
2038 tr("Too many SATA controllers in OVF; import facility only supports one"));
2039 if (vsdeHDCSATA.size() > 0)
2040 {
2041 ComPtr<IStorageController> pController;
2042 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVboxCurrent;
2043 if (hdcVBox == "AHCI")
2044 {
2045 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(), StorageBus_SATA, pController.asOutParam());
2046 if (FAILED(rc)) throw rc;
2047 }
2048 else
2049 throw setError(VBOX_E_FILE_ERROR,
2050 tr("Invalid SATA controller type \"%s\""),
2051 hdcVBox.c_str());
2052 }
2053
2054 /* Hard disk controller SCSI */
2055 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2056 if (vsdeHDCSCSI.size() > 1)
2057 throw setError(VBOX_E_FILE_ERROR,
2058 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2059 if (vsdeHDCSCSI.size() > 0)
2060 {
2061 ComPtr<IStorageController> pController;
2062 Bstr bstrName(L"SCSI Controller");
2063 StorageBus_T busType = StorageBus_SCSI;
2064 StorageControllerType_T controllerType;
2065 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVboxCurrent;
2066 if (hdcVBox == "LsiLogic")
2067 controllerType = StorageControllerType_LsiLogic;
2068 else if (hdcVBox == "LsiLogicSas")
2069 {
2070 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2071 bstrName = L"SAS Controller";
2072 busType = StorageBus_SAS;
2073 controllerType = StorageControllerType_LsiLogicSas;
2074 }
2075 else if (hdcVBox == "BusLogic")
2076 controllerType = StorageControllerType_BusLogic;
2077 else
2078 throw setError(VBOX_E_FILE_ERROR,
2079 tr("Invalid SCSI controller type \"%s\""),
2080 hdcVBox.c_str());
2081
2082 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2083 if (FAILED(rc)) throw rc;
2084 rc = pController->COMSETTER(ControllerType)(controllerType);
2085 if (FAILED(rc)) throw rc;
2086 }
2087
2088 /* Hard disk controller SAS */
2089 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2090 if (vsdeHDCSAS.size() > 1)
2091 throw setError(VBOX_E_FILE_ERROR,
2092 tr("Too many SAS controllers in OVF; import facility only supports one"));
2093 if (vsdeHDCSAS.size() > 0)
2094 {
2095 ComPtr<IStorageController> pController;
2096 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(), StorageBus_SAS, pController.asOutParam());
2097 if (FAILED(rc)) throw rc;
2098 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2099 if (FAILED(rc)) throw rc;
2100 }
2101
2102 /* Now its time to register the machine before we add any hard disks */
2103 rc = mVirtualBox->RegisterMachine(pNewMachine);
2104 if (FAILED(rc)) throw rc;
2105
2106 // store new machine for roll-back in case of errors
2107 Bstr bstrNewMachineId;
2108 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2109 if (FAILED(rc)) throw rc;
2110 Guid uuidNewMachine(bstrNewMachineId);
2111 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2112
2113 // Add floppies and CD-ROMs to the appropriate controllers.
2114 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
2115 if (vsdeFloppy.size() > 1)
2116 throw setError(VBOX_E_FILE_ERROR,
2117 tr("Too many floppy controllers in OVF; import facility only supports one"));
2118 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
2119 if ( (vsdeFloppy.size() > 0)
2120 || (vsdeCDROM.size() > 0)
2121 )
2122 {
2123 // If there's an error here we need to close the session, so
2124 // we need another try/catch block.
2125
2126 try
2127 {
2128 // to attach things we need to open a session for the new machine
2129 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2130 if (FAILED(rc)) throw rc;
2131 stack.fSessionOpen = true;
2132
2133 ComPtr<IMachine> sMachine;
2134 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2135 if (FAILED(rc)) throw rc;
2136
2137 // floppy first
2138 if (vsdeFloppy.size() == 1)
2139 {
2140 ComPtr<IStorageController> pController;
2141 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(), StorageBus_Floppy, pController.asOutParam());
2142 if (FAILED(rc)) throw rc;
2143
2144 Bstr bstrName;
2145 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
2146 if (FAILED(rc)) throw rc;
2147
2148 // this is for rollback later
2149 MyHardDiskAttachment mhda;
2150 mhda.pMachine = pNewMachine;
2151 mhda.controllerType = bstrName;
2152 mhda.lControllerPort = 0;
2153 mhda.lDevice = 0;
2154
2155 Log(("Attaching floppy\n"));
2156
2157 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2158 mhda.lControllerPort,
2159 mhda.lDevice,
2160 DeviceType_Floppy,
2161 NULL);
2162 if (FAILED(rc)) throw rc;
2163
2164 stack.llHardDiskAttachments.push_back(mhda);
2165 }
2166
2167 // CD-ROMs next
2168 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
2169 jt != vsdeCDROM.end();
2170 ++jt)
2171 {
2172 // for now always attach to secondary master on IDE controller;
2173 // there seems to be no useful information in OVF where else to
2174 // attach it (@todo test with latest versions of OVF software)
2175
2176 // find the IDE controller
2177 const ovf::HardDiskController *pController = NULL;
2178 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
2179 kt != vsysThis.mapControllers.end();
2180 ++kt)
2181 {
2182 if (kt->second.system == ovf::HardDiskController::IDE)
2183 {
2184 pController = &kt->second;
2185 break;
2186 }
2187 }
2188
2189 if (!pController)
2190 throw setError(VBOX_E_FILE_ERROR,
2191 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
2192
2193 // this is for rollback later
2194 MyHardDiskAttachment mhda;
2195 mhda.pMachine = pNewMachine;
2196
2197 convertDiskAttachmentValues(*pController,
2198 2, // interpreted as secondary master
2199 mhda.controllerType, // Bstr
2200 mhda.lControllerPort,
2201 mhda.lDevice);
2202
2203 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
2204
2205 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2206 mhda.lControllerPort,
2207 mhda.lDevice,
2208 DeviceType_DVD,
2209 NULL);
2210 if (FAILED(rc)) throw rc;
2211
2212 stack.llHardDiskAttachments.push_back(mhda);
2213 } // end for (itHD = avsdeHDs.begin();
2214
2215 rc = sMachine->SaveSettings();
2216 if (FAILED(rc)) throw rc;
2217
2218 // only now that we're done with all disks, close the session
2219 rc = stack.pSession->UnlockMachine();
2220 if (FAILED(rc)) throw rc;
2221 stack.fSessionOpen = false;
2222 }
2223 catch(HRESULT /* aRC */)
2224 {
2225 if (stack.fSessionOpen)
2226 stack.pSession->UnlockMachine();
2227
2228 throw;
2229 }
2230 }
2231
2232 // create the hard disks & connect them to the appropriate controllers
2233 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2234 if (avsdeHDs.size() > 0)
2235 {
2236 // If there's an error here we need to close the session, so
2237 // we need another try/catch block.
2238 try
2239 {
2240 // to attach things we need to open a session for the new machine
2241 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2242 if (FAILED(rc)) throw rc;
2243 stack.fSessionOpen = true;
2244
2245 /* Iterate over all given disk images */
2246 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2247 for (itHD = avsdeHDs.begin();
2248 itHD != avsdeHDs.end();
2249 ++itHD)
2250 {
2251 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2252
2253 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
2254 // in the virtual system's disks map under that ID and also in the global images map
2255 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
2256 // and find the disk from the OVF's disk list
2257 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
2258 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
2259 || (itDiskImage == stack.mapDisks.end())
2260 )
2261 throw setError(E_FAIL,
2262 tr("Internal inconsistency looking up disk image '%s'"),
2263 vsdeHD->strRef.c_str());
2264
2265 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
2266 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
2267
2268 ComObjPtr<Medium> pTargetHD;
2269 importOneDiskImage(ovfDiskImage,
2270 vsdeHD->strVboxCurrent,
2271 pTargetHD,
2272 stack,
2273 pCallbacks,
2274 pStorage);
2275
2276 // now use the new uuid to attach the disk image to our new machine
2277 ComPtr<IMachine> sMachine;
2278 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2279 if (FAILED(rc)) throw rc;
2280
2281 // find the hard disk controller to which we should attach
2282 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
2283
2284 // this is for rollback later
2285 MyHardDiskAttachment mhda;
2286 mhda.pMachine = pNewMachine;
2287
2288 convertDiskAttachmentValues(hdc,
2289 ovfVdisk.ulAddressOnParent,
2290 mhda.controllerType, // Bstr
2291 mhda.lControllerPort,
2292 mhda.lDevice);
2293
2294 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVboxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
2295
2296 rc = sMachine->AttachDevice(mhda.controllerType.raw(), // wstring name
2297 mhda.lControllerPort, // long controllerPort
2298 mhda.lDevice, // long device
2299 DeviceType_HardDisk, // DeviceType_T type
2300 pTargetHD);
2301 if (FAILED(rc)) throw rc;
2302
2303 stack.llHardDiskAttachments.push_back(mhda);
2304
2305 rc = sMachine->SaveSettings();
2306 if (FAILED(rc)) throw rc;
2307 } // end for (itHD = avsdeHDs.begin();
2308
2309 // only now that we're done with all disks, close the session
2310 rc = stack.pSession->UnlockMachine();
2311 if (FAILED(rc)) throw rc;
2312 stack.fSessionOpen = false;
2313 }
2314 catch(HRESULT /* aRC */)
2315 {
2316 if (stack.fSessionOpen)
2317 stack.pSession->UnlockMachine();
2318
2319 throw;
2320 }
2321 }
2322}
2323
2324/**
2325 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
2326 * structure) into VirtualBox by creating an IMachine instance, which is returned.
2327 *
2328 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2329 * up any leftovers from this function. For this, the given ImportStack instance has received information
2330 * about what needs cleaning up (to support rollback).
2331 *
2332 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
2333 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
2334 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
2335 * will most probably work, reimporting them into the same host will cause conflicts, so we always
2336 * generate new ones on import. This involves the following:
2337 *
2338 * 1) Scan the machine config for disk attachments.
2339 *
2340 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
2341 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
2342 * replace the old UUID with the new one.
2343 *
2344 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
2345 * caller has modified them using setFinalValues().
2346 *
2347 * 4) Create the VirtualBox machine with the modfified machine config.
2348 *
2349 * @param config
2350 * @param pNewMachine
2351 * @param stack
2352 */
2353void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
2354 ComPtr<IMachine> &pReturnNewMachine,
2355 ImportStack &stack,
2356 PVDINTERFACEIO pCallbacks,
2357 PSHA1STORAGE pStorage)
2358{
2359 Assert(vsdescThis->m->pConfig);
2360
2361 HRESULT rc = S_OK;
2362
2363 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
2364
2365 /*
2366 *
2367 * step 1): modify machine config according to OVF config, in case the user
2368 * has modified them using setFinalValues()
2369 *
2370 */
2371
2372 config.machineUserData.strDescription = stack.strDescription;
2373
2374 config.hardwareMachine.cCPUs = stack.cCPUs;
2375 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
2376 if (stack.fForceIOAPIC)
2377 config.hardwareMachine.fHardwareVirt = true;
2378 if (stack.fForceIOAPIC)
2379 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
2380
2381/*
2382 <const name="HardDiskControllerIDE" value="14" />
2383 <const name="HardDiskControllerSATA" value="15" />
2384 <const name="HardDiskControllerSCSI" value="16" />
2385 <const name="HardDiskControllerSAS" value="17" />
2386 <const name="HardDiskImage" value="18" />
2387 <const name="Floppy" value="19" />
2388 <const name="CDROM" value="20" />
2389 <const name="NetworkAdapter" value="21" />
2390*/
2391
2392#ifdef VBOX_WITH_USB
2393 // disable USB if user disabled USB
2394 config.hardwareMachine.usbController.fEnabled = stack.fUSBEnabled;
2395#endif
2396
2397 // audio adapter: only config is turning it off presently
2398 if (stack.strAudioAdapter.isEmpty())
2399 config.hardwareMachine.audioAdapter.fEnabled = false;
2400
2401 /*
2402 *
2403 * step 2: scan the machine config for media attachments
2404 *
2405 */
2406
2407 // for each storage controller...
2408 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
2409 sit != config.storageMachine.llStorageControllers.end();
2410 ++sit)
2411 {
2412 settings::StorageController &sc = *sit;
2413
2414 // find the OVF virtual system description entry for this storage controller
2415 switch (sc.storageBus)
2416 {
2417 case StorageBus_SATA:
2418 break;
2419
2420 case StorageBus_SCSI:
2421 break;
2422
2423 case StorageBus_IDE:
2424 break;
2425
2426 case StorageBus_SAS:
2427 break;
2428 }
2429
2430 /* Get all hard disk descriptions. */
2431 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2432
2433 // for each medium attachment to this controller...
2434 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
2435 dit != sc.llAttachedDevices.end();
2436 ++dit)
2437 {
2438 settings::AttachedDevice &d = *dit;
2439
2440 if (d.uuid.isEmpty())
2441 // empty DVD and floppy media
2442 continue;
2443
2444 // convert the Guid to string
2445 Utf8Str strUuid = d.uuid.toString();
2446
2447
2448 // there must be an image in the OVF disk structs with the same UUID
2449 bool fFound = false;
2450 for (ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2451 oit != stack.mapDisks.end();
2452 ++oit)
2453 {
2454 const ovf::DiskImage &di = oit->second;
2455
2456 if (di.uuidVbox == strUuid)
2457 {
2458 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
2459
2460 /* Iterate over all given disk images of the virtual system
2461 * disks description. We need to find the target disk path,
2462 * which could be changed by the user. */
2463 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2464 for (itHD = avsdeHDs.begin();
2465 itHD != avsdeHDs.end();
2466 ++itHD)
2467 {
2468 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2469 if (vsdeHD->strRef == oit->first)
2470 {
2471 vsdeTargetHD = vsdeHD;
2472 break;
2473 }
2474 }
2475 if (!vsdeTargetHD)
2476 throw setError(E_FAIL,
2477 tr("Internal inconsistency looking up disk image '%s'"),
2478 oit->first.c_str());
2479
2480 /*
2481 *
2482 * step 3: import disk
2483 *
2484 */
2485 ComObjPtr<Medium> pTargetHD;
2486 importOneDiskImage(di,
2487 vsdeTargetHD->strVboxCurrent,
2488 pTargetHD,
2489 stack,
2490 pCallbacks,
2491 pStorage);
2492
2493 // ... and replace the old UUID in the machine config with the one of
2494 // the imported disk that was just created
2495 Bstr hdId;
2496 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
2497 if (FAILED(rc)) throw rc;
2498
2499 d.uuid = hdId;
2500
2501 fFound = true;
2502 break;
2503 }
2504 }
2505
2506 // no disk with such a UUID found:
2507 if (!fFound)
2508 throw setError(E_FAIL,
2509 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s but the OVF describes no such image"),
2510 strUuid.c_str());
2511 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
2512 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
2513
2514 /*
2515 *
2516 * step 4): create the machine and have it import the config
2517 *
2518 */
2519
2520 ComObjPtr<Machine> pNewMachine;
2521 rc = pNewMachine.createObject();
2522 if (FAILED(rc)) throw rc;
2523
2524 // this magic constructor fills the new machine object with the MachineConfig
2525 // instance that we created from the vbox:Machine
2526 rc = pNewMachine->init(mVirtualBox,
2527 stack.strNameVBox, // name from OVF preparations; can be suffixed to avoid duplicates, or changed by user
2528 config); // the whole machine config
2529 if (FAILED(rc)) throw rc;
2530
2531 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
2532
2533 // and register it
2534 rc = mVirtualBox->RegisterMachine(pNewMachine);
2535 if (FAILED(rc)) throw rc;
2536
2537 // store new machine for roll-back in case of errors
2538 Bstr bstrNewMachineId;
2539 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2540 if (FAILED(rc)) throw rc;
2541 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
2542}
2543
2544void Appliance::importMachines(ImportStack &stack,
2545 PVDINTERFACEIO pCallbacks,
2546 PSHA1STORAGE pStorage)
2547{
2548 HRESULT rc = S_OK;
2549
2550 // this is safe to access because this thread only gets started
2551 // if pReader != NULL
2552 const ovf::OVFReader &reader = *m->pReader;
2553
2554 // create a session for the machine + disks we manipulate below
2555 rc = stack.pSession.createInprocObject(CLSID_Session);
2556 if (FAILED(rc)) throw rc;
2557
2558 list<ovf::VirtualSystem>::const_iterator it;
2559 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
2560 /* Iterate through all virtual systems of that appliance */
2561 size_t i = 0;
2562 for (it = reader.m_llVirtualSystems.begin(),
2563 it1 = m->virtualSystemDescriptions.begin();
2564 it != reader.m_llVirtualSystems.end();
2565 ++it, ++it1, ++i)
2566 {
2567 const ovf::VirtualSystem &vsysThis = *it;
2568 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
2569
2570 ComPtr<IMachine> pNewMachine;
2571
2572 // there are two ways in which we can create a vbox machine from OVF:
2573 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
2574 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
2575 // with all the machine config pretty-parsed;
2576 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
2577 // VirtualSystemDescriptionEntry and do import work
2578
2579 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
2580 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
2581
2582 // VM name
2583 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2584 if (vsdeName.size() < 1)
2585 throw setError(VBOX_E_FILE_ERROR,
2586 tr("Missing VM name"));
2587 stack.strNameVBox = vsdeName.front()->strVboxCurrent;
2588
2589 // have VirtualBox suggest where the filename would be placed so we can
2590 // put the disk images in the same directory
2591 Bstr bstrMachineFilename;
2592 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
2593 NULL,
2594 bstrMachineFilename.asOutParam());
2595 if (FAILED(rc)) throw rc;
2596 // and determine the machine folder from that
2597 stack.strMachineFolder = bstrMachineFilename;
2598 stack.strMachineFolder.stripFilename();
2599
2600 // guest OS type
2601 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
2602 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
2603 if (vsdeOS.size() < 1)
2604 throw setError(VBOX_E_FILE_ERROR,
2605 tr("Missing guest OS type"));
2606 stack.strOsTypeVBox = vsdeOS.front()->strVboxCurrent;
2607
2608 // CPU count
2609 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
2610 if (vsdeCPU.size() != 1)
2611 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
2612
2613 const Utf8Str &cpuVBox = vsdeCPU.front()->strVboxCurrent;
2614 stack.cCPUs = (uint32_t)RTStrToUInt64(cpuVBox.c_str());
2615 // We need HWVirt & IO-APIC if more than one CPU is requested
2616 if (stack.cCPUs > 1)
2617 {
2618 stack.fForceHWVirt = true;
2619 stack.fForceIOAPIC = true;
2620 }
2621
2622 // RAM
2623 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
2624 if (vsdeRAM.size() != 1)
2625 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
2626 const Utf8Str &memoryVBox = vsdeRAM.front()->strVboxCurrent;
2627 stack.ulMemorySizeMB = (uint32_t)RTStrToUInt64(memoryVBox.c_str());
2628
2629#ifdef VBOX_WITH_USB
2630 // USB controller
2631 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
2632 // USB support is enabled if there's at least one such entry; to disable USB support,
2633 // the type of the USB item would have been changed to "ignore"
2634 stack.fUSBEnabled = vsdeUSBController.size() > 0;
2635#endif
2636 // audio adapter
2637 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
2638 /* @todo: we support one audio adapter only */
2639 if (vsdeAudioAdapter.size() > 0)
2640 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVboxCurrent;
2641
2642 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
2643 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
2644 if (vsdeDescription.size())
2645 stack.strDescription = vsdeDescription.front()->strVboxCurrent;
2646
2647 // import vbox:machine or OVF now
2648 if (vsdescThis->m->pConfig)
2649 // vbox:Machine config
2650 importVBoxMachine(vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
2651 else
2652 // generic OVF config
2653 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
2654
2655 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
2656}
2657
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