VirtualBox

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

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

Main-OVF: make the target format changeable

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