VirtualBox

source: vbox/trunk/src/VBox/Main/ApplianceImpl.cpp@ 25786

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

Main: fix broken rollback in OVF error handling code (any error in media import would result in incomprehensible error messages saying that a machine could not be registered because it still has hard disk attachments; apparently introduced in april 2009 by the UUID changes -- r46627)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 199.1 KB
Line 
1/* $Id: ApplianceImpl.cpp 25786 2010-01-12 18:01:05Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2009 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#include <iprt/stream.h>
24#include <iprt/path.h>
25#include <iprt/dir.h>
26#include <iprt/file.h>
27#include <iprt/s3.h>
28#include <iprt/sha.h>
29#include <iprt/manifest.h>
30
31#include <VBox/param.h>
32#include <VBox/version.h>
33
34#include "ApplianceImpl.h"
35#include "VFSExplorerImpl.h"
36#include "VirtualBoxImpl.h"
37#include "GuestOSTypeImpl.h"
38#include "ProgressImpl.h"
39#include "MachineImpl.h"
40#include "MediumImpl.h"
41
42#include "HostNetworkInterfaceImpl.h"
43
44#include "Logging.h"
45
46using namespace std;
47
48////////////////////////////////////////////////////////////////////////////////
49//
50// Appliance data definition
51//
52////////////////////////////////////////////////////////////////////////////////
53
54/* Describe a location for the import/export. The location could be a file on a
55 * local hard disk or a remote target based on the supported inet protocols. */
56struct Appliance::LocationInfo
57{
58 LocationInfo()
59 : storageType(VFSType_File) {}
60 VFSType_T storageType; /* Which type of storage should be handled */
61 Utf8Str strPath; /* File path for the import/export */
62 Utf8Str strHostname; /* Hostname on remote storage locations (could be empty) */
63 Utf8Str strUsername; /* Username on remote storage locations (could be empty) */
64 Utf8Str strPassword; /* Password on remote storage locations (could be empty) */
65};
66
67// opaque private instance data of Appliance class
68struct Appliance::Data
69{
70 Data()
71 : pReader(NULL) {}
72
73 ~Data()
74 {
75 if (pReader)
76 {
77 delete pReader;
78 pReader = NULL;
79 }
80 }
81
82 LocationInfo locInfo; /* The location info for the currently processed OVF */
83
84 OVFReader *pReader;
85
86 list< ComObjPtr<VirtualSystemDescription> > virtualSystemDescriptions;
87
88 list<Utf8Str> llWarnings;
89
90 ULONG ulWeightPerOperation;
91 Utf8Str strOVFSHA1Digest;
92};
93
94struct VirtualSystemDescription::Data
95{
96 list<VirtualSystemDescriptionEntry> llDescriptions;
97};
98
99////////////////////////////////////////////////////////////////////////////////
100//
101// internal helpers
102//
103////////////////////////////////////////////////////////////////////////////////
104
105static const struct
106{
107 CIMOSType_T cim;
108 const char *pcszVbox;
109}
110g_osTypes[] =
111{
112 { CIMOSType_CIMOS_Unknown, SchemaDefs_OSTypeId_Other },
113 { CIMOSType_CIMOS_OS2, SchemaDefs_OSTypeId_OS2 },
114 { CIMOSType_CIMOS_MSDOS, SchemaDefs_OSTypeId_DOS },
115 { CIMOSType_CIMOS_WIN3x, SchemaDefs_OSTypeId_Windows31 },
116 { CIMOSType_CIMOS_WIN95, SchemaDefs_OSTypeId_Windows95 },
117 { CIMOSType_CIMOS_WIN98, SchemaDefs_OSTypeId_Windows98 },
118 { CIMOSType_CIMOS_WINNT, SchemaDefs_OSTypeId_WindowsNT4 },
119 { CIMOSType_CIMOS_NetWare, SchemaDefs_OSTypeId_Netware },
120 { CIMOSType_CIMOS_NovellOES, SchemaDefs_OSTypeId_Netware },
121 { CIMOSType_CIMOS_Solaris, SchemaDefs_OSTypeId_OpenSolaris },
122 { CIMOSType_CIMOS_SunOS, SchemaDefs_OSTypeId_OpenSolaris },
123 { CIMOSType_CIMOS_FreeBSD, SchemaDefs_OSTypeId_FreeBSD },
124 { CIMOSType_CIMOS_NetBSD, SchemaDefs_OSTypeId_NetBSD },
125 { CIMOSType_CIMOS_QNX, SchemaDefs_OSTypeId_QNX },
126 { CIMOSType_CIMOS_Windows2000, SchemaDefs_OSTypeId_Windows2000 },
127 { CIMOSType_CIMOS_WindowsMe, SchemaDefs_OSTypeId_WindowsMe },
128 { CIMOSType_CIMOS_OpenBSD, SchemaDefs_OSTypeId_OpenBSD },
129 { CIMOSType_CIMOS_WindowsXP, SchemaDefs_OSTypeId_WindowsXP },
130 { CIMOSType_CIMOS_WindowsXPEmbedded, SchemaDefs_OSTypeId_WindowsXP },
131 { CIMOSType_CIMOS_WindowsEmbeddedforPointofService, SchemaDefs_OSTypeId_WindowsXP },
132 { CIMOSType_CIMOS_MicrosoftWindowsServer2003, SchemaDefs_OSTypeId_Windows2003 },
133 { CIMOSType_CIMOS_MicrosoftWindowsServer2003_64, SchemaDefs_OSTypeId_Windows2003_64 },
134 { CIMOSType_CIMOS_WindowsXP_64, SchemaDefs_OSTypeId_WindowsXP_64 },
135 { CIMOSType_CIMOS_WindowsVista, SchemaDefs_OSTypeId_WindowsVista },
136 { CIMOSType_CIMOS_WindowsVista_64, SchemaDefs_OSTypeId_WindowsVista_64 },
137 { CIMOSType_CIMOS_MicrosoftWindowsServer2008, SchemaDefs_OSTypeId_Windows2008 },
138 { CIMOSType_CIMOS_MicrosoftWindowsServer2008_64, SchemaDefs_OSTypeId_Windows2008_64 },
139 { CIMOSType_CIMOS_FreeBSD_64, SchemaDefs_OSTypeId_FreeBSD_64 },
140 { CIMOSType_CIMOS_RedHatEnterpriseLinux, SchemaDefs_OSTypeId_RedHat },
141 { CIMOSType_CIMOS_RedHatEnterpriseLinux_64, SchemaDefs_OSTypeId_RedHat_64 },
142 { CIMOSType_CIMOS_Solaris_64, SchemaDefs_OSTypeId_OpenSolaris_64 },
143 { CIMOSType_CIMOS_SUSE, SchemaDefs_OSTypeId_OpenSUSE },
144 { CIMOSType_CIMOS_SLES, SchemaDefs_OSTypeId_OpenSUSE },
145 { CIMOSType_CIMOS_NovellLinuxDesktop, SchemaDefs_OSTypeId_OpenSUSE },
146 { CIMOSType_CIMOS_SUSE_64, SchemaDefs_OSTypeId_OpenSUSE_64 },
147 { CIMOSType_CIMOS_SLES_64, SchemaDefs_OSTypeId_OpenSUSE_64 },
148 { CIMOSType_CIMOS_LINUX, SchemaDefs_OSTypeId_Linux },
149 { CIMOSType_CIMOS_SunJavaDesktopSystem, SchemaDefs_OSTypeId_Linux },
150 { CIMOSType_CIMOS_TurboLinux, SchemaDefs_OSTypeId_Linux},
151
152 // { CIMOSType_CIMOS_TurboLinux_64, },
153
154 { CIMOSType_CIMOS_Mandriva, SchemaDefs_OSTypeId_Mandriva },
155 { CIMOSType_CIMOS_Mandriva_64, SchemaDefs_OSTypeId_Mandriva_64 },
156 { CIMOSType_CIMOS_Ubuntu, SchemaDefs_OSTypeId_Ubuntu },
157 { CIMOSType_CIMOS_Ubuntu_64, SchemaDefs_OSTypeId_Ubuntu_64 },
158 { CIMOSType_CIMOS_Debian, SchemaDefs_OSTypeId_Debian },
159 { CIMOSType_CIMOS_Debian_64, SchemaDefs_OSTypeId_Debian_64 },
160 { CIMOSType_CIMOS_Linux_2_4_x, SchemaDefs_OSTypeId_Linux24 },
161 { CIMOSType_CIMOS_Linux_2_4_x_64, SchemaDefs_OSTypeId_Linux24_64 },
162 { CIMOSType_CIMOS_Linux_2_6_x, SchemaDefs_OSTypeId_Linux26 },
163 { CIMOSType_CIMOS_Linux_2_6_x_64, SchemaDefs_OSTypeId_Linux26_64 },
164 { CIMOSType_CIMOS_Linux_64, SchemaDefs_OSTypeId_Linux26_64 }
165};
166
167/* Pattern structure for matching the OS type description field */
168struct osTypePattern
169{
170 const char *pcszPattern;
171 const char *pcszVbox;
172};
173
174/* These are the 32-Bit ones. They are sorted by priority. */
175static const osTypePattern g_osTypesPattern[] =
176{
177 {"Windows NT", SchemaDefs_OSTypeId_WindowsNT4},
178 {"Windows XP", SchemaDefs_OSTypeId_WindowsXP},
179 {"Windows 2000", SchemaDefs_OSTypeId_Windows2000},
180 {"Windows 2003", SchemaDefs_OSTypeId_Windows2003},
181 {"Windows Vista", SchemaDefs_OSTypeId_WindowsVista},
182 {"Windows 2008", SchemaDefs_OSTypeId_Windows2008},
183 {"SUSE", SchemaDefs_OSTypeId_OpenSUSE},
184 {"Novell", SchemaDefs_OSTypeId_OpenSUSE},
185 {"Red Hat", SchemaDefs_OSTypeId_RedHat},
186 {"Mandriva", SchemaDefs_OSTypeId_Mandriva},
187 {"Ubuntu", SchemaDefs_OSTypeId_Ubuntu},
188 {"Debian", SchemaDefs_OSTypeId_Debian},
189 {"QNX", SchemaDefs_OSTypeId_QNX},
190 {"Linux 2.4", SchemaDefs_OSTypeId_Linux24},
191 {"Linux 2.6", SchemaDefs_OSTypeId_Linux26},
192 {"Linux", SchemaDefs_OSTypeId_Linux},
193 {"OpenSolaris", SchemaDefs_OSTypeId_OpenSolaris},
194 {"Solaris", SchemaDefs_OSTypeId_OpenSolaris},
195 {"FreeBSD", SchemaDefs_OSTypeId_FreeBSD},
196 {"NetBSD", SchemaDefs_OSTypeId_NetBSD},
197 {"Windows 95", SchemaDefs_OSTypeId_Windows95},
198 {"Windows 98", SchemaDefs_OSTypeId_Windows98},
199 {"Windows Me", SchemaDefs_OSTypeId_WindowsMe},
200 {"Windows 3.", SchemaDefs_OSTypeId_Windows31},
201 {"DOS", SchemaDefs_OSTypeId_DOS},
202 {"OS2", SchemaDefs_OSTypeId_OS2}
203};
204
205/* These are the 64-Bit ones. They are sorted by priority. */
206static const osTypePattern g_osTypesPattern64[] =
207{
208 {"Windows XP", SchemaDefs_OSTypeId_WindowsXP_64},
209 {"Windows 2003", SchemaDefs_OSTypeId_Windows2003_64},
210 {"Windows Vista", SchemaDefs_OSTypeId_WindowsVista_64},
211 {"Windows 2008", SchemaDefs_OSTypeId_Windows2008_64},
212 {"SUSE", SchemaDefs_OSTypeId_OpenSUSE_64},
213 {"Novell", SchemaDefs_OSTypeId_OpenSUSE_64},
214 {"Red Hat", SchemaDefs_OSTypeId_RedHat_64},
215 {"Mandriva", SchemaDefs_OSTypeId_Mandriva_64},
216 {"Ubuntu", SchemaDefs_OSTypeId_Ubuntu_64},
217 {"Debian", SchemaDefs_OSTypeId_Debian_64},
218 {"Linux 2.4", SchemaDefs_OSTypeId_Linux24_64},
219 {"Linux 2.6", SchemaDefs_OSTypeId_Linux26_64},
220 {"Linux", SchemaDefs_OSTypeId_Linux26_64},
221 {"OpenSolaris", SchemaDefs_OSTypeId_OpenSolaris_64},
222 {"Solaris", SchemaDefs_OSTypeId_OpenSolaris_64},
223 {"FreeBSD", SchemaDefs_OSTypeId_FreeBSD_64},
224};
225
226/**
227 * Private helper func that suggests a VirtualBox guest OS type
228 * for the given OVF operating system type.
229 * @param osTypeVBox
230 * @param c
231 * @param cStr
232 */
233static void convertCIMOSType2VBoxOSType(Utf8Str &strType, CIMOSType_T c, const Utf8Str &cStr)
234{
235 /* First check if the type is other/other_64 */
236 if (c == CIMOSType_CIMOS_Other)
237 {
238 for (size_t i=0; i < RT_ELEMENTS(g_osTypesPattern); ++i)
239 if (cStr.contains (g_osTypesPattern[i].pcszPattern, Utf8Str::CaseInsensitive))
240 {
241 strType = g_osTypesPattern[i].pcszVbox;
242 return;
243 }
244 }
245 else if (c == CIMOSType_CIMOS_Other_64)
246 {
247 for (size_t i=0; i < RT_ELEMENTS(g_osTypesPattern64); ++i)
248 if (cStr.contains (g_osTypesPattern64[i].pcszPattern, Utf8Str::CaseInsensitive))
249 {
250 strType = g_osTypesPattern64[i].pcszVbox;
251 return;
252 }
253 }
254
255 for (size_t i = 0; i < RT_ELEMENTS(g_osTypes); ++i)
256 {
257 if (c == g_osTypes[i].cim)
258 {
259 strType = g_osTypes[i].pcszVbox;
260 return;
261 }
262 }
263
264 strType = SchemaDefs_OSTypeId_Other;
265}
266
267/**
268 * Private helper func that suggests a VirtualBox guest OS type
269 * for the given OVF operating system type.
270 * @param osTypeVBox
271 * @param c
272 */
273static CIMOSType_T convertVBoxOSType2CIMOSType(const char *pcszVbox)
274{
275 for (size_t i = 0; i < RT_ELEMENTS(g_osTypes); ++i)
276 {
277 if (!RTStrICmp(pcszVbox, g_osTypes[i].pcszVbox))
278 return g_osTypes[i].cim;
279 }
280
281 return CIMOSType_CIMOS_Other;
282}
283
284////////////////////////////////////////////////////////////////////////////////
285//
286// IVirtualBox public methods
287//
288////////////////////////////////////////////////////////////////////////////////
289
290// This code is here so we won't have to include the appliance headers in the
291// IVirtualBox implementation.
292
293/**
294 * Implementation for IVirtualBox::createAppliance.
295 *
296 * @param anAppliance IAppliance object created if S_OK is returned.
297 * @return S_OK or error.
298 */
299STDMETHODIMP VirtualBox::CreateAppliance(IAppliance** anAppliance)
300{
301 HRESULT rc;
302
303 ComObjPtr<Appliance> appliance;
304 appliance.createObject();
305 rc = appliance->init(this);
306
307 if (SUCCEEDED(rc))
308 appliance.queryInterfaceTo(anAppliance);
309
310 return rc;
311}
312
313////////////////////////////////////////////////////////////////////////////////
314//
315// Appliance constructor / destructor
316//
317////////////////////////////////////////////////////////////////////////////////
318
319DEFINE_EMPTY_CTOR_DTOR(Appliance)
320
321/**
322 * Appliance COM initializer.
323 * @param
324 * @return
325 */
326HRESULT Appliance::init(VirtualBox *aVirtualBox)
327{
328 /* Enclose the state transition NotReady->InInit->Ready */
329 AutoInitSpan autoInitSpan(this);
330 AssertReturn(autoInitSpan.isOk(), E_FAIL);
331
332 /* Weak reference to a VirtualBox object */
333 unconst(mVirtualBox) = aVirtualBox;
334
335 // initialize data
336 m = new Data;
337
338 /* Confirm a successful initialization */
339 autoInitSpan.setSucceeded();
340
341 return S_OK;
342}
343
344/**
345 * Appliance COM uninitializer.
346 * @return
347 */
348void Appliance::uninit()
349{
350 /* Enclose the state transition Ready->InUninit->NotReady */
351 AutoUninitSpan autoUninitSpan(this);
352 if (autoUninitSpan.uninitDone())
353 return;
354
355 delete m;
356 m = NULL;
357}
358
359////////////////////////////////////////////////////////////////////////////////
360//
361// Appliance private methods
362//
363////////////////////////////////////////////////////////////////////////////////
364
365HRESULT Appliance::searchUniqueVMName(Utf8Str& aName) const
366{
367 IMachine *machine = NULL;
368 char *tmpName = RTStrDup(aName.c_str());
369 int i = 1;
370 /* @todo: Maybe too cost-intensive; try to find a lighter way */
371 while (mVirtualBox->FindMachine(Bstr(tmpName), &machine) != VBOX_E_OBJECT_NOT_FOUND)
372 {
373 RTStrFree(tmpName);
374 RTStrAPrintf(&tmpName, "%s_%d", aName.c_str(), i);
375 ++i;
376 }
377 aName = tmpName;
378 RTStrFree(tmpName);
379
380 return S_OK;
381}
382
383HRESULT Appliance::searchUniqueDiskImageFilePath(Utf8Str& aName) const
384{
385 IMedium *harddisk = NULL;
386 char *tmpName = RTStrDup(aName.c_str());
387 int i = 1;
388 /* Check if the file exists or if a file with this path is registered
389 * already */
390 /* @todo: Maybe too cost-intensive; try to find a lighter way */
391 while (RTPathExists(tmpName) ||
392 mVirtualBox->FindHardDisk(Bstr(tmpName), &harddisk) != VBOX_E_OBJECT_NOT_FOUND)
393 {
394 RTStrFree(tmpName);
395 char *tmpDir = RTStrDup(aName.c_str());
396 RTPathStripFilename(tmpDir);;
397 char *tmpFile = RTStrDup(RTPathFilename(aName.c_str()));
398 RTPathStripExt(tmpFile);
399 const char *tmpExt = RTPathExt(aName.c_str());
400 RTStrAPrintf(&tmpName, "%s%c%s_%d%s", tmpDir, RTPATH_DELIMITER, tmpFile, i, tmpExt);
401 RTStrFree(tmpFile);
402 RTStrFree(tmpDir);
403 ++i;
404 }
405 aName = tmpName;
406 RTStrFree(tmpName);
407
408 return S_OK;
409}
410
411/**
412 * Called from the import and export background threads to synchronize the second
413 * background disk thread's progress object with the current progress object so
414 * that the user interface sees progress correctly and that cancel signals are
415 * passed on to the second thread.
416 * @param pProgressThis Progress object of the current thread.
417 * @param pProgressAsync Progress object of asynchronous task running in background.
418 */
419void Appliance::waitForAsyncProgress(ComObjPtr<Progress> &pProgressThis,
420 ComPtr<IProgress> &pProgressAsync)
421{
422 HRESULT rc;
423
424 // now loop until the asynchronous operation completes and then report its result
425 BOOL fCompleted;
426 BOOL fCanceled;
427 ULONG currentPercent;
428 while (SUCCEEDED(pProgressAsync->COMGETTER(Completed(&fCompleted))))
429 {
430 rc = pProgressThis->COMGETTER(Canceled)(&fCanceled);
431 if (FAILED(rc)) throw rc;
432 if (fCanceled)
433 {
434 pProgressAsync->Cancel();
435 break;
436 }
437
438 rc = pProgressAsync->COMGETTER(Percent(&currentPercent));
439 if (FAILED(rc)) throw rc;
440 if (!pProgressThis.isNull())
441 pProgressThis->SetCurrentOperationProgress(currentPercent);
442 if (fCompleted)
443 break;
444
445 /* Make sure the loop is not too tight */
446 rc = pProgressAsync->WaitForCompletion(100);
447 if (FAILED(rc)) throw rc;
448 }
449 // report result of asynchronous operation
450 LONG iRc;
451 rc = pProgressAsync->COMGETTER(ResultCode)(&iRc);
452 if (FAILED(rc)) throw rc;
453
454
455 // if the thread of the progress object has an error, then
456 // retrieve the error info from there, or it'll be lost
457 if (FAILED(iRc))
458 {
459 ProgressErrorInfo info(pProgressAsync);
460 Utf8Str str(info.getText());
461 const char *pcsz = str.c_str();
462 HRESULT rc2 = setError(iRc, pcsz);
463 throw rc2;
464 }
465}
466
467void Appliance::addWarning(const char* aWarning, ...)
468{
469 va_list args;
470 va_start(args, aWarning);
471 Utf8StrFmtVA str(aWarning, args);
472 va_end(args);
473 m->llWarnings.push_back(str);
474}
475
476void Appliance::disksWeight(uint32_t &ulTotalMB, uint32_t &cDisks) const
477{
478 ulTotalMB = 0;
479 cDisks = 0;
480 /* Weigh the disk images according to their sizes */
481 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
482 for (it = m->virtualSystemDescriptions.begin();
483 it != m->virtualSystemDescriptions.end();
484 ++it)
485 {
486 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
487 /* One for every hard disk of the Virtual System */
488 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
489 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
490 for (itH = avsdeHDs.begin();
491 itH != avsdeHDs.end();
492 ++itH)
493 {
494 const VirtualSystemDescriptionEntry *pHD = *itH;
495 ulTotalMB += pHD->ulSizeMB;
496 ++cDisks;
497 }
498 }
499
500}
501
502HRESULT Appliance::setUpProgressFS(ComObjPtr<Progress> &pProgress, const Bstr &bstrDescription)
503{
504 HRESULT rc;
505
506 /* Create the progress object */
507 pProgress.createObject();
508
509 /* Weigh the disk images according to their sizes */
510 uint32_t ulTotalMB;
511 uint32_t cDisks;
512 disksWeight(ulTotalMB, cDisks);
513
514 ULONG cOperations = 1 + cDisks; // one op per disk plus 1 for the XML
515
516 ULONG ulTotalOperationsWeight;
517 if (ulTotalMB)
518 {
519 m->ulWeightPerOperation = (ULONG)((double)ulTotalMB * 1 / 100); // use 1% of the progress for the XML
520 ulTotalOperationsWeight = ulTotalMB + m->ulWeightPerOperation;
521 }
522 else
523 {
524 // no disks to export:
525 ulTotalOperationsWeight = 1;
526 m->ulWeightPerOperation = 1;
527 }
528
529 Log(("Setting up progress object: ulTotalMB = %d, cDisks = %d, => cOperations = %d, ulTotalOperationsWeight = %d, m->ulWeightPerOperation = %d\n",
530 ulTotalMB, cDisks, cOperations, ulTotalOperationsWeight, m->ulWeightPerOperation));
531
532 rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
533 bstrDescription,
534 TRUE /* aCancelable */,
535 cOperations, // ULONG cOperations,
536 ulTotalOperationsWeight, // ULONG ulTotalOperationsWeight,
537 bstrDescription, // CBSTR bstrFirstOperationDescription,
538 m->ulWeightPerOperation); // ULONG ulFirstOperationWeight,
539 return rc;
540}
541
542HRESULT Appliance::setUpProgressImportS3(ComObjPtr<Progress> &pProgress, const Bstr &bstrDescription)
543{
544 HRESULT rc;
545
546 /* Create the progress object */
547 pProgress.createObject();
548
549 /* Weigh the disk images according to their sizes */
550 uint32_t ulTotalMB;
551 uint32_t cDisks;
552 disksWeight(ulTotalMB, cDisks);
553
554 ULONG cOperations = 1 + 1 + 1 + cDisks; // one op per disk plus 1 for init, plus 1 for the manifest file & 1 plus for the import */
555
556 ULONG ulTotalOperationsWeight = ulTotalMB;
557 if (!ulTotalOperationsWeight)
558 // no disks to export:
559 ulTotalOperationsWeight = 1;
560
561 ULONG ulImportWeight = (ULONG)((double)ulTotalOperationsWeight * 50 / 100); // use 50% for import
562 ulTotalOperationsWeight += ulImportWeight;
563
564 m->ulWeightPerOperation = ulImportWeight; /* save for using later */
565
566 ULONG ulInitWeight = (ULONG)((double)ulTotalOperationsWeight * 0.1 / 100); // use 0.1% for init
567 ulTotalOperationsWeight += ulInitWeight;
568
569 Log(("Setting up progress object: ulTotalMB = %d, cDisks = %d, => cOperations = %d, ulTotalOperationsWeight = %d, m->ulWeightPerOperation = %d\n",
570 ulTotalMB, cDisks, cOperations, ulTotalOperationsWeight, m->ulWeightPerOperation));
571
572 rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
573 bstrDescription,
574 TRUE /* aCancelable */,
575 cOperations, // ULONG cOperations,
576 ulTotalOperationsWeight, // ULONG ulTotalOperationsWeight,
577 Bstr(tr("Init")), // CBSTR bstrFirstOperationDescription,
578 ulInitWeight); // ULONG ulFirstOperationWeight,
579 return rc;
580}
581
582HRESULT Appliance::setUpProgressWriteS3(ComObjPtr<Progress> &pProgress, const Bstr &bstrDescription)
583{
584 HRESULT rc;
585
586 /* Create the progress object */
587 pProgress.createObject();
588
589 /* Weigh the disk images according to their sizes */
590 uint32_t ulTotalMB;
591 uint32_t cDisks;
592 disksWeight(ulTotalMB, cDisks);
593
594 ULONG cOperations = 1 + 1 + 1 + cDisks; // one op per disk plus 1 for the OVF, plus 1 for the mf & 1 plus to the temporary creation */
595
596 ULONG ulTotalOperationsWeight;
597 if (ulTotalMB)
598 {
599 m->ulWeightPerOperation = (ULONG)((double)ulTotalMB * 1 / 100); // use 1% of the progress for OVF file upload (we didn't know the size at this point)
600 ulTotalOperationsWeight = ulTotalMB + m->ulWeightPerOperation;
601 }
602 else
603 {
604 // no disks to export:
605 ulTotalOperationsWeight = 1;
606 m->ulWeightPerOperation = 1;
607 }
608 ULONG ulOVFCreationWeight = (ULONG)((double)ulTotalOperationsWeight * 50.0 / 100.0); /* Use 50% for the creation of the OVF & the disks */
609 ulTotalOperationsWeight += ulOVFCreationWeight;
610
611 Log(("Setting up progress object: ulTotalMB = %d, cDisks = %d, => cOperations = %d, ulTotalOperationsWeight = %d, m->ulWeightPerOperation = %d\n",
612 ulTotalMB, cDisks, cOperations, ulTotalOperationsWeight, m->ulWeightPerOperation));
613
614 rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
615 bstrDescription,
616 TRUE /* aCancelable */,
617 cOperations, // ULONG cOperations,
618 ulTotalOperationsWeight, // ULONG ulTotalOperationsWeight,
619 bstrDescription, // CBSTR bstrFirstOperationDescription,
620 ulOVFCreationWeight); // ULONG ulFirstOperationWeight,
621 return rc;
622}
623
624void Appliance::parseURI(Utf8Str strUri, LocationInfo &locInfo) const
625{
626 /* Check the URI for the protocol */
627 if (strUri.startsWith("file://", Utf8Str::CaseInsensitive)) /* File based */
628 {
629 locInfo.storageType = VFSType_File;
630 strUri = strUri.substr(sizeof("file://") - 1);
631 }
632 else if (strUri.startsWith("SunCloud://", Utf8Str::CaseInsensitive)) /* Sun Cloud service */
633 {
634 locInfo.storageType = VFSType_S3;
635 strUri = strUri.substr(sizeof("SunCloud://") - 1);
636 }
637 else if (strUri.startsWith("S3://", Utf8Str::CaseInsensitive)) /* S3 service */
638 {
639 locInfo.storageType = VFSType_S3;
640 strUri = strUri.substr(sizeof("S3://") - 1);
641 }
642 else if (strUri.startsWith("webdav://", Utf8Str::CaseInsensitive)) /* webdav service */
643 throw E_NOTIMPL;
644
645 /* Not necessary on a file based URI */
646 if (locInfo.storageType != VFSType_File)
647 {
648 size_t uppos = strUri.find("@"); /* username:password combo */
649 if (uppos != Utf8Str::npos)
650 {
651 locInfo.strUsername = strUri.substr(0, uppos);
652 strUri = strUri.substr(uppos + 1);
653 size_t upos = locInfo.strUsername.find(":");
654 if (upos != Utf8Str::npos)
655 {
656 locInfo.strPassword = locInfo.strUsername.substr(upos + 1);
657 locInfo.strUsername = locInfo.strUsername.substr(0, upos);
658 }
659 }
660 size_t hpos = strUri.find("/"); /* hostname part */
661 if (hpos != Utf8Str::npos)
662 {
663 locInfo.strHostname = strUri.substr(0, hpos);
664 strUri = strUri.substr(hpos);
665 }
666 }
667
668 locInfo.strPath = strUri;
669}
670
671void Appliance::parseBucket(Utf8Str &aPath, Utf8Str &aBucket) const
672{
673 /* Buckets are S3 specific. So parse the bucket out of the file path */
674 if (!aPath.startsWith("/"))
675 throw setError(E_INVALIDARG,
676 tr("The path '%s' must start with /"), aPath.c_str());
677 size_t bpos = aPath.find("/", 1);
678 if (bpos != Utf8Str::npos)
679 {
680 aBucket = aPath.substr(1, bpos - 1); /* The bucket without any slashes */
681 aPath = aPath.substr(bpos); /* The rest of the file path */
682 }
683 /* If there is no bucket name provided reject it */
684 if (aBucket.isEmpty())
685 throw setError(E_INVALIDARG,
686 tr("You doesn't provide a bucket name in the URI '%s'"), aPath.c_str());
687}
688
689Utf8Str Appliance::manifestFileName(Utf8Str aPath) const
690{
691 /* Get the name part */
692 char *pszMfName = RTStrDup(RTPathFilename(aPath.c_str()));
693 /* Strip any extensions */
694 RTPathStripExt(pszMfName);
695 /* Path without the filename */
696 aPath.stripFilename();
697 /* Format the manifest path */
698 Utf8StrFmt strMfFile("%s/%s.mf", aPath.c_str(), pszMfName);
699 RTStrFree(pszMfName);
700 return strMfFile;
701}
702
703struct Appliance::TaskOVF
704{
705 TaskOVF(Appliance *aThat)
706 : pAppliance(aThat)
707 , rc(S_OK) {}
708
709 static int updateProgress(unsigned uPercent, void *pvUser);
710
711 LocationInfo locInfo;
712 Appliance *pAppliance;
713 ComObjPtr<Progress> progress;
714 HRESULT rc;
715};
716
717struct Appliance::TaskImportOVF: Appliance::TaskOVF
718{
719 enum TaskType
720 {
721 Read,
722 Import
723 };
724
725 TaskImportOVF(Appliance *aThat)
726 : TaskOVF(aThat)
727 , taskType(Read) {}
728
729 int startThread();
730
731 TaskType taskType;
732};
733
734struct Appliance::TaskExportOVF: Appliance::TaskOVF
735{
736 enum OVFFormat
737 {
738 unspecified,
739 OVF_0_9,
740 OVF_1_0
741 };
742 enum TaskType
743 {
744 Write
745 };
746
747 TaskExportOVF(Appliance *aThat)
748 : TaskOVF(aThat)
749 , taskType(Write) {}
750
751 int startThread();
752
753 TaskType taskType;
754 OVFFormat enFormat;
755};
756
757struct MyHardDiskAttachment
758{
759 Bstr bstrUuid;
760 ComPtr<IMachine> pMachine;
761 Bstr controllerType;
762 int32_t lChannel;
763 int32_t lDevice;
764};
765
766/* static */
767int Appliance::TaskOVF::updateProgress(unsigned uPercent, void *pvUser)
768{
769 Appliance::TaskOVF* pTask = *(Appliance::TaskOVF**)pvUser;
770
771 if (pTask &&
772 !pTask->progress.isNull())
773 {
774 BOOL fCanceled;
775 pTask->progress->COMGETTER(Canceled)(&fCanceled);
776 if (fCanceled)
777 return -1;
778 pTask->progress->SetCurrentOperationProgress(uPercent);
779 }
780 return VINF_SUCCESS;
781}
782
783HRESULT Appliance::readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
784{
785 /* Initialize our worker task */
786 std::auto_ptr<TaskImportOVF> task(new TaskImportOVF(this));
787 /* What should the task do */
788 task->taskType = TaskImportOVF::Read;
789 /* Copy the current location info to the task */
790 task->locInfo = aLocInfo;
791
792 BstrFmt bstrDesc = BstrFmt(tr("Read appliance '%s'"),
793 aLocInfo.strPath.c_str());
794 HRESULT rc;
795 /* Create the progress object */
796 aProgress.createObject();
797 if (task->locInfo.storageType == VFSType_File)
798 {
799 /* 1 operation only */
800 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
801 bstrDesc,
802 TRUE /* aCancelable */);
803 }
804 else
805 {
806 /* 4/5 is downloading, 1/5 is reading */
807 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
808 bstrDesc,
809 TRUE /* aCancelable */,
810 2, // ULONG cOperations,
811 5, // ULONG ulTotalOperationsWeight,
812 BstrFmt(tr("Download appliance '%s'"),
813 aLocInfo.strPath.c_str()), // CBSTR bstrFirstOperationDescription,
814 4); // ULONG ulFirstOperationWeight,
815 }
816 if (FAILED(rc)) throw rc;
817
818 task->progress = aProgress;
819
820 rc = task->startThread();
821 if (FAILED(rc)) throw rc;
822
823 /* Don't destruct on success */
824 task.release();
825
826 return rc;
827}
828
829HRESULT Appliance::importImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
830{
831 /* Initialize our worker task */
832 std::auto_ptr<TaskImportOVF> task(new TaskImportOVF(this));
833 /* What should the task do */
834 task->taskType = TaskImportOVF::Import;
835 /* Copy the current location info to the task */
836 task->locInfo = aLocInfo;
837
838 Bstr progressDesc = BstrFmt(tr("Import appliance '%s'"),
839 aLocInfo.strPath.c_str());
840
841 HRESULT rc = S_OK;
842
843 /* todo: This progress init stuff should be done a little bit more generic */
844 if (task->locInfo.storageType == VFSType_File)
845 rc = setUpProgressFS(aProgress, progressDesc);
846 else
847 rc = setUpProgressImportS3(aProgress, progressDesc);
848 if (FAILED(rc)) throw rc;
849
850 task->progress = aProgress;
851
852 rc = task->startThread();
853 if (FAILED(rc)) throw rc;
854
855 /* Don't destruct on success */
856 task.release();
857
858 return rc;
859}
860
861/**
862 * Worker thread implementation for Read() (ovf reader).
863 * @param aThread
864 * @param pvUser
865 */
866/* static */
867DECLCALLBACK(int) Appliance::taskThreadImportOVF(RTTHREAD /* aThread */, void *pvUser)
868{
869 std::auto_ptr<TaskImportOVF> task(static_cast<TaskImportOVF*>(pvUser));
870 AssertReturn(task.get(), VERR_GENERAL_FAILURE);
871
872 Appliance *pAppliance = task->pAppliance;
873
874 LogFlowFuncEnter();
875 LogFlowFunc(("Appliance %p\n", pAppliance));
876
877 HRESULT rc = S_OK;
878
879 switch(task->taskType)
880 {
881 case TaskImportOVF::Read:
882 {
883 if (task->locInfo.storageType == VFSType_File)
884 rc = pAppliance->readFS(task.get());
885 else if (task->locInfo.storageType == VFSType_S3)
886 rc = pAppliance->readS3(task.get());
887 break;
888 }
889 case TaskImportOVF::Import:
890 {
891 if (task->locInfo.storageType == VFSType_File)
892 rc = pAppliance->importFS(task.get());
893 else if (task->locInfo.storageType == VFSType_S3)
894 rc = pAppliance->importS3(task.get());
895 break;
896 }
897 }
898
899 LogFlowFunc(("rc=%Rhrc\n", rc));
900 LogFlowFuncLeave();
901
902 return VINF_SUCCESS;
903}
904
905int Appliance::TaskImportOVF::startThread()
906{
907 int vrc = RTThreadCreate(NULL, Appliance::taskThreadImportOVF, this,
908 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
909 "Appliance::Task");
910
911 ComAssertMsgRCRet(vrc,
912 ("Could not create taskThreadImportOVF (%Rrc)\n", vrc), E_FAIL);
913
914 return S_OK;
915}
916
917int Appliance::readFS(TaskImportOVF *pTask)
918{
919 LogFlowFuncEnter();
920 LogFlowFunc(("Appliance %p\n", this));
921
922 AutoCaller autoCaller(this);
923 if (FAILED(autoCaller.rc())) return autoCaller.rc();
924
925 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
926
927 HRESULT rc = S_OK;
928
929 try
930 {
931 /* Read & parse the XML structure of the OVF file */
932 m->pReader = new OVFReader(pTask->locInfo.strPath);
933 /* Create the SHA1 sum of the OVF file for later validation */
934 char *pszDigest;
935 int vrc = RTSha1Digest(pTask->locInfo.strPath.c_str(), &pszDigest);
936 if (RT_FAILURE(vrc))
937 throw setError(VBOX_E_FILE_ERROR,
938 tr("Couldn't calculate SHA1 digest for file '%s' (%Rrc)"),
939 RTPathFilename(pTask->locInfo.strPath.c_str()), vrc);
940 m->strOVFSHA1Digest = pszDigest;
941 RTStrFree(pszDigest);
942 }
943 catch(xml::Error &x)
944 {
945 rc = setError(VBOX_E_FILE_ERROR,
946 x.what());
947 }
948
949 pTask->rc = rc;
950
951 if (!pTask->progress.isNull())
952 pTask->progress->notifyComplete(rc);
953
954 LogFlowFunc(("rc=%Rhrc\n", rc));
955 LogFlowFuncLeave();
956
957 return VINF_SUCCESS;
958}
959
960int Appliance::readS3(TaskImportOVF *pTask)
961{
962 LogFlowFuncEnter();
963 LogFlowFunc(("Appliance %p\n", this));
964
965 AutoCaller autoCaller(this);
966 if (FAILED(autoCaller.rc())) return autoCaller.rc();
967
968 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
969
970 HRESULT rc = S_OK;
971 int vrc = VINF_SUCCESS;
972 RTS3 hS3 = NIL_RTS3;
973 char szOSTmpDir[RTPATH_MAX];
974 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
975 /* The template for the temporary directory created below */
976 char *pszTmpDir;
977 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
978 list< pair<Utf8Str, ULONG> > filesList;
979 Utf8Str strTmpOvf;
980
981 try
982 {
983 /* Extract the bucket */
984 Utf8Str tmpPath = pTask->locInfo.strPath;
985 Utf8Str bucket;
986 parseBucket(tmpPath, bucket);
987
988 /* We need a temporary directory which we can put the OVF file & all
989 * disk images in */
990 vrc = RTDirCreateTemp(pszTmpDir);
991 if (RT_FAILURE(vrc))
992 throw setError(VBOX_E_FILE_ERROR,
993 tr("Cannot create temporary directory '%s'"), pszTmpDir);
994
995 /* The temporary name of the target OVF file */
996 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
997
998 /* Next we have to download the OVF */
999 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1000 if(RT_FAILURE(vrc))
1001 throw setError(VBOX_E_IPRT_ERROR,
1002 tr("Cannot create S3 service handler"));
1003 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1004
1005 /* Get it */
1006 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
1007 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
1008 if (RT_FAILURE(vrc))
1009 {
1010 if(vrc == VERR_S3_CANCELED)
1011 throw S_OK; /* todo: !!!!!!!!!!!!! */
1012 else if(vrc == VERR_S3_ACCESS_DENIED)
1013 throw setError(E_ACCESSDENIED,
1014 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
1015 else if(vrc == VERR_S3_NOT_FOUND)
1016 throw setError(VBOX_E_FILE_ERROR,
1017 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1018 else
1019 throw setError(VBOX_E_IPRT_ERROR,
1020 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1021 }
1022
1023 /* Close the connection early */
1024 RTS3Destroy(hS3);
1025 hS3 = NIL_RTS3;
1026
1027 if (!pTask->progress.isNull())
1028 pTask->progress->SetNextOperation(Bstr(tr("Reading")), 1);
1029
1030 /* Prepare the temporary reading of the OVF */
1031 ComObjPtr<Progress> progress;
1032 LocationInfo li;
1033 li.strPath = strTmpOvf;
1034 /* Start the reading from the fs */
1035 rc = readImpl(li, progress);
1036 if (FAILED(rc)) throw rc;
1037
1038 /* Unlock the appliance for the reading thread */
1039 appLock.release();
1040 /* Wait until the reading is done, but report the progress back to the
1041 caller */
1042 ComPtr<IProgress> progressInt(progress);
1043 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
1044
1045 /* Again lock the appliance for the next steps */
1046 appLock.acquire();
1047 }
1048 catch(HRESULT aRC)
1049 {
1050 rc = aRC;
1051 }
1052 /* Cleanup */
1053 RTS3Destroy(hS3);
1054 /* Delete all files which where temporary created */
1055 if (RTPathExists(strTmpOvf.c_str()))
1056 {
1057 vrc = RTFileDelete(strTmpOvf.c_str());
1058 if(RT_FAILURE(vrc))
1059 rc = setError(VBOX_E_FILE_ERROR,
1060 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
1061 }
1062 /* Delete the temporary directory */
1063 if (RTPathExists(pszTmpDir))
1064 {
1065 vrc = RTDirRemove(pszTmpDir);
1066 if(RT_FAILURE(vrc))
1067 rc = setError(VBOX_E_FILE_ERROR,
1068 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1069 }
1070 if (pszTmpDir)
1071 RTStrFree(pszTmpDir);
1072
1073 pTask->rc = rc;
1074
1075 if (!pTask->progress.isNull())
1076 pTask->progress->notifyComplete(rc);
1077
1078 LogFlowFunc(("rc=%Rhrc\n", rc));
1079 LogFlowFuncLeave();
1080
1081 return VINF_SUCCESS;
1082}
1083
1084int Appliance::importFS(TaskImportOVF *pTask)
1085{
1086 LogFlowFuncEnter();
1087 LogFlowFunc(("Appliance %p\n", this));
1088
1089 AutoCaller autoCaller(this);
1090 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1091
1092 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1093
1094 HRESULT rc = S_OK;
1095
1096 // rollback for errors:
1097 // a list of images that we created/imported
1098 list<MyHardDiskAttachment> llHardDiskAttachments;
1099 list< ComPtr<IMedium> > llHardDisksCreated;
1100 list<Bstr> llMachinesRegistered; // list of string UUIDs
1101
1102 ComPtr<ISession> session;
1103 bool fSessionOpen = false;
1104 rc = session.createInprocObject(CLSID_Session);
1105 if (FAILED(rc)) return rc;
1106
1107 const OVFReader &reader = *m->pReader;
1108 // this is safe to access because this thread only gets started
1109 // if pReader != NULL
1110
1111 /* If an manifest file exists, verify the content. Therefore we need all
1112 * files which are referenced by the OVF & the OVF itself */
1113 Utf8Str strMfFile = manifestFileName(pTask->locInfo.strPath);
1114 list<Utf8Str> filesList;
1115 if (RTPathExists(strMfFile.c_str()))
1116 {
1117 Utf8Str strSrcDir(pTask->locInfo.strPath);
1118 strSrcDir.stripFilename();
1119 /* Add every disks of every virtual system to an internal list */
1120 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1121 for (it = m->virtualSystemDescriptions.begin();
1122 it != m->virtualSystemDescriptions.end();
1123 ++it)
1124 {
1125 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1126 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1127 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1128 for (itH = avsdeHDs.begin();
1129 itH != avsdeHDs.end();
1130 ++itH)
1131 {
1132 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1133 /* Find the disk from the OVF's disk list */
1134 DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1135 const DiskImage &di = itDiskImage->second;
1136 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1137 filesList.push_back(strSrcFilePath);
1138 }
1139 }
1140 /* Create the test list */
1141 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST)*(filesList.size()+1));
1142 pTestList[0].pszTestFile = (char*)pTask->locInfo.strPath.c_str();
1143 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1144 int vrc = VINF_SUCCESS;
1145 size_t i = 1;
1146 list<Utf8Str>::const_iterator it1;
1147 for (it1 = filesList.begin();
1148 it1 != filesList.end();
1149 ++it1, ++i)
1150 {
1151 char* pszDigest;
1152 vrc = RTSha1Digest((*it1).c_str(), &pszDigest);
1153 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1154 pTestList[i].pszTestDigest = pszDigest;
1155 }
1156 size_t cIndexOnError;
1157 vrc = RTManifestVerify(strMfFile.c_str(), pTestList, filesList.size() + 1, &cIndexOnError);
1158 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1159 rc = setError(VBOX_E_FILE_ERROR,
1160 tr("The SHA1 digest of '%s' doesn't match to the one in '%s'"),
1161 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1162 RTPathFilename(strMfFile.c_str()));
1163 else if (RT_FAILURE(vrc))
1164 rc = setError(VBOX_E_FILE_ERROR,
1165 tr("Couldn't verify the content of '%s' against the available files (%Rrc)"),
1166 RTPathFilename(strMfFile.c_str()),
1167 vrc);
1168 /* Cleanup */
1169 for (size_t j = 1;
1170 j < filesList.size();
1171 ++j)
1172 RTStrFree(pTestList[j].pszTestDigest);
1173 RTMemFree(pTestList);
1174 if (FAILED(rc))
1175 {
1176 /* Return on error */
1177 pTask->rc = rc;
1178
1179 if (!pTask->progress.isNull())
1180 pTask->progress->notifyComplete(rc);
1181 return rc;
1182 }
1183 }
1184
1185 list<VirtualSystem>::const_iterator it;
1186 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1187 /* Iterate through all virtual systems of that appliance */
1188 size_t i = 0;
1189 for (it = reader.m_llVirtualSystems.begin(),
1190 it1 = m->virtualSystemDescriptions.begin();
1191 it != reader.m_llVirtualSystems.end();
1192 ++it, ++it1, ++i)
1193 {
1194 const VirtualSystem &vsysThis = *it;
1195 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1196
1197 ComPtr<IMachine> pNewMachine;
1198
1199 /* Catch possible errors */
1200 try
1201 {
1202 /* Guest OS type */
1203 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1204 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1205 if (vsdeOS.size() < 1)
1206 throw setError(VBOX_E_FILE_ERROR,
1207 tr("Missing guest OS type"));
1208 const Utf8Str &strOsTypeVBox = vsdeOS.front()->strVbox;
1209
1210 /* Now that we know the base system get our internal defaults based on that. */
1211 ComPtr<IGuestOSType> osType;
1212 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), osType.asOutParam());
1213 if (FAILED(rc)) throw rc;
1214
1215 /* Create the machine */
1216 /* First get the name */
1217 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1218 if (vsdeName.size() < 1)
1219 throw setError(VBOX_E_FILE_ERROR,
1220 tr("Missing VM name"));
1221 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
1222 rc = mVirtualBox->CreateMachine(Bstr(strNameVBox), Bstr(strOsTypeVBox),
1223 Bstr(), Bstr(),
1224 pNewMachine.asOutParam());
1225 if (FAILED(rc)) throw rc;
1226
1227 // and the description
1228 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1229 if (vsdeDescription.size())
1230 {
1231 const Utf8Str &strDescription = vsdeDescription.front()->strVbox;
1232 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1233 if (FAILED(rc)) throw rc;
1234 }
1235
1236 /* CPU count */
1237 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
1238 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1239 const Utf8Str &cpuVBox = vsdeCPU.front()->strVbox;
1240 ULONG tmpCount = (ULONG)RTStrToUInt64(cpuVBox.c_str());
1241 rc = pNewMachine->COMSETTER(CPUCount)(tmpCount);
1242 if (FAILED(rc)) throw rc;
1243 bool fEnableIOApic = false;
1244 /* We need HWVirt & IO-APIC if more than one CPU is requested */
1245 if (tmpCount > 1)
1246 {
1247 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1248 if (FAILED(rc)) throw rc;
1249
1250 fEnableIOApic = true;
1251 }
1252
1253 /* RAM */
1254 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1255 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1256 const Utf8Str &memoryVBox = vsdeRAM.front()->strVbox;
1257 ULONG tt = (ULONG)RTStrToUInt64(memoryVBox.c_str());
1258 rc = pNewMachine->COMSETTER(MemorySize)(tt);
1259 if (FAILED(rc)) throw rc;
1260
1261 /* VRAM */
1262 /* Get the recommended VRAM for this guest OS type */
1263 ULONG vramVBox;
1264 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1265 if (FAILED(rc)) throw rc;
1266
1267 /* Set the VRAM */
1268 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1269 if (FAILED(rc)) throw rc;
1270
1271 /* I/O APIC: so far we have no setting for this. Enable it if we
1272 import a Windows VM because if if Windows was installed without IOAPIC,
1273 it will not mind finding an one later on, but if Windows was installed
1274 _with_ an IOAPIC, it will bluescreen if it's not found */
1275 Bstr bstrFamilyId;
1276 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1277 if (FAILED(rc)) throw rc;
1278
1279 Utf8Str strFamilyId(bstrFamilyId);
1280 if (strFamilyId == "Windows")
1281 fEnableIOApic = true;
1282
1283 /* If IP-APIC should be enabled could be have different reasons.
1284 See CPU count & the Win test above. Here we enable it if it was
1285 previously requested. */
1286 if (fEnableIOApic)
1287 {
1288 ComPtr<IBIOSSettings> pBIOSSettings;
1289 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1290 if (FAILED(rc)) throw rc;
1291
1292 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1293 if (FAILED(rc)) throw rc;
1294 }
1295
1296 /* Audio Adapter */
1297 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1298 /* @todo: we support one audio adapter only */
1299 if (vsdeAudioAdapter.size() > 0)
1300 {
1301 const Utf8Str& audioAdapterVBox = vsdeAudioAdapter.front()->strVbox;
1302 if (audioAdapterVBox.compare("null", Utf8Str::CaseInsensitive) != 0)
1303 {
1304 uint32_t audio = RTStrToUInt32(audioAdapterVBox.c_str());
1305 ComPtr<IAudioAdapter> audioAdapter;
1306 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1307 if (FAILED(rc)) throw rc;
1308 rc = audioAdapter->COMSETTER(Enabled)(true);
1309 if (FAILED(rc)) throw rc;
1310 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1311 if (FAILED(rc)) throw rc;
1312 }
1313 }
1314
1315#ifdef VBOX_WITH_USB
1316 /* USB Controller */
1317 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1318 // USB support is enabled if there's at least one such entry; to disable USB support,
1319 // the type of the USB item would have been changed to "ignore"
1320 bool fUSBEnabled = vsdeUSBController.size() > 0;
1321
1322 ComPtr<IUSBController> usbController;
1323 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1324 if (FAILED(rc)) throw rc;
1325 rc = usbController->COMSETTER(Enabled)(fUSBEnabled);
1326 if (FAILED(rc)) throw rc;
1327#endif /* VBOX_WITH_USB */
1328
1329 /* Change the network adapters */
1330 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1331 if (vsdeNW.size() == 0)
1332 {
1333 /* No network adapters, so we have to disable our default one */
1334 ComPtr<INetworkAdapter> nwVBox;
1335 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1336 if (FAILED(rc)) throw rc;
1337 rc = nwVBox->COMSETTER(Enabled)(false);
1338 if (FAILED(rc)) throw rc;
1339 }
1340 else
1341 {
1342 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1343 /* Iterate through all network cards. We support 8 network adapters
1344 * at the maximum. (@todo: warn if there are more!) */
1345 size_t a = 0;
1346 for (nwIt = vsdeNW.begin();
1347 (nwIt != vsdeNW.end() && a < SchemaDefs::NetworkAdapterCount);
1348 ++nwIt, ++a)
1349 {
1350 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1351
1352 const Utf8Str &nwTypeVBox = pvsys->strVbox;
1353 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1354 ComPtr<INetworkAdapter> pNetworkAdapter;
1355 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1356 if (FAILED(rc)) throw rc;
1357 /* Enable the network card & set the adapter type */
1358 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1359 if (FAILED(rc)) throw rc;
1360 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1361 if (FAILED(rc)) throw rc;
1362
1363 // default is NAT; change to "bridged" if extra conf says so
1364 if (!pvsys->strExtraConfig.compare("type=Bridged", Utf8Str::CaseInsensitive))
1365 {
1366 /* Attach to the right interface */
1367 rc = pNetworkAdapter->AttachToBridgedInterface();
1368 if (FAILED(rc)) throw rc;
1369 ComPtr<IHost> host;
1370 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1371 if (FAILED(rc)) throw rc;
1372 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1373 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1374 if (FAILED(rc)) throw rc;
1375 /* We search for the first host network interface which
1376 * is usable for bridged networking */
1377 for (size_t j = 0;
1378 j < nwInterfaces.size();
1379 ++j)
1380 {
1381 HostNetworkInterfaceType_T itype;
1382 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1383 if (FAILED(rc)) throw rc;
1384 if (itype == HostNetworkInterfaceType_Bridged)
1385 {
1386 Bstr name;
1387 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1388 if (FAILED(rc)) throw rc;
1389 /* Set the interface name to attach to */
1390 pNetworkAdapter->COMSETTER(HostInterface)(name);
1391 if (FAILED(rc)) throw rc;
1392 break;
1393 }
1394 }
1395 }
1396 /* Next test for host only interfaces */
1397 else if (!pvsys->strExtraConfig.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1398 {
1399 /* Attach to the right interface */
1400 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1401 if (FAILED(rc)) throw rc;
1402 ComPtr<IHost> host;
1403 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1404 if (FAILED(rc)) throw rc;
1405 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1406 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1407 if (FAILED(rc)) throw rc;
1408 /* We search for the first host network interface which
1409 * is usable for host only networking */
1410 for (size_t j = 0;
1411 j < nwInterfaces.size();
1412 ++j)
1413 {
1414 HostNetworkInterfaceType_T itype;
1415 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1416 if (FAILED(rc)) throw rc;
1417 if (itype == HostNetworkInterfaceType_HostOnly)
1418 {
1419 Bstr name;
1420 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1421 if (FAILED(rc)) throw rc;
1422 /* Set the interface name to attach to */
1423 pNetworkAdapter->COMSETTER(HostInterface)(name);
1424 if (FAILED(rc)) throw rc;
1425 break;
1426 }
1427 }
1428 }
1429 }
1430 }
1431
1432 /* Hard disk controller IDE */
1433 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1434 if (vsdeHDCIDE.size() > 1)
1435 throw setError(VBOX_E_FILE_ERROR,
1436 tr("Too many IDE controllers in OVF; import facility only supports one"));
1437 if (vsdeHDCIDE.size() == 1)
1438 {
1439 ComPtr<IStorageController> pController;
1440 rc = pNewMachine->AddStorageController(Bstr("IDE Controller"), StorageBus_IDE, pController.asOutParam());
1441 if (FAILED(rc)) throw rc;
1442
1443 const char *pcszIDEType = vsdeHDCIDE.front()->strVbox.c_str();
1444 if (!strcmp(pcszIDEType, "PIIX3"))
1445 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1446 else if (!strcmp(pcszIDEType, "PIIX4"))
1447 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1448 else if (!strcmp(pcszIDEType, "ICH6"))
1449 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1450 else
1451 throw setError(VBOX_E_FILE_ERROR,
1452 tr("Invalid IDE controller type \"%s\""),
1453 pcszIDEType);
1454 if (FAILED(rc)) throw rc;
1455 }
1456#ifdef VBOX_WITH_AHCI
1457 /* Hard disk controller SATA */
1458 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1459 if (vsdeHDCSATA.size() > 1)
1460 throw setError(VBOX_E_FILE_ERROR,
1461 tr("Too many SATA controllers in OVF; import facility only supports one"));
1462 if (vsdeHDCSATA.size() > 0)
1463 {
1464 ComPtr<IStorageController> pController;
1465 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVbox;
1466 if (hdcVBox == "AHCI")
1467 {
1468 rc = pNewMachine->AddStorageController(Bstr("SATA Controller"), StorageBus_SATA, pController.asOutParam());
1469 if (FAILED(rc)) throw rc;
1470 }
1471 else
1472 throw setError(VBOX_E_FILE_ERROR,
1473 tr("Invalid SATA controller type \"%s\""),
1474 hdcVBox.c_str());
1475 }
1476#endif /* VBOX_WITH_AHCI */
1477
1478#ifdef VBOX_WITH_LSILOGIC
1479 /* Hard disk controller SCSI */
1480 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1481 if (vsdeHDCSCSI.size() > 1)
1482 throw setError(VBOX_E_FILE_ERROR,
1483 tr("Too many SCSI controllers in OVF; import facility only supports one"));
1484 if (vsdeHDCSCSI.size() > 0)
1485 {
1486 ComPtr<IStorageController> pController;
1487 StorageControllerType_T controllerType;
1488 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVbox;
1489 if (hdcVBox == "LsiLogic")
1490 controllerType = StorageControllerType_LsiLogic;
1491 else if (hdcVBox == "BusLogic")
1492 controllerType = StorageControllerType_BusLogic;
1493 else
1494 throw setError(VBOX_E_FILE_ERROR,
1495 tr("Invalid SCSI controller type \"%s\""),
1496 hdcVBox.c_str());
1497
1498 rc = pNewMachine->AddStorageController(Bstr("SCSI Controller"), StorageBus_SCSI, pController.asOutParam());
1499 if (FAILED(rc)) throw rc;
1500 rc = pController->COMSETTER(ControllerType)(controllerType);
1501 if (FAILED(rc)) throw rc;
1502 }
1503#endif /* VBOX_WITH_LSILOGIC */
1504
1505 /* Now its time to register the machine before we add any hard disks */
1506 rc = mVirtualBox->RegisterMachine(pNewMachine);
1507 if (FAILED(rc)) throw rc;
1508
1509 Bstr bstrNewMachineId;
1510 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
1511 if (FAILED(rc)) throw rc;
1512
1513 // store new machine for roll-back in case of errors
1514 llMachinesRegistered.push_back(bstrNewMachineId);
1515
1516 // Add floppies and CD-ROMs to the appropriate controllers.
1517 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1518 if (vsdeFloppy.size() > 1)
1519 throw setError(VBOX_E_FILE_ERROR,
1520 tr("Too many floppy controllers in OVF; import facility only supports one"));
1521 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1522 if ( (vsdeFloppy.size() > 0)
1523 || (vsdeCDROM.size() > 0)
1524 )
1525 {
1526 // If there's an error here we need to close the session, so
1527 // we need another try/catch block.
1528
1529 try
1530 {
1531 /* In order to attach things we need to open a session
1532 * for the new machine */
1533 rc = mVirtualBox->OpenSession(session, bstrNewMachineId);
1534 if (FAILED(rc)) throw rc;
1535 fSessionOpen = true;
1536
1537 ComPtr<IMachine> sMachine;
1538 rc = session->COMGETTER(Machine)(sMachine.asOutParam());
1539 if (FAILED(rc)) throw rc;
1540
1541 // floppy first
1542 if (vsdeFloppy.size() == 1)
1543 {
1544 ComPtr<IStorageController> pController;
1545 rc = sMachine->AddStorageController(Bstr("Floppy Controller"), StorageBus_Floppy, pController.asOutParam());
1546 if (FAILED(rc)) throw rc;
1547
1548 Bstr bstrName;
1549 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1550 if (FAILED(rc)) throw rc;
1551
1552 // this is for rollback later
1553 MyHardDiskAttachment mhda;
1554 mhda.bstrUuid = bstrNewMachineId;
1555 mhda.pMachine = pNewMachine;
1556 mhda.controllerType = bstrName;
1557 mhda.lChannel = 0;
1558 mhda.lDevice = 0;
1559
1560 Log(("Attaching floppy\n"));
1561
1562 rc = sMachine->AttachDevice(mhda.controllerType,
1563 mhda.lChannel,
1564 mhda.lDevice,
1565 DeviceType_Floppy,
1566 Bstr(""));
1567 if (FAILED(rc)) throw rc;
1568
1569 llHardDiskAttachments.push_back(mhda);
1570 }
1571
1572
1573 // CD-ROMs next
1574 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
1575 jt != vsdeCDROM.end();
1576 ++jt)
1577 {
1578 // for now always attach to secondary master on IDE controller;
1579 // there seems to be no useful information in OVF where else to
1580 // attach jt (@todo test with latest versions of OVF software)
1581
1582 // find the IDE controller
1583 const HardDiskController *pController = NULL;
1584 for (ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
1585 kt != vsysThis.mapControllers.end();
1586 ++kt)
1587 {
1588 if (kt->second.system == HardDiskController::IDE)
1589 {
1590 pController = &kt->second;
1591 }
1592 }
1593
1594 if (!pController)
1595 throw setError(VBOX_E_FILE_ERROR,
1596 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
1597
1598 // this is for rollback later
1599 MyHardDiskAttachment mhda;
1600 mhda.bstrUuid = bstrNewMachineId;
1601 mhda.pMachine = pNewMachine;
1602
1603 ConvertDiskAttachmentValues(*pController,
1604 2, // interpreted as secondary master
1605 mhda.controllerType, // Bstr
1606 mhda.lChannel,
1607 mhda.lDevice);
1608
1609 Log(("Attaching CD-ROM to channel %d on device %d\n", mhda.lChannel, mhda.lDevice));
1610
1611 rc = sMachine->AttachDevice(mhda.controllerType,
1612 mhda.lChannel,
1613 mhda.lDevice,
1614 DeviceType_DVD,
1615 Bstr(""));
1616 if (FAILED(rc)) throw rc;
1617
1618 llHardDiskAttachments.push_back(mhda);
1619 } // end for (itHD = avsdeHDs.begin();
1620
1621 rc = sMachine->SaveSettings();
1622 if (FAILED(rc)) throw rc;
1623
1624 // only now that we're done with all disks, close the session
1625 rc = session->Close();
1626 if (FAILED(rc)) throw rc;
1627 fSessionOpen = false;
1628 }
1629 catch(HRESULT /* aRC */)
1630 {
1631 if (fSessionOpen)
1632 session->Close();
1633
1634 throw;
1635 }
1636 }
1637
1638 /* Create the hard disks & connect them to the appropriate controllers. */
1639 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1640 if (avsdeHDs.size() > 0)
1641 {
1642 // If there's an error here we need to close the session, so
1643 // we need another try/catch block.
1644 ComPtr<IMedium> srcHdVBox;
1645 bool fSourceHdNeedsClosing = false;
1646
1647 try
1648 {
1649 /* In order to attach hard disks we need to open a session
1650 * for the new machine */
1651 rc = mVirtualBox->OpenSession(session, bstrNewMachineId);
1652 if (FAILED(rc)) throw rc;
1653 fSessionOpen = true;
1654
1655 /* The disk image has to be on the same place as the OVF file. So
1656 * strip the filename out of the full file path. */
1657 Utf8Str strSrcDir(pTask->locInfo.strPath);
1658 strSrcDir.stripFilename();
1659
1660 /* Iterate over all given disk images */
1661 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1662 for (itHD = avsdeHDs.begin();
1663 itHD != avsdeHDs.end();
1664 ++itHD)
1665 {
1666 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1667
1668 /* Check if the destination file exists already or the
1669 * destination path is empty. */
1670 if ( vsdeHD->strVbox.isEmpty()
1671 || RTPathExists(vsdeHD->strVbox.c_str())
1672 )
1673 /* This isn't allowed */
1674 throw setError(VBOX_E_FILE_ERROR,
1675 tr("Destination file '%s' exists",
1676 vsdeHD->strVbox.c_str()));
1677
1678 /* Find the disk from the OVF's disk list */
1679 DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1680 /* vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1681 in the virtual system's disks map under that ID and also in the global images map. */
1682 VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1683
1684 if ( itDiskImage == reader.m_mapDisks.end()
1685 || itVirtualDisk == vsysThis.mapVirtualDisks.end()
1686 )
1687 throw setError(E_FAIL,
1688 tr("Internal inconsistency looking up disk images."));
1689
1690 const DiskImage &di = itDiskImage->second;
1691 const VirtualDisk &vd = itVirtualDisk->second;
1692
1693 /* Make sure all target directories exists */
1694 rc = VirtualBox::ensureFilePathExists(vsdeHD->strVbox.c_str());
1695 if (FAILED(rc))
1696 throw rc;
1697
1698 // subprogress object for hard disk
1699 ComPtr<IProgress> pProgress2;
1700
1701 ComPtr<IMedium> dstHdVBox;
1702 /* If strHref is empty we have to create a new file */
1703 if (di.strHref.isEmpty())
1704 {
1705 /* Which format to use? */
1706 Bstr srcFormat = L"VDI";
1707 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1708 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive))
1709 srcFormat = L"VMDK";
1710 /* Create an empty hard disk */
1711 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(vsdeHD->strVbox), dstHdVBox.asOutParam());
1712 if (FAILED(rc)) throw rc;
1713
1714 /* Create a dynamic growing disk image with the given capacity */
1715 rc = dstHdVBox->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1716 if (FAILED(rc)) throw rc;
1717
1718 /* Advance to the next operation */
1719 if (!pTask->progress.isNull())
1720 pTask->progress->SetNextOperation(BstrFmt(tr("Creating virtual disk image '%s'"), vsdeHD->strVbox.c_str()),
1721 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally
1722 }
1723 else
1724 {
1725 /* Construct the source file path */
1726 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1727 /* Check if the source file exists */
1728 if (!RTPathExists(strSrcFilePath.c_str()))
1729 /* This isn't allowed */
1730 throw setError(VBOX_E_FILE_ERROR,
1731 tr("Source virtual disk image file '%s' doesn't exist"),
1732 strSrcFilePath.c_str());
1733
1734 /* Clone the disk image (this is necessary cause the id has
1735 * to be recreated for the case the same hard disk is
1736 * attached already from a previous import) */
1737
1738 /* First open the existing disk image */
1739 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1740 AccessMode_ReadOnly,
1741 false, Bstr(""), false, Bstr(""),
1742 srcHdVBox.asOutParam());
1743 if (FAILED(rc)) throw rc;
1744 fSourceHdNeedsClosing = true;
1745
1746 /* We need the format description of the source disk image */
1747 Bstr srcFormat;
1748 rc = srcHdVBox->COMGETTER(Format)(srcFormat.asOutParam());
1749 if (FAILED(rc)) throw rc;
1750 /* Create a new hard disk interface for the destination disk image */
1751 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(vsdeHD->strVbox), dstHdVBox.asOutParam());
1752 if (FAILED(rc)) throw rc;
1753 /* Clone the source disk image */
1754 rc = srcHdVBox->CloneTo(dstHdVBox, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1755 if (FAILED(rc)) throw rc;
1756
1757 /* Advance to the next operation */
1758 if (!pTask->progress.isNull())
1759 pTask->progress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1760 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally);
1761 }
1762
1763 // now wait for the background disk operation to complete; this throws HRESULTs on error
1764 waitForAsyncProgress(pTask->progress, pProgress2);
1765
1766 if (fSourceHdNeedsClosing)
1767 {
1768 rc = srcHdVBox->Close();
1769 if (FAILED(rc)) throw rc;
1770 fSourceHdNeedsClosing = false;
1771 }
1772
1773 llHardDisksCreated.push_back(dstHdVBox);
1774 /* Now use the new uuid to attach the disk image to our new machine */
1775 ComPtr<IMachine> sMachine;
1776 rc = session->COMGETTER(Machine)(sMachine.asOutParam());
1777 if (FAILED(rc)) throw rc;
1778 Bstr hdId;
1779 rc = dstHdVBox->COMGETTER(Id)(hdId.asOutParam());
1780 if (FAILED(rc)) throw rc;
1781
1782 /* For now we assume we have one controller of every type only */
1783 HardDiskController hdc = (*vsysThis.mapControllers.find(vd.idController)).second;
1784
1785 // this is for rollback later
1786 MyHardDiskAttachment mhda;
1787 mhda.bstrUuid = bstrNewMachineId;
1788 mhda.pMachine = pNewMachine;
1789
1790 ConvertDiskAttachmentValues(hdc,
1791 vd.ulAddressOnParent,
1792 mhda.controllerType, // Bstr
1793 mhda.lChannel,
1794 mhda.lDevice);
1795
1796 Log(("Attaching disk %s to channel %d on device %d\n", vsdeHD->strVbox.c_str(), mhda.lChannel, mhda.lDevice));
1797
1798 rc = sMachine->AttachDevice(mhda.controllerType,
1799 mhda.lChannel,
1800 mhda.lDevice,
1801 DeviceType_HardDisk,
1802 hdId);
1803 if (FAILED(rc)) throw rc;
1804
1805 llHardDiskAttachments.push_back(mhda);
1806
1807 rc = sMachine->SaveSettings();
1808 if (FAILED(rc)) throw rc;
1809 } // end for (itHD = avsdeHDs.begin();
1810
1811 // only now that we're done with all disks, close the session
1812 rc = session->Close();
1813 if (FAILED(rc)) throw rc;
1814 fSessionOpen = false;
1815 }
1816 catch(HRESULT /* aRC */)
1817 {
1818 if (fSourceHdNeedsClosing)
1819 srcHdVBox->Close();
1820
1821 if (fSessionOpen)
1822 session->Close();
1823
1824 throw;
1825 }
1826 }
1827 }
1828 catch(HRESULT aRC)
1829 {
1830 rc = aRC;
1831 }
1832
1833 if (FAILED(rc))
1834 break;
1835
1836 } // for (it = pAppliance->m->llVirtualSystems.begin(),
1837
1838 if (FAILED(rc))
1839 {
1840 // with _whatever_ error we've had, do a complete roll-back of
1841 // machines and disks we've created; unfortunately this is
1842 // not so trivially done...
1843
1844 HRESULT rc2;
1845 // detach all hard disks from all machines we created
1846 list<MyHardDiskAttachment>::iterator itM;
1847 for (itM = llHardDiskAttachments.begin();
1848 itM != llHardDiskAttachments.end();
1849 ++itM)
1850 {
1851 const MyHardDiskAttachment &mhda = *itM;
1852 rc2 = mVirtualBox->OpenSession(session, mhda.bstrUuid);
1853 if (SUCCEEDED(rc2))
1854 {
1855 ComPtr<IMachine> sMachine;
1856 rc2 = session->COMGETTER(Machine)(sMachine.asOutParam());
1857 if (SUCCEEDED(rc2))
1858 {
1859 rc2 = sMachine->DetachDevice(Bstr(mhda.controllerType), mhda.lChannel, mhda.lDevice);
1860 rc2 = sMachine->SaveSettings();
1861 }
1862 session->Close();
1863 }
1864 }
1865
1866 // now clean up all hard disks we created
1867 list< ComPtr<IMedium> >::iterator itHD;
1868 for (itHD = llHardDisksCreated.begin();
1869 itHD != llHardDisksCreated.end();
1870 ++itHD)
1871 {
1872 ComPtr<IMedium> pDisk = *itHD;
1873 ComPtr<IProgress> pProgress;
1874 rc2 = pDisk->DeleteStorage(pProgress.asOutParam());
1875 rc2 = pProgress->WaitForCompletion(-1);
1876 }
1877
1878 // finally, deregister and remove all machines
1879 list<Bstr>::iterator itID;
1880 for (itID = llMachinesRegistered.begin();
1881 itID != llMachinesRegistered.end();
1882 ++itID)
1883 {
1884 const Bstr &bstrGuid = *itID;
1885 ComPtr<IMachine> failedMachine;
1886 rc2 = mVirtualBox->UnregisterMachine(bstrGuid, failedMachine.asOutParam());
1887 if (SUCCEEDED(rc2))
1888 rc2 = failedMachine->DeleteSettings();
1889 }
1890 }
1891
1892 pTask->rc = rc;
1893
1894 if (!pTask->progress.isNull())
1895 pTask->progress->notifyComplete(rc);
1896
1897 LogFlowFunc(("rc=%Rhrc\n", rc));
1898 LogFlowFuncLeave();
1899
1900 return VINF_SUCCESS;
1901}
1902
1903/**
1904 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
1905 * Throws HRESULT values on errors!
1906 *
1907 * @param hdc
1908 * @param vd
1909 * @param mhda
1910 */
1911void Appliance::ConvertDiskAttachmentValues(const HardDiskController &hdc,
1912 uint32_t ulAddressOnParent,
1913 Bstr &controllerType,
1914 int32_t &lChannel,
1915 int32_t &lDevice)
1916{
1917 switch (hdc.system)
1918 {
1919 case HardDiskController::IDE:
1920 // For the IDE bus, the channel parameter can be either 0 or 1, to specify the primary
1921 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
1922 // the device number can be either 0 or 1, to specify the master or the slave device,
1923 // respectively. For the secondary IDE controller, the device number is always 1 because
1924 // the master device is reserved for the CD-ROM drive.
1925 controllerType = Bstr("IDE Controller");
1926 switch (ulAddressOnParent)
1927 {
1928 case 0: // interpret this as primary master
1929 lChannel = (long)0;
1930 lDevice = (long)0;
1931 break;
1932
1933 case 1: // interpret this as primary slave
1934 lChannel = (long)0;
1935 lDevice = (long)1;
1936 break;
1937
1938 case 2: // interpret this as secondary master
1939 lChannel = (long)1;
1940 lDevice = (long)0;
1941 break;
1942
1943 case 3: // interpret this as secondary slave
1944 lChannel = (long)1;
1945 lDevice = (long)1;
1946 break;
1947
1948 default:
1949 throw setError(VBOX_E_NOT_SUPPORTED,
1950 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"), ulAddressOnParent);
1951 break;
1952 }
1953 break;
1954
1955 case HardDiskController::SATA:
1956 controllerType = Bstr("SATA Controller");
1957 lChannel = (long)ulAddressOnParent;
1958 lDevice = (long)0;
1959 break;
1960
1961 case HardDiskController::SCSI:
1962 controllerType = Bstr("SCSI Controller");
1963 lChannel = (long)ulAddressOnParent;
1964 lDevice = (long)0;
1965 break;
1966
1967 default: break;
1968 }
1969}
1970
1971int Appliance::importS3(TaskImportOVF *pTask)
1972{
1973 LogFlowFuncEnter();
1974 LogFlowFunc(("Appliance %p\n", this));
1975
1976 AutoCaller autoCaller(this);
1977 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1978
1979 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1980
1981 int vrc = VINF_SUCCESS;
1982 RTS3 hS3 = NIL_RTS3;
1983 char szOSTmpDir[RTPATH_MAX];
1984 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1985 /* The template for the temporary directory created below */
1986 char *pszTmpDir;
1987 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
1988 list< pair<Utf8Str, ULONG> > filesList;
1989
1990 HRESULT rc = S_OK;
1991 try
1992 {
1993 /* Extract the bucket */
1994 Utf8Str tmpPath = pTask->locInfo.strPath;
1995 Utf8Str bucket;
1996 parseBucket(tmpPath, bucket);
1997
1998 /* We need a temporary directory which we can put the all disk images
1999 * in */
2000 vrc = RTDirCreateTemp(pszTmpDir);
2001 if (RT_FAILURE(vrc))
2002 throw setError(VBOX_E_FILE_ERROR,
2003 tr("Cannot create temporary directory '%s'"), pszTmpDir);
2004
2005 /* Add every disks of every virtual system to an internal list */
2006 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2007 for (it = m->virtualSystemDescriptions.begin();
2008 it != m->virtualSystemDescriptions.end();
2009 ++it)
2010 {
2011 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2012 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2013 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2014 for (itH = avsdeHDs.begin();
2015 itH != avsdeHDs.end();
2016 ++itH)
2017 {
2018 const Utf8Str &strTargetFile = (*itH)->strOvf;
2019 if (!strTargetFile.isEmpty())
2020 {
2021 /* The temporary name of the target disk file */
2022 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
2023 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
2024 }
2025 }
2026 }
2027
2028 /* Next we have to download the disk images */
2029 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2030 if(RT_FAILURE(vrc))
2031 throw setError(VBOX_E_IPRT_ERROR,
2032 tr("Cannot create S3 service handler"));
2033 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2034
2035 /* Download all files */
2036 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2037 {
2038 const pair<Utf8Str, ULONG> &s = (*it1);
2039 const Utf8Str &strSrcFile = s.first;
2040 /* Construct the source file name */
2041 char *pszFilename = RTPathFilename(strSrcFile.c_str());
2042 /* Advance to the next operation */
2043 if (!pTask->progress.isNull())
2044 pTask->progress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), s.second);
2045
2046 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
2047 if (RT_FAILURE(vrc))
2048 {
2049 if(vrc == VERR_S3_CANCELED)
2050 throw S_OK; /* todo: !!!!!!!!!!!!! */
2051 else if(vrc == VERR_S3_ACCESS_DENIED)
2052 throw setError(E_ACCESSDENIED,
2053 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
2054 else if(vrc == VERR_S3_NOT_FOUND)
2055 throw setError(VBOX_E_FILE_ERROR,
2056 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
2057 else
2058 throw setError(VBOX_E_IPRT_ERROR,
2059 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2060 }
2061 }
2062
2063 /* Provide a OVF file (haven't to exist) so the import routine can
2064 * figure out where the disk images/manifest file are located. */
2065 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2066 /* Now check if there is an manifest file. This is optional. */
2067 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
2068 char *pszFilename = RTPathFilename(strManifestFile.c_str());
2069 if (!pTask->progress.isNull())
2070 pTask->progress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
2071
2072 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
2073 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
2074 if (RT_SUCCESS(vrc))
2075 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
2076 else if (RT_FAILURE(vrc))
2077 {
2078 if(vrc == VERR_S3_CANCELED)
2079 throw S_OK; /* todo: !!!!!!!!!!!!! */
2080 else if(vrc == VERR_S3_NOT_FOUND)
2081 vrc = VINF_SUCCESS; /* Not found is ok */
2082 else if(vrc == VERR_S3_ACCESS_DENIED)
2083 throw setError(E_ACCESSDENIED,
2084 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
2085 else
2086 throw setError(VBOX_E_IPRT_ERROR,
2087 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2088 }
2089
2090 /* Close the connection early */
2091 RTS3Destroy(hS3);
2092 hS3 = NIL_RTS3;
2093
2094 if (!pTask->progress.isNull())
2095 pTask->progress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightPerOperation);
2096
2097 ComObjPtr<Progress> progress;
2098 /* Import the whole temporary OVF & the disk images */
2099 LocationInfo li;
2100 li.strPath = strTmpOvf;
2101 rc = importImpl(li, progress);
2102 if (FAILED(rc)) throw rc;
2103
2104 /* Unlock the appliance for the fs import thread */
2105 appLock.release();
2106 /* Wait until the import is done, but report the progress back to the
2107 caller */
2108 ComPtr<IProgress> progressInt(progress);
2109 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
2110
2111 /* Again lock the appliance for the next steps */
2112 appLock.acquire();
2113 }
2114 catch(HRESULT aRC)
2115 {
2116 rc = aRC;
2117 }
2118 /* Cleanup */
2119 RTS3Destroy(hS3);
2120 /* Delete all files which where temporary created */
2121 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2122 {
2123 const char *pszFilePath = (*it1).first.c_str();
2124 if (RTPathExists(pszFilePath))
2125 {
2126 vrc = RTFileDelete(pszFilePath);
2127 if(RT_FAILURE(vrc))
2128 rc = setError(VBOX_E_FILE_ERROR,
2129 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2130 }
2131 }
2132 /* Delete the temporary directory */
2133 if (RTPathExists(pszTmpDir))
2134 {
2135 vrc = RTDirRemove(pszTmpDir);
2136 if(RT_FAILURE(vrc))
2137 rc = setError(VBOX_E_FILE_ERROR,
2138 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2139 }
2140 if (pszTmpDir)
2141 RTStrFree(pszTmpDir);
2142
2143 pTask->rc = rc;
2144
2145 if (!pTask->progress.isNull())
2146 pTask->progress->notifyComplete(rc);
2147
2148 LogFlowFunc(("rc=%Rhrc\n", rc));
2149 LogFlowFuncLeave();
2150
2151 return VINF_SUCCESS;
2152}
2153
2154HRESULT Appliance::writeImpl(int aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
2155{
2156 HRESULT rc = S_OK;
2157 try
2158 {
2159 /* Initialize our worker task */
2160 std::auto_ptr<TaskExportOVF> task(new TaskExportOVF(this));
2161 /* What should the task do */
2162 task->taskType = TaskExportOVF::Write;
2163 /* The OVF version to write */
2164 task->enFormat = (TaskExportOVF::OVFFormat)aFormat;
2165 /* Copy the current location info to the task */
2166 task->locInfo = aLocInfo;
2167
2168 Bstr progressDesc = BstrFmt(tr("Export appliance '%s'"),
2169 task->locInfo.strPath.c_str());
2170
2171 /* todo: This progress init stuff should be done a little bit more generic */
2172 if (task->locInfo.storageType == VFSType_File)
2173 rc = setUpProgressFS(aProgress, progressDesc);
2174 else
2175 rc = setUpProgressWriteS3(aProgress, progressDesc);
2176
2177 task->progress = aProgress;
2178
2179 rc = task->startThread();
2180 if (FAILED(rc)) throw rc;
2181
2182 /* Don't destruct on success */
2183 task.release();
2184 }
2185 catch (HRESULT aRC)
2186 {
2187 rc = aRC;
2188 }
2189
2190 return rc;
2191}
2192
2193DECLCALLBACK(int) Appliance::taskThreadWriteOVF(RTTHREAD /* aThread */, void *pvUser)
2194{
2195 std::auto_ptr<TaskExportOVF> task(static_cast<TaskExportOVF*>(pvUser));
2196 AssertReturn(task.get(), VERR_GENERAL_FAILURE);
2197
2198 Appliance *pAppliance = task->pAppliance;
2199
2200 LogFlowFuncEnter();
2201 LogFlowFunc(("Appliance %p\n", pAppliance));
2202
2203 HRESULT rc = S_OK;
2204
2205 switch(task->taskType)
2206 {
2207 case TaskExportOVF::Write:
2208 {
2209 if (task->locInfo.storageType == VFSType_File)
2210 rc = pAppliance->writeFS(task.get());
2211 else if (task->locInfo.storageType == VFSType_S3)
2212 rc = pAppliance->writeS3(task.get());
2213 break;
2214 }
2215 }
2216
2217 LogFlowFunc(("rc=%Rhrc\n", rc));
2218 LogFlowFuncLeave();
2219
2220 return VINF_SUCCESS;
2221}
2222
2223int Appliance::TaskExportOVF::startThread()
2224{
2225 int vrc = RTThreadCreate(NULL, Appliance::taskThreadWriteOVF, this,
2226 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
2227 "Appliance::Task");
2228
2229 ComAssertMsgRCRet(vrc,
2230 ("Could not create taskThreadWriteOVF (%Rrc)\n", vrc), E_FAIL);
2231
2232 return S_OK;
2233}
2234
2235int Appliance::writeFS(TaskExportOVF *pTask)
2236{
2237 LogFlowFuncEnter();
2238 LogFlowFunc(("Appliance %p\n", this));
2239
2240 AutoCaller autoCaller(this);
2241 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2242
2243 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
2244
2245 HRESULT rc = S_OK;
2246
2247 try
2248 {
2249 xml::Document doc;
2250 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
2251
2252 pelmRoot->setAttribute("ovf:version", (pTask->enFormat == TaskExportOVF::OVF_1_0) ? "1.0" : "0.9");
2253 pelmRoot->setAttribute("xml:lang", "en-US");
2254
2255 Utf8Str strNamespace = (pTask->enFormat == TaskExportOVF::OVF_0_9)
2256 ? "http://www.vmware.com/schema/ovf/1/envelope" // 0.9
2257 : "http://schemas.dmtf.org/ovf/envelope/1"; // 1.0
2258 pelmRoot->setAttribute("xmlns", strNamespace);
2259 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
2260
2261// pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
2262 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
2263 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
2264 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
2265// pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
2266
2267 // <Envelope>/<References>
2268 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
2269
2270 /* <Envelope>/<DiskSection>:
2271 <DiskSection>
2272 <Info>List of the virtual disks used in the package</Info>
2273 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="http://www.vmware.com/specifications/vmdk.html#compressed" ovf:populatedSize="1924967692"/>
2274 </DiskSection> */
2275 xml::ElementNode *pelmDiskSection;
2276 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2277 {
2278 // <Section xsi:type="ovf:DiskSection_Type">
2279 pelmDiskSection = pelmRoot->createChild("Section");
2280 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
2281 }
2282 else
2283 pelmDiskSection = pelmRoot->createChild("DiskSection");
2284
2285 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
2286 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
2287 // for now, set up a map so we have a list of unique disk names (to make
2288 // sure the same disk name is only added once)
2289 map<Utf8Str, const VirtualSystemDescriptionEntry*> mapDisks;
2290
2291 /* <Envelope>/<NetworkSection>:
2292 <NetworkSection>
2293 <Info>Logical networks used in the package</Info>
2294 <Network ovf:name="VM Network">
2295 <Description>The network that the LAMP Service will be available on</Description>
2296 </Network>
2297 </NetworkSection> */
2298 xml::ElementNode *pelmNetworkSection;
2299 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2300 {
2301 // <Section xsi:type="ovf:NetworkSection_Type">
2302 pelmNetworkSection = pelmRoot->createChild("Section");
2303 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
2304 }
2305 else
2306 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
2307
2308 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
2309 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
2310 // for now, set up a map so we have a list of unique network names (to make
2311 // sure the same network name is only added once)
2312 map<Utf8Str, bool> mapNetworks;
2313 // we fill this later below when we iterate over the networks
2314
2315 // and here come the virtual systems:
2316
2317 // write a collection if we have more than one virtual system _and_ we're
2318 // writing OVF 1.0; otherwise fail since ovftool can't import more than
2319 // one machine, it seems
2320 xml::ElementNode *pelmToAddVirtualSystemsTo;
2321 if (m->virtualSystemDescriptions.size() > 1)
2322 {
2323 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2324 throw setError(VBOX_E_FILE_ERROR,
2325 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
2326
2327 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
2328 /* xml::AttributeNode *pattrVirtualSystemCollectionId = */ pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
2329 }
2330 else
2331 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
2332
2333 uint32_t cDisks = 0;
2334
2335 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2336 /* Iterate through all virtual systems of that appliance */
2337 for (it = m->virtualSystemDescriptions.begin();
2338 it != m->virtualSystemDescriptions.end();
2339 ++it)
2340 {
2341 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2342
2343 xml::ElementNode *pelmVirtualSystem;
2344 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2345 {
2346 // <Section xsi:type="ovf:NetworkSection_Type">
2347 pelmVirtualSystem = pelmToAddVirtualSystemsTo->createChild("Content");
2348 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
2349 }
2350 else
2351 pelmVirtualSystem = pelmToAddVirtualSystemsTo->createChild("VirtualSystem");
2352
2353 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
2354
2355 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2356 if (llName.size() != 1)
2357 throw setError(VBOX_E_NOT_SUPPORTED,
2358 tr("Missing VM name"));
2359 Utf8Str &strVMName = llName.front()->strVbox;
2360 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
2361
2362 // product info
2363 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
2364 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
2365 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
2366 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
2367 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
2368 bool fProduct = llProduct.size() && !llProduct.front()->strVbox.isEmpty();
2369 bool fProductUrl = llProductUrl.size() && !llProductUrl.front()->strVbox.isEmpty();
2370 bool fVendor = llVendor.size() && !llVendor.front()->strVbox.isEmpty();
2371 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.front()->strVbox.isEmpty();
2372 bool fVersion = llVersion.size() && !llVersion.front()->strVbox.isEmpty();
2373 if (fProduct ||
2374 fProductUrl ||
2375 fVersion ||
2376 fVendorUrl ||
2377 fVersion)
2378 {
2379 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
2380 <Info>Meta-information about the installed software</Info>
2381 <Product>VAtest</Product>
2382 <Vendor>SUN Microsystems</Vendor>
2383 <Version>10.0</Version>
2384 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
2385 <VendorUrl>http://www.sun.com</VendorUrl>
2386 </Section> */
2387 xml::ElementNode *pelmAnnotationSection;
2388 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2389 {
2390 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
2391 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
2392 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
2393 }
2394 else
2395 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
2396
2397 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
2398 if (fProduct)
2399 pelmAnnotationSection->createChild("Product")->addContent(llProduct.front()->strVbox);
2400 if (fVendor)
2401 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.front()->strVbox);
2402 if (fVersion)
2403 pelmAnnotationSection->createChild("Version")->addContent(llVersion.front()->strVbox);
2404 if (fProductUrl)
2405 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.front()->strVbox);
2406 if (fVendorUrl)
2407 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.front()->strVbox);
2408 }
2409
2410 // description
2411 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
2412 if (llDescription.size() &&
2413 !llDescription.front()->strVbox.isEmpty())
2414 {
2415 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
2416 <Info>A human-readable annotation</Info>
2417 <Annotation>Plan 9</Annotation>
2418 </Section> */
2419 xml::ElementNode *pelmAnnotationSection;
2420 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2421 {
2422 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
2423 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
2424 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
2425 }
2426 else
2427 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
2428
2429 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
2430 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.front()->strVbox);
2431 }
2432
2433 // license
2434 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
2435 if (llLicense.size() &&
2436 !llLicense.front()->strVbox.isEmpty())
2437 {
2438 /* <EulaSection>
2439 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
2440 <License ovf:msgid="1">License terms can go in here.</License>
2441 </EulaSection> */
2442 xml::ElementNode *pelmEulaSection;
2443 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2444 {
2445 pelmEulaSection = pelmVirtualSystem->createChild("Section");
2446 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
2447 }
2448 else
2449 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
2450
2451 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
2452 pelmEulaSection->createChild("License")->addContent(llLicense.front()->strVbox);
2453 }
2454
2455 // operating system
2456 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
2457 if (llOS.size() != 1)
2458 throw setError(VBOX_E_NOT_SUPPORTED,
2459 tr("Missing OS type"));
2460 /* <OperatingSystemSection ovf:id="82">
2461 <Info>Guest Operating System</Info>
2462 <Description>Linux 2.6.x</Description>
2463 </OperatingSystemSection> */
2464 xml::ElementNode *pelmOperatingSystemSection;
2465 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2466 {
2467 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
2468 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
2469 }
2470 else
2471 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
2472
2473 pelmOperatingSystemSection->setAttribute("ovf:id", llOS.front()->strOvf);
2474 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
2475 Utf8Str strOSDesc;
2476 convertCIMOSType2VBoxOSType(strOSDesc, (CIMOSType_T)llOS.front()->strOvf.toInt32(), "");
2477 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
2478
2479 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
2480 xml::ElementNode *pelmVirtualHardwareSection;
2481 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2482 {
2483 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
2484 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
2485 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
2486 }
2487 else
2488 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
2489
2490 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
2491
2492 /* <System>
2493 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
2494 <vssd:ElementName>vmware</vssd:ElementName>
2495 <vssd:InstanceID>1</vssd:InstanceID>
2496 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
2497 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
2498 </System> */
2499 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
2500
2501 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
2502
2503 // <vssd:InstanceId>0</vssd:InstanceId>
2504 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2505 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
2506 else // capitalization changed...
2507 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
2508
2509 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
2510 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
2511 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
2512 const char *pcszHardware = "virtualbox-2.2";
2513 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2514 // pretend to be vmware compatible then
2515 pcszHardware = "vmx-6";
2516 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
2517
2518 // loop thru all description entries twice; once to write out all
2519 // devices _except_ disk images, and a second time to assign the
2520 // disk images; this is because disk images need to reference
2521 // IDE controllers, and we can't know their instance IDs without
2522 // assigning them first
2523
2524 uint32_t idIDEController = 0;
2525 int32_t lIDEControllerIndex = 0;
2526 uint32_t idSATAController = 0;
2527 int32_t lSATAControllerIndex = 0;
2528 uint32_t idSCSIController = 0;
2529 int32_t lSCSIControllerIndex = 0;
2530
2531 uint32_t ulInstanceID = 1;
2532
2533 for (size_t uLoop = 1;
2534 uLoop <= 2;
2535 ++uLoop)
2536 {
2537 int32_t lIndexThis = 0;
2538 list<VirtualSystemDescriptionEntry>::const_iterator itD;
2539 for (itD = vsdescThis->m->llDescriptions.begin();
2540 itD != vsdescThis->m->llDescriptions.end();
2541 ++itD, ++lIndexThis)
2542 {
2543 const VirtualSystemDescriptionEntry &desc = *itD;
2544
2545 OVFResourceType_T type = (OVFResourceType_T)0; // if this becomes != 0 then we do stuff
2546 Utf8Str strResourceSubType;
2547
2548 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
2549 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
2550
2551 uint32_t ulParent = 0;
2552
2553 int32_t lVirtualQuantity = -1;
2554 Utf8Str strAllocationUnits;
2555
2556 int32_t lAddress = -1;
2557 int32_t lBusNumber = -1;
2558 int32_t lAddressOnParent = -1;
2559
2560 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
2561 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
2562 Utf8Str strHostResource;
2563
2564 uint64_t uTemp;
2565
2566 switch (desc.type)
2567 {
2568 case VirtualSystemDescriptionType_CPU:
2569 /* <Item>
2570 <rasd:Caption>1 virtual CPU</rasd:Caption>
2571 <rasd:Description>Number of virtual CPUs</rasd:Description>
2572 <rasd:ElementName>virtual CPU</rasd:ElementName>
2573 <rasd:InstanceID>1</rasd:InstanceID>
2574 <rasd:ResourceType>3</rasd:ResourceType>
2575 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2576 </Item> */
2577 if (uLoop == 1)
2578 {
2579 strDescription = "Number of virtual CPUs";
2580 type = OVFResourceType_Processor; // 3
2581 desc.strVbox.toInt(uTemp);
2582 lVirtualQuantity = (int32_t)uTemp;
2583 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
2584 }
2585 break;
2586
2587 case VirtualSystemDescriptionType_Memory:
2588 /* <Item>
2589 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
2590 <rasd:Caption>256 MB of memory</rasd:Caption>
2591 <rasd:Description>Memory Size</rasd:Description>
2592 <rasd:ElementName>Memory</rasd:ElementName>
2593 <rasd:InstanceID>2</rasd:InstanceID>
2594 <rasd:ResourceType>4</rasd:ResourceType>
2595 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
2596 </Item> */
2597 if (uLoop == 1)
2598 {
2599 strDescription = "Memory Size";
2600 type = OVFResourceType_Memory; // 4
2601 desc.strVbox.toInt(uTemp);
2602 lVirtualQuantity = (int32_t)(uTemp / _1M);
2603 strAllocationUnits = "MegaBytes";
2604 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
2605 }
2606 break;
2607
2608 case VirtualSystemDescriptionType_HardDiskControllerIDE:
2609 /* <Item>
2610 <rasd:Caption>ideController1</rasd:Caption>
2611 <rasd:Description>IDE Controller</rasd:Description>
2612 <rasd:InstanceId>5</rasd:InstanceId>
2613 <rasd:ResourceType>5</rasd:ResourceType>
2614 <rasd:Address>1</rasd:Address>
2615 <rasd:BusNumber>1</rasd:BusNumber>
2616 </Item> */
2617 if (uLoop == 1)
2618 {
2619 strDescription = "IDE Controller";
2620 strCaption = "ideController0";
2621 type = OVFResourceType_IDEController; // 5
2622 strResourceSubType = desc.strVbox;
2623 // it seems that OVFTool always writes these two, and since we can only
2624 // have one IDE controller, we'll use this as well
2625 lAddress = 1;
2626 lBusNumber = 1;
2627
2628 // remember this ID
2629 idIDEController = ulInstanceID;
2630 lIDEControllerIndex = lIndexThis;
2631 }
2632 break;
2633
2634 case VirtualSystemDescriptionType_HardDiskControllerSATA:
2635 /* <Item>
2636 <rasd:Caption>sataController0</rasd:Caption>
2637 <rasd:Description>SATA Controller</rasd:Description>
2638 <rasd:InstanceId>4</rasd:InstanceId>
2639 <rasd:ResourceType>20</rasd:ResourceType>
2640 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
2641 <rasd:Address>0</rasd:Address>
2642 <rasd:BusNumber>0</rasd:BusNumber>
2643 </Item>
2644 */
2645 if (uLoop == 1)
2646 {
2647 strDescription = "SATA Controller";
2648 strCaption = "sataController0";
2649 type = OVFResourceType_OtherStorageDevice; // 20
2650 // it seems that OVFTool always writes these two, and since we can only
2651 // have one SATA controller, we'll use this as well
2652 lAddress = 0;
2653 lBusNumber = 0;
2654
2655 if ( desc.strVbox.isEmpty() // AHCI is the default in VirtualBox
2656 || (!desc.strVbox.compare("ahci", Utf8Str::CaseInsensitive))
2657 )
2658 strResourceSubType = "AHCI";
2659 else
2660 throw setError(VBOX_E_NOT_SUPPORTED,
2661 tr("Invalid config string \"%s\" in SATA controller"), desc.strVbox.c_str());
2662
2663 // remember this ID
2664 idSATAController = ulInstanceID;
2665 lSATAControllerIndex = lIndexThis;
2666 }
2667 break;
2668
2669 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
2670 /* <Item>
2671 <rasd:Caption>scsiController0</rasd:Caption>
2672 <rasd:Description>SCSI Controller</rasd:Description>
2673 <rasd:InstanceId>4</rasd:InstanceId>
2674 <rasd:ResourceType>6</rasd:ResourceType>
2675 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
2676 <rasd:Address>0</rasd:Address>
2677 <rasd:BusNumber>0</rasd:BusNumber>
2678 </Item>
2679 */
2680 if (uLoop == 1)
2681 {
2682 strDescription = "SCSI Controller";
2683 strCaption = "scsiController0";
2684 type = OVFResourceType_ParallelSCSIHBA; // 6
2685 // it seems that OVFTool always writes these two, and since we can only
2686 // have one SATA controller, we'll use this as well
2687 lAddress = 0;
2688 lBusNumber = 0;
2689
2690 if ( desc.strVbox.isEmpty() // LsiLogic is the default in VirtualBox
2691 || (!desc.strVbox.compare("lsilogic", Utf8Str::CaseInsensitive))
2692 )
2693 strResourceSubType = "lsilogic";
2694 else if (!desc.strVbox.compare("buslogic", Utf8Str::CaseInsensitive))
2695 strResourceSubType = "buslogic";
2696 else
2697 throw setError(VBOX_E_NOT_SUPPORTED,
2698 tr("Invalid config string \"%s\" in SCSI controller"), desc.strVbox.c_str());
2699
2700 // remember this ID
2701 idSCSIController = ulInstanceID;
2702 lSCSIControllerIndex = lIndexThis;
2703 }
2704 break;
2705
2706 case VirtualSystemDescriptionType_HardDiskImage:
2707 /* <Item>
2708 <rasd:Caption>disk1</rasd:Caption>
2709 <rasd:InstanceId>8</rasd:InstanceId>
2710 <rasd:ResourceType>17</rasd:ResourceType>
2711 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
2712 <rasd:Parent>4</rasd:Parent>
2713 <rasd:AddressOnParent>0</rasd:AddressOnParent>
2714 </Item> */
2715 if (uLoop == 2)
2716 {
2717 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
2718
2719 strDescription = "Disk Image";
2720 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
2721 type = OVFResourceType_HardDisk; // 17
2722
2723 // the following references the "<Disks>" XML block
2724 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
2725
2726 // controller=<index>;channel=<c>
2727 size_t pos1 = desc.strExtraConfig.find("controller=");
2728 size_t pos2 = desc.strExtraConfig.find("channel=");
2729 if (pos1 != Utf8Str::npos)
2730 {
2731 int32_t lControllerIndex = -1;
2732 RTStrToInt32Ex(desc.strExtraConfig.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
2733 if (lControllerIndex == lIDEControllerIndex)
2734 ulParent = idIDEController;
2735 else if (lControllerIndex == lSCSIControllerIndex)
2736 ulParent = idSCSIController;
2737 else if (lControllerIndex == lSATAControllerIndex)
2738 ulParent = idSATAController;
2739 }
2740 if (pos2 != Utf8Str::npos)
2741 RTStrToInt32Ex(desc.strExtraConfig.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
2742
2743 if ( !ulParent
2744 || lAddressOnParent == -1
2745 )
2746 throw setError(VBOX_E_NOT_SUPPORTED,
2747 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfig.c_str());
2748
2749 mapDisks[strDiskID] = &desc;
2750 }
2751 break;
2752
2753 case VirtualSystemDescriptionType_Floppy:
2754 if (uLoop == 1)
2755 {
2756 strDescription = "Floppy Drive";
2757 strCaption = "floppy0"; // this is what OVFTool writes
2758 type = OVFResourceType_FloppyDrive; // 14
2759 lAutomaticAllocation = 0;
2760 lAddressOnParent = 0; // this is what OVFTool writes
2761 }
2762 break;
2763
2764 case VirtualSystemDescriptionType_CDROM:
2765 if (uLoop == 2)
2766 {
2767 // we can't have a CD without an IDE controller
2768 if (!idIDEController)
2769 throw setError(VBOX_E_NOT_SUPPORTED,
2770 tr("Can't have CD-ROM without IDE controller"));
2771
2772 strDescription = "CD-ROM Drive";
2773 strCaption = "cdrom1"; // this is what OVFTool writes
2774 type = OVFResourceType_CDDrive; // 15
2775 lAutomaticAllocation = 1;
2776 ulParent = idIDEController;
2777 lAddressOnParent = 0; // this is what OVFTool writes
2778 }
2779 break;
2780
2781 case VirtualSystemDescriptionType_NetworkAdapter:
2782 /* <Item>
2783 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
2784 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
2785 <rasd:Connection>VM Network</rasd:Connection>
2786 <rasd:ElementName>VM network</rasd:ElementName>
2787 <rasd:InstanceID>3</rasd:InstanceID>
2788 <rasd:ResourceType>10</rasd:ResourceType>
2789 </Item> */
2790 if (uLoop == 1)
2791 {
2792 lAutomaticAllocation = 1;
2793 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
2794 type = OVFResourceType_EthernetAdapter; // 10
2795 /* Set the hardware type to something useful.
2796 * To be compatible with vmware & others we set
2797 * PCNet32 for our PCNet types & E1000 for the
2798 * E1000 cards. */
2799 switch (desc.strVbox.toInt32())
2800 {
2801 case NetworkAdapterType_Am79C970A:
2802 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
2803#ifdef VBOX_WITH_E1000
2804 case NetworkAdapterType_I82540EM:
2805 case NetworkAdapterType_I82545EM:
2806 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
2807#endif /* VBOX_WITH_E1000 */
2808 }
2809 strConnection = desc.strOvf;
2810
2811 mapNetworks[desc.strOvf] = true;
2812 }
2813 break;
2814
2815 case VirtualSystemDescriptionType_USBController:
2816 /* <Item ovf:required="false">
2817 <rasd:Caption>usb</rasd:Caption>
2818 <rasd:Description>USB Controller</rasd:Description>
2819 <rasd:InstanceId>3</rasd:InstanceId>
2820 <rasd:ResourceType>23</rasd:ResourceType>
2821 <rasd:Address>0</rasd:Address>
2822 <rasd:BusNumber>0</rasd:BusNumber>
2823 </Item> */
2824 if (uLoop == 1)
2825 {
2826 strDescription = "USB Controller";
2827 strCaption = "usb";
2828 type = OVFResourceType_USBController; // 23
2829 lAddress = 0; // this is what OVFTool writes
2830 lBusNumber = 0; // this is what OVFTool writes
2831 }
2832 break;
2833
2834 case VirtualSystemDescriptionType_SoundCard:
2835 /* <Item ovf:required="false">
2836 <rasd:Caption>sound</rasd:Caption>
2837 <rasd:Description>Sound Card</rasd:Description>
2838 <rasd:InstanceId>10</rasd:InstanceId>
2839 <rasd:ResourceType>35</rasd:ResourceType>
2840 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
2841 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
2842 <rasd:AddressOnParent>3</rasd:AddressOnParent>
2843 </Item> */
2844 if (uLoop == 1)
2845 {
2846 strDescription = "Sound Card";
2847 strCaption = "sound";
2848 type = OVFResourceType_SoundCard; // 35
2849 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
2850 lAutomaticAllocation = 0;
2851 lAddressOnParent = 3; // what gives? this is what OVFTool writes
2852 }
2853 break;
2854 }
2855
2856 if (type)
2857 {
2858 xml::ElementNode *pItem;
2859
2860 pItem = pelmVirtualHardwareSection->createChild("Item");
2861
2862 // NOTE: do not change the order of these items without good reason! While we don't care
2863 // about ordering, VMware's ovftool does and fails if the items are not written in
2864 // exactly this order, as stupid as it seems.
2865
2866 if (!strCaption.isEmpty())
2867 {
2868 pItem->createChild("rasd:Caption")->addContent(strCaption);
2869 if (pTask->enFormat == TaskExportOVF::OVF_1_0)
2870 pItem->createChild("rasd:ElementName")->addContent(strCaption);
2871 }
2872
2873 if (!strDescription.isEmpty())
2874 pItem->createChild("rasd:Description")->addContent(strDescription);
2875
2876 // <rasd:InstanceID>1</rasd:InstanceID>
2877 xml::ElementNode *pelmInstanceID;
2878 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2879 pelmInstanceID = pItem->createChild("rasd:InstanceId");
2880 else
2881 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
2882 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
2883
2884 // <rasd:ResourceType>3</rasd:ResourceType>
2885 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
2886 if (!strResourceSubType.isEmpty())
2887 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
2888
2889 if (!strHostResource.isEmpty())
2890 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
2891
2892 if (!strAllocationUnits.isEmpty())
2893 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
2894
2895 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2896 if (lVirtualQuantity != -1)
2897 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2898
2899 if (lAutomaticAllocation != -1)
2900 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
2901
2902 if (!strConnection.isEmpty())
2903 pItem->createChild("rasd:Connection")->addContent(strConnection);
2904
2905 if (lAddress != -1)
2906 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
2907
2908 if (lBusNumber != -1)
2909 if (pTask->enFormat == TaskExportOVF::OVF_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool compatibility
2910 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
2911
2912 if (ulParent)
2913 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
2914 if (lAddressOnParent != -1)
2915 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
2916 }
2917 }
2918 } // for (size_t uLoop = 0; ...
2919 }
2920
2921 // finally, fill in the network section we set up empty above according
2922 // to the networks we found with the hardware items
2923 map<Utf8Str, bool>::const_iterator itN;
2924 for (itN = mapNetworks.begin();
2925 itN != mapNetworks.end();
2926 ++itN)
2927 {
2928 const Utf8Str &strNetwork = itN->first;
2929 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
2930 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
2931 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
2932 }
2933
2934 list<Utf8Str> diskList;
2935 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
2936 uint32_t ulFile = 1;
2937 for (itS = mapDisks.begin();
2938 itS != mapDisks.end();
2939 ++itS)
2940 {
2941 const Utf8Str &strDiskID = itS->first;
2942 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
2943
2944 // source path: where the VBox image is
2945 const Utf8Str &strSrcFilePath = pDiskEntry->strVbox;
2946 Bstr bstrSrcFilePath(strSrcFilePath);
2947 if (!RTPathExists(strSrcFilePath.c_str()))
2948 /* This isn't allowed */
2949 throw setError(VBOX_E_FILE_ERROR,
2950 tr("Source virtual disk image file '%s' doesn't exist"),
2951 strSrcFilePath.c_str());
2952
2953 // output filename
2954 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2955 // target path needs to be composed from where the output OVF is
2956 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2957 strTargetFilePath.stripFilename();
2958 strTargetFilePath.append("/");
2959 strTargetFilePath.append(strTargetFileNameOnly);
2960
2961 // clone the disk:
2962 ComPtr<IMedium> pSourceDisk;
2963 ComPtr<IMedium> pTargetDisk;
2964 ComPtr<IProgress> pProgress2;
2965
2966 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
2967 rc = mVirtualBox->FindHardDisk(bstrSrcFilePath, pSourceDisk.asOutParam());
2968 if (FAILED(rc)) throw rc;
2969
2970 /* We are always exporting to vmdfk stream optimized for now */
2971 Bstr bstrSrcFormat = L"VMDK";
2972
2973 // create a new hard disk interface for the destination disk image
2974 Log(("Creating target disk \"%s\"\n", strTargetFilePath.raw()));
2975 rc = mVirtualBox->CreateHardDisk(bstrSrcFormat, Bstr(strTargetFilePath), pTargetDisk.asOutParam());
2976 if (FAILED(rc)) throw rc;
2977
2978 // the target disk is now registered and needs to be removed again,
2979 // both after successful cloning or if anything goes bad!
2980 try
2981 {
2982 // create a flat copy of the source disk image
2983 rc = pSourceDisk->CloneTo(pTargetDisk, MediumVariant_VmdkStreamOptimized, NULL, pProgress2.asOutParam());
2984 if (FAILED(rc)) throw rc;
2985
2986 // advance to the next operation
2987 if (!pTask->progress.isNull())
2988 pTask->progress->SetNextOperation(BstrFmt(tr("Exporting virtual disk image '%s'"), strSrcFilePath.c_str()),
2989 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally);
2990
2991 // now wait for the background disk operation to complete; this throws HRESULTs on error
2992 waitForAsyncProgress(pTask->progress, pProgress2);
2993 }
2994 catch (HRESULT rc3)
2995 {
2996 // upon error after registering, close the disk or
2997 // it'll stick in the registry forever
2998 pTargetDisk->Close();
2999 throw rc3;
3000 }
3001 diskList.push_back(strTargetFilePath);
3002
3003 // we need the following for the XML
3004 uint64_t cbFile = 0; // actual file size
3005 rc = pTargetDisk->COMGETTER(Size)(&cbFile);
3006 if (FAILED(rc)) throw rc;
3007
3008 ULONG64 cbCapacity = 0; // size reported to guest
3009 rc = pTargetDisk->COMGETTER(LogicalSize)(&cbCapacity);
3010 if (FAILED(rc)) throw rc;
3011 // capacity is reported in megabytes, so...
3012 cbCapacity *= _1M;
3013
3014 // upon success, close the disk as well
3015 rc = pTargetDisk->Close();
3016 if (FAILED(rc)) throw rc;
3017
3018 // now handle the XML for the disk:
3019 Utf8StrFmt strFileRef("file%RI32", ulFile++);
3020 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
3021 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
3022 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
3023 pelmFile->setAttribute("ovf:id", strFileRef);
3024 pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
3025
3026 // add disk to XML Disks section
3027 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="http://www.vmware.com/specifications/vmdk.html#sparse"/>
3028 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
3029 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
3030 pelmDisk->setAttribute("ovf:diskId", strDiskID);
3031 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
3032 pelmDisk->setAttribute("ovf:format", "http://www.vmware.com/specifications/vmdk.html#sparse"); // must be sparse or ovftool chokes
3033 }
3034
3035 // now go write the XML
3036 xml::XmlFileWriter writer(doc);
3037 writer.write(pTask->locInfo.strPath.c_str());
3038
3039 /* Create & write the manifest file */
3040 const char** ppManifestFiles = (const char**)RTMemAlloc(sizeof(char*)*diskList.size() + 1);
3041 ppManifestFiles[0] = pTask->locInfo.strPath.c_str();
3042 list<Utf8Str>::const_iterator it1;
3043 size_t i = 1;
3044 for (it1 = diskList.begin();
3045 it1 != diskList.end();
3046 ++it1, ++i)
3047 ppManifestFiles[i] = (*it1).c_str();
3048 Utf8Str strMfFile = manifestFileName(pTask->locInfo.strPath.c_str());
3049 int vrc = RTManifestWriteFiles(strMfFile.c_str(), ppManifestFiles, diskList.size()+1);
3050 if (RT_FAILURE(vrc))
3051 throw setError(VBOX_E_FILE_ERROR,
3052 tr("Couldn't create manifest file '%s' (%Rrc)"),
3053 RTPathFilename(strMfFile.c_str()), vrc);
3054 RTMemFree(ppManifestFiles);
3055 }
3056 catch(xml::Error &x)
3057 {
3058 rc = setError(VBOX_E_FILE_ERROR,
3059 x.what());
3060 }
3061 catch(HRESULT aRC)
3062 {
3063 rc = aRC;
3064 }
3065
3066 pTask->rc = rc;
3067
3068 if (!pTask->progress.isNull())
3069 pTask->progress->notifyComplete(rc);
3070
3071 LogFlowFunc(("rc=%Rhrc\n", rc));
3072 LogFlowFuncLeave();
3073
3074 return VINF_SUCCESS;
3075}
3076
3077int Appliance::writeS3(TaskExportOVF *pTask)
3078{
3079 LogFlowFuncEnter();
3080 LogFlowFunc(("Appliance %p\n", this));
3081
3082 AutoCaller autoCaller(this);
3083 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3084
3085 HRESULT rc = S_OK;
3086
3087 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
3088
3089 int vrc = VINF_SUCCESS;
3090 RTS3 hS3 = NIL_RTS3;
3091 char szOSTmpDir[RTPATH_MAX];
3092 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
3093 /* The template for the temporary directory created below */
3094 char *pszTmpDir;
3095 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
3096 list< pair<Utf8Str, ULONG> > filesList;
3097
3098 // todo:
3099 // - usable error codes
3100 // - seems snapshot filenames are problematic {uuid}.vdi
3101 try
3102 {
3103 /* Extract the bucket */
3104 Utf8Str tmpPath = pTask->locInfo.strPath;
3105 Utf8Str bucket;
3106 parseBucket(tmpPath, bucket);
3107
3108 /* We need a temporary directory which we can put the OVF file & all
3109 * disk images in */
3110 vrc = RTDirCreateTemp(pszTmpDir);
3111 if (RT_FAILURE(vrc))
3112 throw setError(VBOX_E_FILE_ERROR,
3113 tr("Cannot create temporary directory '%s'"), pszTmpDir);
3114
3115 /* The temporary name of the target OVF file */
3116 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
3117
3118 /* Prepare the temporary writing of the OVF */
3119 ComObjPtr<Progress> progress;
3120 /* Create a temporary file based location info for the sub task */
3121 LocationInfo li;
3122 li.strPath = strTmpOvf;
3123 rc = writeImpl(pTask->enFormat, li, progress);
3124 if (FAILED(rc)) throw rc;
3125
3126 /* Unlock the appliance for the writing thread */
3127 appLock.release();
3128 /* Wait until the writing is done, but report the progress back to the
3129 caller */
3130 ComPtr<IProgress> progressInt(progress);
3131 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
3132
3133 /* Again lock the appliance for the next steps */
3134 appLock.acquire();
3135
3136 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
3137 if(RT_FAILURE(vrc))
3138 throw setError(VBOX_E_FILE_ERROR,
3139 tr("Cannot find source file '%s'"), strTmpOvf.c_str());
3140 /* Add the OVF file */
3141 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightPerOperation)); /* Use 1% of the total for the OVF file upload */
3142 Utf8Str strMfFile = manifestFileName(strTmpOvf);
3143 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightPerOperation)); /* Use 1% of the total for the manifest file upload */
3144
3145 /* Now add every disks of every virtual system */
3146 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
3147 for (it = m->virtualSystemDescriptions.begin();
3148 it != m->virtualSystemDescriptions.end();
3149 ++it)
3150 {
3151 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
3152 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
3153 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
3154 for (itH = avsdeHDs.begin();
3155 itH != avsdeHDs.end();
3156 ++itH)
3157 {
3158 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
3159 /* Target path needs to be composed from where the output OVF is */
3160 Utf8Str strTargetFilePath(strTmpOvf);
3161 strTargetFilePath.stripFilename();
3162 strTargetFilePath.append("/");
3163 strTargetFilePath.append(strTargetFileNameOnly);
3164 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
3165 if(RT_FAILURE(vrc))
3166 throw setError(VBOX_E_FILE_ERROR,
3167 tr("Cannot find source file '%s'"), strTargetFilePath.c_str());
3168 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
3169 }
3170 }
3171 /* Next we have to upload the OVF & all disk images */
3172 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
3173 if(RT_FAILURE(vrc))
3174 throw setError(VBOX_E_IPRT_ERROR,
3175 tr("Cannot create S3 service handler"));
3176 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
3177
3178 /* Upload all files */
3179 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
3180 {
3181 const pair<Utf8Str, ULONG> &s = (*it1);
3182 char *pszFilename = RTPathFilename(s.first.c_str());
3183 /* Advance to the next operation */
3184 if (!pTask->progress.isNull())
3185 pTask->progress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename), s.second);
3186 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
3187 if (RT_FAILURE(vrc))
3188 {
3189 if(vrc == VERR_S3_CANCELED)
3190 break;
3191 else if(vrc == VERR_S3_ACCESS_DENIED)
3192 throw setError(E_ACCESSDENIED,
3193 tr("Cannot upload file '%s' to S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
3194 else if(vrc == VERR_S3_NOT_FOUND)
3195 throw setError(VBOX_E_FILE_ERROR,
3196 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
3197 else
3198 throw setError(VBOX_E_IPRT_ERROR,
3199 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
3200 }
3201 }
3202 }
3203 catch(HRESULT aRC)
3204 {
3205 rc = aRC;
3206 }
3207 /* Cleanup */
3208 RTS3Destroy(hS3);
3209 /* Delete all files which where temporary created */
3210 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
3211 {
3212 const char *pszFilePath = (*it1).first.c_str();
3213 if (RTPathExists(pszFilePath))
3214 {
3215 vrc = RTFileDelete(pszFilePath);
3216 if(RT_FAILURE(vrc))
3217 rc = setError(VBOX_E_FILE_ERROR,
3218 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
3219 }
3220 }
3221 /* Delete the temporary directory */
3222 if (RTPathExists(pszTmpDir))
3223 {
3224 vrc = RTDirRemove(pszTmpDir);
3225 if(RT_FAILURE(vrc))
3226 rc = setError(VBOX_E_FILE_ERROR,
3227 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
3228 }
3229 if (pszTmpDir)
3230 RTStrFree(pszTmpDir);
3231
3232 pTask->rc = rc;
3233
3234 if (!pTask->progress.isNull())
3235 pTask->progress->notifyComplete(rc);
3236
3237 LogFlowFunc(("rc=%Rhrc\n", rc));
3238 LogFlowFuncLeave();
3239
3240 return VINF_SUCCESS;
3241}
3242
3243////////////////////////////////////////////////////////////////////////////////
3244//
3245// IAppliance public methods
3246//
3247////////////////////////////////////////////////////////////////////////////////
3248
3249/**
3250 * Public method implementation.
3251 * @param
3252 * @return
3253 */
3254STDMETHODIMP Appliance::COMGETTER(Path)(BSTR *aPath)
3255{
3256 if (!aPath)
3257 return E_POINTER;
3258
3259 AutoCaller autoCaller(this);
3260 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3261
3262 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3263
3264 Bstr bstrPath(m->locInfo.strPath);
3265 bstrPath.cloneTo(aPath);
3266
3267 return S_OK;
3268}
3269
3270/**
3271 * Public method implementation.
3272 * @param
3273 * @return
3274 */
3275STDMETHODIMP Appliance::COMGETTER(Disks)(ComSafeArrayOut(BSTR, aDisks))
3276{
3277 CheckComArgOutSafeArrayPointerValid(aDisks);
3278
3279 AutoCaller autoCaller(this);
3280 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3281
3282 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3283
3284 if (m->pReader) // OVFReader instantiated?
3285 {
3286 size_t c = m->pReader->m_mapDisks.size();
3287 com::SafeArray<BSTR> sfaDisks(c);
3288
3289 DiskImagesMap::const_iterator it;
3290 size_t i = 0;
3291 for (it = m->pReader->m_mapDisks.begin();
3292 it != m->pReader->m_mapDisks.end();
3293 ++it, ++i)
3294 {
3295 // create a string representing this disk
3296 const DiskImage &d = it->second;
3297 char *psz = NULL;
3298 RTStrAPrintf(&psz,
3299 "%s\t"
3300 "%RI64\t"
3301 "%RI64\t"
3302 "%s\t"
3303 "%s\t"
3304 "%RI64\t"
3305 "%RI64\t"
3306 "%s",
3307 d.strDiskId.c_str(),
3308 d.iCapacity,
3309 d.iPopulatedSize,
3310 d.strFormat.c_str(),
3311 d.strHref.c_str(),
3312 d.iSize,
3313 d.iChunkSize,
3314 d.strCompression.c_str());
3315 Utf8Str utf(psz);
3316 Bstr bstr(utf);
3317 // push to safearray
3318 bstr.cloneTo(&sfaDisks[i]);
3319 RTStrFree(psz);
3320 }
3321
3322 sfaDisks.detachTo(ComSafeArrayOutArg(aDisks));
3323 }
3324
3325 return S_OK;
3326}
3327
3328/**
3329 * Public method implementation.
3330 * @param
3331 * @return
3332 */
3333STDMETHODIMP Appliance::COMGETTER(VirtualSystemDescriptions)(ComSafeArrayOut(IVirtualSystemDescription*, aVirtualSystemDescriptions))
3334{
3335 CheckComArgOutSafeArrayPointerValid(aVirtualSystemDescriptions);
3336
3337 AutoCaller autoCaller(this);
3338 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3339
3340 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3341
3342 SafeIfaceArray<IVirtualSystemDescription> sfaVSD(m->virtualSystemDescriptions);
3343 sfaVSD.detachTo(ComSafeArrayOutArg(aVirtualSystemDescriptions));
3344
3345 return S_OK;
3346}
3347
3348/**
3349 * Public method implementation.
3350 * @param path
3351 * @return
3352 */
3353STDMETHODIMP Appliance::Read(IN_BSTR path, IProgress **aProgress)
3354{
3355 if (!path) return E_POINTER;
3356 CheckComArgOutPointerValid(aProgress);
3357
3358 AutoCaller autoCaller(this);
3359 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3360
3361 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3362
3363 if (m->pReader)
3364 {
3365 delete m->pReader;
3366 m->pReader = NULL;
3367 }
3368
3369 // see if we can handle this file; for now we insist it has an ".ovf" extension
3370 Utf8Str strPath (path);
3371 if (!strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
3372 return setError(VBOX_E_FILE_ERROR,
3373 tr("Appliance file must have .ovf extension"));
3374
3375 ComObjPtr<Progress> progress;
3376 HRESULT rc = S_OK;
3377 try
3378 {
3379 /* Parse all necessary info out of the URI */
3380 parseURI(strPath, m->locInfo);
3381 rc = readImpl(m->locInfo, progress);
3382 }
3383 catch (HRESULT aRC)
3384 {
3385 rc = aRC;
3386 }
3387
3388 if (SUCCEEDED(rc))
3389 /* Return progress to the caller */
3390 progress.queryInterfaceTo(aProgress);
3391
3392 return S_OK;
3393}
3394
3395/**
3396 * Public method implementation.
3397 * @return
3398 */
3399STDMETHODIMP Appliance::Interpret()
3400{
3401 // @todo:
3402 // - don't use COM methods but the methods directly (faster, but needs appropriate locking of that objects itself (s. HardDisk))
3403 // - Appropriate handle errors like not supported file formats
3404 AutoCaller autoCaller(this);
3405 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3406
3407 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3408
3409 HRESULT rc = S_OK;
3410
3411 /* Clear any previous virtual system descriptions */
3412 m->virtualSystemDescriptions.clear();
3413
3414 /* We need the default path for storing disk images */
3415 ComPtr<ISystemProperties> systemProps;
3416 rc = mVirtualBox->COMGETTER(SystemProperties)(systemProps.asOutParam());
3417 if (FAILED(rc)) return rc;
3418 Bstr bstrDefaultHardDiskLocation;
3419 rc = systemProps->COMGETTER(DefaultHardDiskFolder)(bstrDefaultHardDiskLocation.asOutParam());
3420 if (FAILED(rc)) return rc;
3421
3422 if (!m->pReader)
3423 return setError(E_FAIL,
3424 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
3425
3426 /* Try/catch so we can clean up on error */
3427 try
3428 {
3429 list<VirtualSystem>::const_iterator it;
3430 /* Iterate through all virtual systems */
3431 for (it = m->pReader->m_llVirtualSystems.begin();
3432 it != m->pReader->m_llVirtualSystems.end();
3433 ++it)
3434 {
3435 const VirtualSystem &vsysThis = *it;
3436
3437 ComObjPtr<VirtualSystemDescription> pNewDesc;
3438 rc = pNewDesc.createObject();
3439 if (FAILED(rc)) throw rc;
3440 rc = pNewDesc->init();
3441 if (FAILED(rc)) throw rc;
3442
3443 /* Guest OS type */
3444 Utf8Str strOsTypeVBox,
3445 strCIMOSType = Utf8StrFmt("%RI32", (uint32_t)vsysThis.cimos);
3446 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
3447 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
3448 "",
3449 strCIMOSType,
3450 strOsTypeVBox);
3451
3452 /* VM name */
3453 /* If the there isn't any name specified create a default one out of
3454 * the OS type */
3455 Utf8Str nameVBox = vsysThis.strName;
3456 if (nameVBox.isEmpty())
3457 nameVBox = strOsTypeVBox;
3458 searchUniqueVMName(nameVBox);
3459 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
3460 "",
3461 vsysThis.strName,
3462 nameVBox);
3463
3464 /* VM Product */
3465 if (!vsysThis.strProduct.isEmpty())
3466 pNewDesc->addEntry(VirtualSystemDescriptionType_Product,
3467 "",
3468 vsysThis.strProduct,
3469 vsysThis.strProduct);
3470
3471 /* VM Vendor */
3472 if (!vsysThis.strVendor.isEmpty())
3473 pNewDesc->addEntry(VirtualSystemDescriptionType_Vendor,
3474 "",
3475 vsysThis.strVendor,
3476 vsysThis.strVendor);
3477
3478 /* VM Version */
3479 if (!vsysThis.strVersion.isEmpty())
3480 pNewDesc->addEntry(VirtualSystemDescriptionType_Version,
3481 "",
3482 vsysThis.strVersion,
3483 vsysThis.strVersion);
3484
3485 /* VM ProductUrl */
3486 if (!vsysThis.strProductUrl.isEmpty())
3487 pNewDesc->addEntry(VirtualSystemDescriptionType_ProductUrl,
3488 "",
3489 vsysThis.strProductUrl,
3490 vsysThis.strProductUrl);
3491
3492 /* VM VendorUrl */
3493 if (!vsysThis.strVendorUrl.isEmpty())
3494 pNewDesc->addEntry(VirtualSystemDescriptionType_VendorUrl,
3495 "",
3496 vsysThis.strVendorUrl,
3497 vsysThis.strVendorUrl);
3498
3499 /* VM description */
3500 if (!vsysThis.strDescription.isEmpty())
3501 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
3502 "",
3503 vsysThis.strDescription,
3504 vsysThis.strDescription);
3505
3506 /* VM license */
3507 if (!vsysThis.strLicenseText.isEmpty())
3508 pNewDesc->addEntry(VirtualSystemDescriptionType_License,
3509 "",
3510 vsysThis.strLicenseText,
3511 vsysThis.strLicenseText);
3512
3513 /* Now that we know the OS type, get our internal defaults based on that. */
3514 ComPtr<IGuestOSType> pGuestOSType;
3515 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), pGuestOSType.asOutParam());
3516 if (FAILED(rc)) throw rc;
3517
3518 /* CPU count */
3519 ULONG cpuCountVBox = vsysThis.cCPUs;
3520 /* Check for the constrains */
3521 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
3522 {
3523 addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for max %u CPU's only."),
3524 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
3525 cpuCountVBox = SchemaDefs::MaxCPUCount;
3526 }
3527 if (vsysThis.cCPUs == 0)
3528 cpuCountVBox = 1;
3529 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
3530 "",
3531 Utf8StrFmt("%RI32", (uint32_t)vsysThis.cCPUs),
3532 Utf8StrFmt("%RI32", (uint32_t)cpuCountVBox));
3533
3534 /* RAM */
3535 uint64_t ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
3536 /* Check for the constrains */
3537 if (ullMemSizeVBox != 0 &&
3538 (ullMemSizeVBox < MM_RAM_MIN_IN_MB ||
3539 ullMemSizeVBox > MM_RAM_MAX_IN_MB))
3540 {
3541 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."),
3542 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
3543 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
3544 }
3545 if (vsysThis.ullMemorySize == 0)
3546 {
3547 /* If the RAM of the OVF is zero, use our predefined values */
3548 ULONG memSizeVBox2;
3549 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
3550 if (FAILED(rc)) throw rc;
3551 /* VBox stores that in MByte */
3552 ullMemSizeVBox = (uint64_t)memSizeVBox2;
3553 }
3554 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
3555 "",
3556 Utf8StrFmt("%RI64", (uint64_t)vsysThis.ullMemorySize),
3557 Utf8StrFmt("%RI64", (uint64_t)ullMemSizeVBox));
3558
3559 /* Audio */
3560 if (!vsysThis.strSoundCardType.isEmpty())
3561 /* Currently we set the AC97 always.
3562 @todo: figure out the hardware which could be possible */
3563 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
3564 "",
3565 vsysThis.strSoundCardType,
3566 Utf8StrFmt("%RI32", (uint32_t)AudioControllerType_AC97));
3567
3568#ifdef VBOX_WITH_USB
3569 /* USB Controller */
3570 if (vsysThis.fHasUsbController)
3571 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
3572#endif /* VBOX_WITH_USB */
3573
3574 /* Network Controller */
3575 size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size();
3576 if (cEthernetAdapters > 0)
3577 {
3578 /* Check for the constrains */
3579 if (cEthernetAdapters > SchemaDefs::NetworkAdapterCount)
3580 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
3581 vsysThis.strName.c_str(), cEthernetAdapters, SchemaDefs::NetworkAdapterCount);
3582
3583 /* Get the default network adapter type for the selected guest OS */
3584 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
3585 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
3586 if (FAILED(rc)) throw rc;
3587
3588 EthernetAdaptersList::const_iterator itEA;
3589 /* Iterate through all abstract networks. We support 8 network
3590 * adapters at the maximum, so the first 8 will be added only. */
3591 size_t a = 0;
3592 for (itEA = vsysThis.llEthernetAdapters.begin();
3593 itEA != vsysThis.llEthernetAdapters.end() && a < SchemaDefs::NetworkAdapterCount;
3594 ++itEA, ++a)
3595 {
3596 const EthernetAdapter &ea = *itEA; // logical network to connect to
3597 Utf8Str strNetwork = ea.strNetworkName;
3598 // make sure it's one of these two
3599 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
3600 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
3601 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
3602 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
3603 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
3604 )
3605 strNetwork = "Bridged"; // VMware assumes this is the default apparently
3606
3607 /* Figure out the hardware type */
3608 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
3609 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
3610 {
3611 /* If the default adapter is already one of the two
3612 * PCNet adapters use the default one. If not use the
3613 * Am79C970A as fallback. */
3614 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
3615 defaultAdapterVBox == NetworkAdapterType_Am79C973))
3616 nwAdapterVBox = NetworkAdapterType_Am79C970A;
3617 }
3618#ifdef VBOX_WITH_E1000
3619 /* VMWare accidentally write this with VirtualCenter 3.5,
3620 so make sure in this case always to use the VMWare one */
3621 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
3622 nwAdapterVBox = NetworkAdapterType_I82545EM;
3623 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
3624 {
3625 /* Check if this OVF was written by VirtualBox */
3626 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
3627 {
3628 /* If the default adapter is already one of the three
3629 * E1000 adapters use the default one. If not use the
3630 * I82545EM as fallback. */
3631 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
3632 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
3633 defaultAdapterVBox == NetworkAdapterType_I82545EM))
3634 nwAdapterVBox = NetworkAdapterType_I82540EM;
3635 }
3636 else
3637 /* Always use this one since it's what VMware uses */
3638 nwAdapterVBox = NetworkAdapterType_I82545EM;
3639 }
3640#endif /* VBOX_WITH_E1000 */
3641
3642 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
3643 "", // ref
3644 ea.strNetworkName, // orig
3645 Utf8StrFmt("%RI32", (uint32_t)nwAdapterVBox), // conf
3646 0,
3647 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
3648 }
3649 }
3650
3651 /* Floppy Drive */
3652 if (vsysThis.fHasFloppyDrive)
3653 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
3654
3655 /* CD Drive */
3656 if (vsysThis.fHasCdromDrive)
3657 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
3658
3659 /* Hard disk Controller */
3660 uint16_t cIDEused = 0;
3661 uint16_t cSATAused = 0; NOREF(cSATAused);
3662 uint16_t cSCSIused = 0; NOREF(cSCSIused);
3663 ControllersMap::const_iterator hdcIt;
3664 /* Iterate through all hard disk controllers */
3665 for (hdcIt = vsysThis.mapControllers.begin();
3666 hdcIt != vsysThis.mapControllers.end();
3667 ++hdcIt)
3668 {
3669 const HardDiskController &hdc = hdcIt->second;
3670 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
3671
3672 switch (hdc.system)
3673 {
3674 case HardDiskController::IDE:
3675 {
3676 /* Check for the constrains */
3677 /* @todo: I'm very confused! Are these bits *one* controller or
3678 is every port/bus declared as an extra controller. */
3679 if (cIDEused < 4)
3680 {
3681 // @todo: figure out the IDE types
3682 /* Use PIIX4 as default */
3683 Utf8Str strType = "PIIX4";
3684 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
3685 strType = "PIIX3";
3686 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
3687 strType = "ICH6";
3688 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
3689 strControllerID,
3690 hdc.strControllerType,
3691 strType);
3692 }
3693 else
3694 {
3695 /* Warn only once */
3696 if (cIDEused == 1)
3697 addWarning(tr("The virtual \"%s\" system requests support for more than one IDE controller, but VirtualBox has support for only one."),
3698 vsysThis.strName.c_str());
3699
3700 }
3701 ++cIDEused;
3702 break;
3703 }
3704
3705 case HardDiskController::SATA:
3706 {
3707#ifdef VBOX_WITH_AHCI
3708 /* Check for the constrains */
3709 if (cSATAused < 1)
3710 {
3711 // @todo: figure out the SATA types
3712 /* We only support a plain AHCI controller, so use them always */
3713 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
3714 strControllerID,
3715 hdc.strControllerType,
3716 "AHCI");
3717 }
3718 else
3719 {
3720 /* Warn only once */
3721 if (cSATAused == 1)
3722 addWarning(tr("The virtual system \"%s\" requests support for more than one SATA controller, but VirtualBox has support for only one"),
3723 vsysThis.strName.c_str());
3724
3725 }
3726 ++cSATAused;
3727 break;
3728#else /* !VBOX_WITH_AHCI */
3729 addWarning(tr("The virtual system \"%s\" requests at least one SATA controller but this version of VirtualBox does not provide a SATA controller emulation"),
3730 vsysThis.strName.c_str());
3731#endif /* !VBOX_WITH_AHCI */
3732 }
3733
3734 case HardDiskController::SCSI:
3735 {
3736#ifdef VBOX_WITH_LSILOGIC
3737 /* Check for the constrains */
3738 if (cSCSIused < 1)
3739 {
3740 Utf8Str hdcController = "LsiLogic";
3741 if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
3742 hdcController = "BusLogic";
3743 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
3744 strControllerID,
3745 hdc.strControllerType,
3746 hdcController);
3747 }
3748 else
3749 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."),
3750 vsysThis.strName.c_str(),
3751 hdc.strControllerType.c_str(),
3752 strControllerID.c_str());
3753 ++cSCSIused;
3754 break;
3755#else /* !VBOX_WITH_LSILOGIC */
3756 addWarning(tr("The virtual system \"%s\" requests at least one SATA controller but this version of VirtualBox does not provide a SCSI controller emulation"),
3757 vsysThis.strName.c_str());
3758#endif /* !VBOX_WITH_LSILOGIC */
3759 }
3760 }
3761 }
3762
3763 /* Hard disks */
3764 if (vsysThis.mapVirtualDisks.size() > 0)
3765 {
3766 VirtualDisksMap::const_iterator itVD;
3767 /* Iterate through all hard disks ()*/
3768 for (itVD = vsysThis.mapVirtualDisks.begin();
3769 itVD != vsysThis.mapVirtualDisks.end();
3770 ++itVD)
3771 {
3772 const VirtualDisk &hd = itVD->second;
3773 /* Get the associated disk image */
3774 const DiskImage &di = m->pReader->m_mapDisks[hd.strDiskId];
3775
3776 // @todo:
3777 // - figure out all possible vmdk formats we also support
3778 // - figure out if there is a url specifier for vhd already
3779 // - we need a url specifier for the vdi format
3780 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
3781 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive))
3782 {
3783 /* If the href is empty use the VM name as filename */
3784 Utf8Str strFilename = di.strHref;
3785 if (!strFilename.length())
3786 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
3787 /* Construct a unique target path */
3788 Utf8StrFmt strPath("%ls%c%s",
3789 bstrDefaultHardDiskLocation.raw(),
3790 RTPATH_DELIMITER,
3791 strFilename.c_str());
3792 searchUniqueDiskImageFilePath(strPath);
3793
3794 /* find the description for the hard disk controller
3795 * that has the same ID as hd.idController */
3796 const VirtualSystemDescriptionEntry *pController;
3797 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
3798 throw setError(E_FAIL,
3799 tr("Cannot find hard disk controller with OVF instance ID %RI32 to which disk \"%s\" should be attached"),
3800 hd.idController,
3801 di.strHref.c_str());
3802
3803 /* controller to attach to, and the bus within that controller */
3804 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
3805 pController->ulIndex,
3806 hd.ulAddressOnParent);
3807 ULONG ulSize = 0;
3808 if (di.iCapacity != -1)
3809 ulSize = (ULONG)(di.iCapacity / _1M);
3810 else if (di.iPopulatedSize != -1)
3811 ulSize = (ULONG)(di.iPopulatedSize / _1M);
3812 else if (di.iSize != -1)
3813 ulSize = (ULONG)(di.iSize / _1M);
3814 if (ulSize == 0)
3815 ulSize = 10000; // assume 10 GB, this is for the progress bar only anyway
3816 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
3817 hd.strDiskId,
3818 di.strHref,
3819 strPath,
3820 ulSize,
3821 strExtraConfig);
3822 }
3823 else
3824 throw setError(VBOX_E_FILE_ERROR,
3825 tr("Unsupported format for virtual disk image in OVF: \"%s\"", di.strFormat.c_str()));
3826 }
3827 }
3828
3829 m->virtualSystemDescriptions.push_back(pNewDesc);
3830 }
3831 }
3832 catch (HRESULT aRC)
3833 {
3834 /* On error we clear the list & return */
3835 m->virtualSystemDescriptions.clear();
3836 rc = aRC;
3837 }
3838
3839 return rc;
3840}
3841
3842/**
3843 * Public method implementation.
3844 * @param aProgress
3845 * @return
3846 */
3847STDMETHODIMP Appliance::ImportMachines(IProgress **aProgress)
3848{
3849 CheckComArgOutPointerValid(aProgress);
3850
3851 AutoCaller autoCaller(this);
3852 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3853
3854 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3855
3856 if (!m->pReader)
3857 return setError(E_FAIL,
3858 tr("Cannot import machines without reading it first (call read() before importMachines())"));
3859
3860 ComObjPtr<Progress> progress;
3861 HRESULT rc = S_OK;
3862 try
3863 {
3864 rc = importImpl(m->locInfo, progress);
3865 }
3866 catch (HRESULT aRC)
3867 {
3868 rc = aRC;
3869 }
3870
3871 if (SUCCEEDED(rc))
3872 /* Return progress to the caller */
3873 progress.queryInterfaceTo(aProgress);
3874
3875 return rc;
3876}
3877
3878STDMETHODIMP Appliance::CreateVFSExplorer(IN_BSTR aURI, IVFSExplorer **aExplorer)
3879{
3880 CheckComArgOutPointerValid(aExplorer);
3881
3882 AutoCaller autoCaller(this);
3883 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3884
3885 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3886
3887 ComObjPtr<VFSExplorer> explorer;
3888 HRESULT rc = S_OK;
3889 try
3890 {
3891 Utf8Str uri(aURI);
3892 /* Check which kind of export the user has requested */
3893 LocationInfo li;
3894 parseURI(uri, li);
3895 /* Create the explorer object */
3896 explorer.createObject();
3897 rc = explorer->init(li.storageType, li.strPath, li.strHostname, li.strUsername, li.strPassword, mVirtualBox);
3898 }
3899 catch (HRESULT aRC)
3900 {
3901 rc = aRC;
3902 }
3903
3904 if (SUCCEEDED(rc))
3905 /* Return explorer to the caller */
3906 explorer.queryInterfaceTo(aExplorer);
3907
3908 return rc;
3909}
3910
3911STDMETHODIMP Appliance::Write(IN_BSTR format, IN_BSTR path, IProgress **aProgress)
3912{
3913 if (!path) return E_POINTER;
3914 CheckComArgOutPointerValid(aProgress);
3915
3916 AutoCaller autoCaller(this);
3917 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3918
3919 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3920
3921 // see if we can handle this file; for now we insist it has an ".ovf" extension
3922 Utf8Str strPath = path;
3923 if (!strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
3924 return setError(VBOX_E_FILE_ERROR,
3925 tr("Appliance file must have .ovf extension"));
3926
3927 Utf8Str strFormat(format);
3928 TaskExportOVF::OVFFormat ovfF;
3929 if (strFormat == "ovf-0.9")
3930 ovfF = TaskExportOVF::OVF_0_9;
3931 else if (strFormat == "ovf-1.0")
3932 ovfF = TaskExportOVF::OVF_1_0;
3933 else
3934 return setError(VBOX_E_FILE_ERROR,
3935 tr("Invalid format \"%s\" specified"), strFormat.c_str());
3936
3937 ComObjPtr<Progress> progress;
3938 HRESULT rc = S_OK;
3939 try
3940 {
3941 /* Parse all necessary info out of the URI */
3942 parseURI(strPath, m->locInfo);
3943 rc = writeImpl(ovfF, m->locInfo, progress);
3944 }
3945 catch (HRESULT aRC)
3946 {
3947 rc = aRC;
3948 }
3949
3950 if (SUCCEEDED(rc))
3951 /* Return progress to the caller */
3952 progress.queryInterfaceTo(aProgress);
3953
3954 return rc;
3955}
3956
3957/**
3958* Public method implementation.
3959 * @return
3960 */
3961STDMETHODIMP Appliance::GetWarnings(ComSafeArrayOut(BSTR, aWarnings))
3962{
3963 if (ComSafeArrayOutIsNull(aWarnings))
3964 return E_POINTER;
3965
3966 AutoCaller autoCaller(this);
3967 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3968
3969 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3970
3971 com::SafeArray<BSTR> sfaWarnings(m->llWarnings.size());
3972
3973 list<Utf8Str>::const_iterator it;
3974 size_t i = 0;
3975 for (it = m->llWarnings.begin();
3976 it != m->llWarnings.end();
3977 ++it, ++i)
3978 {
3979 Bstr bstr = *it;
3980 bstr.cloneTo(&sfaWarnings[i]);
3981 }
3982
3983 sfaWarnings.detachTo(ComSafeArrayOutArg(aWarnings));
3984
3985 return S_OK;
3986}
3987
3988////////////////////////////////////////////////////////////////////////////////
3989//
3990// IVirtualSystemDescription constructor / destructor
3991//
3992////////////////////////////////////////////////////////////////////////////////
3993
3994DEFINE_EMPTY_CTOR_DTOR(VirtualSystemDescription)
3995
3996/**
3997 * COM initializer.
3998 * @return
3999 */
4000HRESULT VirtualSystemDescription::init()
4001{
4002 /* Enclose the state transition NotReady->InInit->Ready */
4003 AutoInitSpan autoInitSpan(this);
4004 AssertReturn(autoInitSpan.isOk(), E_FAIL);
4005
4006 /* Initialize data */
4007 m = new Data();
4008
4009 /* Confirm a successful initialization */
4010 autoInitSpan.setSucceeded();
4011 return S_OK;
4012}
4013
4014/**
4015* COM uninitializer.
4016*/
4017
4018void VirtualSystemDescription::uninit()
4019{
4020 delete m;
4021 m = NULL;
4022}
4023
4024////////////////////////////////////////////////////////////////////////////////
4025//
4026// IVirtualSystemDescription public methods
4027//
4028////////////////////////////////////////////////////////////////////////////////
4029
4030/**
4031 * Public method implementation.
4032 * @param
4033 * @return
4034 */
4035STDMETHODIMP VirtualSystemDescription::COMGETTER(Count)(ULONG *aCount)
4036{
4037 if (!aCount)
4038 return E_POINTER;
4039
4040 AutoCaller autoCaller(this);
4041 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4042
4043 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4044
4045 *aCount = (ULONG)m->llDescriptions.size();
4046
4047 return S_OK;
4048}
4049
4050/**
4051 * Public method implementation.
4052 * @return
4053 */
4054STDMETHODIMP VirtualSystemDescription::GetDescription(ComSafeArrayOut(VirtualSystemDescriptionType_T, aTypes),
4055 ComSafeArrayOut(BSTR, aRefs),
4056 ComSafeArrayOut(BSTR, aOrigValues),
4057 ComSafeArrayOut(BSTR, aVboxValues),
4058 ComSafeArrayOut(BSTR, aExtraConfigValues))
4059{
4060 if (ComSafeArrayOutIsNull(aTypes) ||
4061 ComSafeArrayOutIsNull(aRefs) ||
4062 ComSafeArrayOutIsNull(aOrigValues) ||
4063 ComSafeArrayOutIsNull(aVboxValues) ||
4064 ComSafeArrayOutIsNull(aExtraConfigValues))
4065 return E_POINTER;
4066
4067 AutoCaller autoCaller(this);
4068 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4069
4070 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4071
4072 ULONG c = (ULONG)m->llDescriptions.size();
4073 com::SafeArray<VirtualSystemDescriptionType_T> sfaTypes(c);
4074 com::SafeArray<BSTR> sfaRefs(c);
4075 com::SafeArray<BSTR> sfaOrigValues(c);
4076 com::SafeArray<BSTR> sfaVboxValues(c);
4077 com::SafeArray<BSTR> sfaExtraConfigValues(c);
4078
4079 list<VirtualSystemDescriptionEntry>::const_iterator it;
4080 size_t i = 0;
4081 for (it = m->llDescriptions.begin();
4082 it != m->llDescriptions.end();
4083 ++it, ++i)
4084 {
4085 const VirtualSystemDescriptionEntry &vsde = (*it);
4086
4087 sfaTypes[i] = vsde.type;
4088
4089 Bstr bstr = vsde.strRef;
4090 bstr.cloneTo(&sfaRefs[i]);
4091
4092 bstr = vsde.strOvf;
4093 bstr.cloneTo(&sfaOrigValues[i]);
4094
4095 bstr = vsde.strVbox;
4096 bstr.cloneTo(&sfaVboxValues[i]);
4097
4098 bstr = vsde.strExtraConfig;
4099 bstr.cloneTo(&sfaExtraConfigValues[i]);
4100 }
4101
4102 sfaTypes.detachTo(ComSafeArrayOutArg(aTypes));
4103 sfaRefs.detachTo(ComSafeArrayOutArg(aRefs));
4104 sfaOrigValues.detachTo(ComSafeArrayOutArg(aOrigValues));
4105 sfaVboxValues.detachTo(ComSafeArrayOutArg(aVboxValues));
4106 sfaExtraConfigValues.detachTo(ComSafeArrayOutArg(aExtraConfigValues));
4107
4108 return S_OK;
4109}
4110
4111/**
4112 * Public method implementation.
4113 * @return
4114 */
4115STDMETHODIMP VirtualSystemDescription::GetDescriptionByType(VirtualSystemDescriptionType_T aType,
4116 ComSafeArrayOut(VirtualSystemDescriptionType_T, aTypes),
4117 ComSafeArrayOut(BSTR, aRefs),
4118 ComSafeArrayOut(BSTR, aOrigValues),
4119 ComSafeArrayOut(BSTR, aVboxValues),
4120 ComSafeArrayOut(BSTR, aExtraConfigValues))
4121{
4122 if (ComSafeArrayOutIsNull(aTypes) ||
4123 ComSafeArrayOutIsNull(aRefs) ||
4124 ComSafeArrayOutIsNull(aOrigValues) ||
4125 ComSafeArrayOutIsNull(aVboxValues) ||
4126 ComSafeArrayOutIsNull(aExtraConfigValues))
4127 return E_POINTER;
4128
4129 AutoCaller autoCaller(this);
4130 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4131
4132 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4133
4134 std::list<VirtualSystemDescriptionEntry*> vsd = findByType (aType);
4135 ULONG c = (ULONG)vsd.size();
4136 com::SafeArray<VirtualSystemDescriptionType_T> sfaTypes(c);
4137 com::SafeArray<BSTR> sfaRefs(c);
4138 com::SafeArray<BSTR> sfaOrigValues(c);
4139 com::SafeArray<BSTR> sfaVboxValues(c);
4140 com::SafeArray<BSTR> sfaExtraConfigValues(c);
4141
4142 list<VirtualSystemDescriptionEntry*>::const_iterator it;
4143 size_t i = 0;
4144 for (it = vsd.begin();
4145 it != vsd.end();
4146 ++it, ++i)
4147 {
4148 const VirtualSystemDescriptionEntry *vsde = (*it);
4149
4150 sfaTypes[i] = vsde->type;
4151
4152 Bstr bstr = vsde->strRef;
4153 bstr.cloneTo(&sfaRefs[i]);
4154
4155 bstr = vsde->strOvf;
4156 bstr.cloneTo(&sfaOrigValues[i]);
4157
4158 bstr = vsde->strVbox;
4159 bstr.cloneTo(&sfaVboxValues[i]);
4160
4161 bstr = vsde->strExtraConfig;
4162 bstr.cloneTo(&sfaExtraConfigValues[i]);
4163 }
4164
4165 sfaTypes.detachTo(ComSafeArrayOutArg(aTypes));
4166 sfaRefs.detachTo(ComSafeArrayOutArg(aRefs));
4167 sfaOrigValues.detachTo(ComSafeArrayOutArg(aOrigValues));
4168 sfaVboxValues.detachTo(ComSafeArrayOutArg(aVboxValues));
4169 sfaExtraConfigValues.detachTo(ComSafeArrayOutArg(aExtraConfigValues));
4170
4171 return S_OK;
4172}
4173
4174/**
4175 * Public method implementation.
4176 * @return
4177 */
4178STDMETHODIMP VirtualSystemDescription::GetValuesByType(VirtualSystemDescriptionType_T aType,
4179 VirtualSystemDescriptionValueType_T aWhich,
4180 ComSafeArrayOut(BSTR, aValues))
4181{
4182 if (ComSafeArrayOutIsNull(aValues))
4183 return E_POINTER;
4184
4185 AutoCaller autoCaller(this);
4186 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4187
4188 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4189
4190 std::list<VirtualSystemDescriptionEntry*> vsd = findByType (aType);
4191 com::SafeArray<BSTR> sfaValues((ULONG)vsd.size());
4192
4193 list<VirtualSystemDescriptionEntry*>::const_iterator it;
4194 size_t i = 0;
4195 for (it = vsd.begin();
4196 it != vsd.end();
4197 ++it, ++i)
4198 {
4199 const VirtualSystemDescriptionEntry *vsde = (*it);
4200
4201 Bstr bstr;
4202 switch (aWhich)
4203 {
4204 case VirtualSystemDescriptionValueType_Reference: bstr = vsde->strRef; break;
4205 case VirtualSystemDescriptionValueType_Original: bstr = vsde->strOvf; break;
4206 case VirtualSystemDescriptionValueType_Auto: bstr = vsde->strVbox; break;
4207 case VirtualSystemDescriptionValueType_ExtraConfig: bstr = vsde->strExtraConfig; break;
4208 }
4209
4210 bstr.cloneTo(&sfaValues[i]);
4211 }
4212
4213 sfaValues.detachTo(ComSafeArrayOutArg(aValues));
4214
4215 return S_OK;
4216}
4217
4218/**
4219 * Public method implementation.
4220 * @return
4221 */
4222STDMETHODIMP VirtualSystemDescription::SetFinalValues(ComSafeArrayIn(BOOL, aEnabled),
4223 ComSafeArrayIn(IN_BSTR, argVboxValues),
4224 ComSafeArrayIn(IN_BSTR, argExtraConfigValues))
4225{
4226#ifndef RT_OS_WINDOWS
4227 NOREF(aEnabledSize);
4228#endif /* RT_OS_WINDOWS */
4229
4230 CheckComArgSafeArrayNotNull(aEnabled);
4231 CheckComArgSafeArrayNotNull(argVboxValues);
4232 CheckComArgSafeArrayNotNull(argExtraConfigValues);
4233
4234 AutoCaller autoCaller(this);
4235 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4236
4237 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4238
4239 com::SafeArray<BOOL> sfaEnabled(ComSafeArrayInArg(aEnabled));
4240 com::SafeArray<IN_BSTR> sfaVboxValues(ComSafeArrayInArg(argVboxValues));
4241 com::SafeArray<IN_BSTR> sfaExtraConfigValues(ComSafeArrayInArg(argExtraConfigValues));
4242
4243 if ( (sfaEnabled.size() != m->llDescriptions.size())
4244 || (sfaVboxValues.size() != m->llDescriptions.size())
4245 || (sfaExtraConfigValues.size() != m->llDescriptions.size())
4246 )
4247 return E_INVALIDARG;
4248
4249 list<VirtualSystemDescriptionEntry>::iterator it;
4250 size_t i = 0;
4251 for (it = m->llDescriptions.begin();
4252 it != m->llDescriptions.end();
4253 ++it, ++i)
4254 {
4255 VirtualSystemDescriptionEntry& vsde = *it;
4256
4257 if (sfaEnabled[i])
4258 {
4259 vsde.strVbox = sfaVboxValues[i];
4260 vsde.strExtraConfig = sfaExtraConfigValues[i];
4261 }
4262 else
4263 vsde.type = VirtualSystemDescriptionType_Ignore;
4264 }
4265
4266 return S_OK;
4267}
4268
4269/**
4270 * Public method implementation.
4271 * @return
4272 */
4273STDMETHODIMP VirtualSystemDescription::AddDescription(VirtualSystemDescriptionType_T aType,
4274 IN_BSTR aVboxValue,
4275 IN_BSTR aExtraConfigValue)
4276{
4277 CheckComArgNotNull(aVboxValue);
4278 CheckComArgNotNull(aExtraConfigValue);
4279
4280 AutoCaller autoCaller(this);
4281 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4282
4283 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4284
4285 addEntry(aType, "", aVboxValue, aVboxValue, 0, aExtraConfigValue);
4286
4287 return S_OK;
4288}
4289
4290/**
4291 * Internal method; adds a new description item to the member list.
4292 * @param aType Type of description for the new item.
4293 * @param strRef Reference item; only used with hard disk controllers.
4294 * @param aOrigValue Corresponding original value from OVF.
4295 * @param aAutoValue Initial configuration value (can be overridden by caller with setFinalValues).
4296 * @param ulSizeMB Weight for IProgress
4297 * @param strExtraConfig Extra configuration; meaning dependent on type.
4298 */
4299void VirtualSystemDescription::addEntry(VirtualSystemDescriptionType_T aType,
4300 const Utf8Str &strRef,
4301 const Utf8Str &aOrigValue,
4302 const Utf8Str &aAutoValue,
4303 uint32_t ulSizeMB,
4304 const Utf8Str &strExtraConfig /*= ""*/)
4305{
4306 VirtualSystemDescriptionEntry vsde;
4307 vsde.ulIndex = (uint32_t)m->llDescriptions.size(); // each entry gets an index so the client side can reference them
4308 vsde.type = aType;
4309 vsde.strRef = strRef;
4310 vsde.strOvf = aOrigValue;
4311 vsde.strVbox = aAutoValue;
4312 vsde.strExtraConfig = strExtraConfig;
4313 vsde.ulSizeMB = ulSizeMB;
4314
4315 m->llDescriptions.push_back(vsde);
4316}
4317
4318/**
4319 * Private method; returns a list of description items containing all the items from the member
4320 * description items of this virtual system that match the given type.
4321 * @param aType
4322 * @return
4323 */
4324std::list<VirtualSystemDescriptionEntry*> VirtualSystemDescription::findByType(VirtualSystemDescriptionType_T aType)
4325{
4326 std::list<VirtualSystemDescriptionEntry*> vsd;
4327
4328 list<VirtualSystemDescriptionEntry>::iterator it;
4329 for (it = m->llDescriptions.begin();
4330 it != m->llDescriptions.end();
4331 ++it)
4332 {
4333 if (it->type == aType)
4334 vsd.push_back(&(*it));
4335 }
4336
4337 return vsd;
4338}
4339
4340/**
4341 * Private method; looks thru the member hardware items for the IDE, SATA, or SCSI controller with
4342 * the given reference ID. Useful when needing the controller for a particular
4343 * virtual disk.
4344 * @param id
4345 * @return
4346 */
4347const VirtualSystemDescriptionEntry* VirtualSystemDescription::findControllerFromID(uint32_t id)
4348{
4349 Utf8Str strRef = Utf8StrFmt("%RI32", id);
4350 list<VirtualSystemDescriptionEntry>::const_iterator it;
4351 for (it = m->llDescriptions.begin();
4352 it != m->llDescriptions.end();
4353 ++it)
4354 {
4355 const VirtualSystemDescriptionEntry &d = *it;
4356 switch (d.type)
4357 {
4358 case VirtualSystemDescriptionType_HardDiskControllerIDE:
4359 case VirtualSystemDescriptionType_HardDiskControllerSATA:
4360 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
4361 if (d.strRef == strRef)
4362 return &d;
4363 break;
4364 }
4365 }
4366
4367 return NULL;
4368}
4369
4370////////////////////////////////////////////////////////////////////////////////
4371//
4372// IMachine public methods
4373//
4374////////////////////////////////////////////////////////////////////////////////
4375
4376// This code is here so we won't have to include the appliance headers in the
4377// IMachine implementation, and we also need to access private appliance data.
4378
4379/**
4380* Public method implementation.
4381* @param appliance
4382* @return
4383*/
4384
4385STDMETHODIMP Machine::Export(IAppliance *aAppliance, IVirtualSystemDescription **aDescription)
4386{
4387 HRESULT rc = S_OK;
4388
4389 if (!aAppliance)
4390 return E_POINTER;
4391
4392 AutoCaller autoCaller(this);
4393 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4394
4395 AutoReadLock alock1(this COMMA_LOCKVAL_SRC_POS);
4396
4397 ComObjPtr<VirtualSystemDescription> pNewDesc;
4398
4399 try
4400 {
4401 Bstr bstrName1;
4402 Bstr bstrDescription;
4403 Bstr bstrGuestOSType;
4404 uint32_t cCPUs;
4405 uint32_t ulMemSizeMB;
4406 BOOL fUSBEnabled;
4407 BOOL fAudioEnabled;
4408 AudioControllerType_T audioController;
4409
4410 ComPtr<IUSBController> pUsbController;
4411 ComPtr<IAudioAdapter> pAudioAdapter;
4412
4413 // get name
4414 bstrName1 = mUserData->mName;
4415 // get description
4416 bstrDescription = mUserData->mDescription;
4417 // get guest OS
4418 bstrGuestOSType = mUserData->mOSTypeId;
4419 // CPU count
4420 cCPUs = mHWData->mCPUCount;
4421 // memory size in MB
4422 ulMemSizeMB = mHWData->mMemorySize;
4423 // VRAM size?
4424 // BIOS settings?
4425 // 3D acceleration enabled?
4426 // hardware virtualization enabled?
4427 // nested paging enabled?
4428 // HWVirtExVPIDEnabled?
4429 // PAEEnabled?
4430 // snapshotFolder?
4431 // VRDPServer?
4432
4433 // this is more tricky so use the COM method
4434 rc = COMGETTER(USBController)(pUsbController.asOutParam());
4435 if (FAILED(rc))
4436 fUSBEnabled = false;
4437 else
4438 rc = pUsbController->COMGETTER(Enabled)(&fUSBEnabled);
4439
4440 pAudioAdapter = mAudioAdapter;
4441 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
4442 if (FAILED(rc)) throw rc;
4443 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
4444 if (FAILED(rc)) throw rc;
4445
4446 // create a new virtual system
4447 rc = pNewDesc.createObject();
4448 if (FAILED(rc)) throw rc;
4449 rc = pNewDesc->init();
4450 if (FAILED(rc)) throw rc;
4451
4452 /* Guest OS type */
4453 Utf8Str strOsTypeVBox(bstrGuestOSType);
4454 CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str());
4455 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
4456 "",
4457 Utf8StrFmt("%RI32", cim),
4458 strOsTypeVBox);
4459
4460 /* VM name */
4461 Utf8Str strVMName(bstrName1);
4462 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
4463 "",
4464 strVMName,
4465 strVMName);
4466
4467 // description
4468 Utf8Str strDescription(bstrDescription);
4469 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
4470 "",
4471 strDescription,
4472 strDescription);
4473
4474 /* CPU count*/
4475 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
4476 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
4477 "",
4478 strCpuCount,
4479 strCpuCount);
4480
4481 /* Memory */
4482 Utf8Str strMemory = Utf8StrFmt("%RI64", (uint64_t)ulMemSizeMB * _1M);
4483 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
4484 "",
4485 strMemory,
4486 strMemory);
4487
4488 int32_t lIDEControllerIndex = 0;
4489 int32_t lSATAControllerIndex = 0;
4490 int32_t lSCSIControllerIndex = 0;
4491
4492 /* Fetch all available storage controllers */
4493 com::SafeIfaceArray<IStorageController> nwControllers;
4494 rc = COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(nwControllers));
4495 if (FAILED(rc)) throw rc;
4496
4497 ComPtr<IStorageController> pIDEController;
4498#ifdef VBOX_WITH_AHCI
4499 ComPtr<IStorageController> pSATAController;
4500#endif /* VBOX_WITH_AHCI */
4501#ifdef VBOX_WITH_LSILOGIC
4502 ComPtr<IStorageController> pSCSIController;
4503#endif /* VBOX_WITH_LSILOGIC */
4504 for (size_t j = 0; j < nwControllers.size(); ++j)
4505 {
4506 StorageBus_T eType;
4507 rc = nwControllers[j]->COMGETTER(Bus)(&eType);
4508 if (FAILED(rc)) throw rc;
4509 if ( eType == StorageBus_IDE
4510 && pIDEController.isNull())
4511 pIDEController = nwControllers[j];
4512#ifdef VBOX_WITH_AHCI
4513 else if ( eType == StorageBus_SATA
4514 && pSATAController.isNull())
4515 pSATAController = nwControllers[j];
4516#endif /* VBOX_WITH_AHCI */
4517#ifdef VBOX_WITH_LSILOGIC
4518 else if ( eType == StorageBus_SCSI
4519 && pSATAController.isNull())
4520 pSCSIController = nwControllers[j];
4521#endif /* VBOX_WITH_LSILOGIC */
4522 }
4523
4524// <const name="HardDiskControllerIDE" value="6" />
4525 if (!pIDEController.isNull())
4526 {
4527 Utf8Str strVbox;
4528 StorageControllerType_T ctlr;
4529 rc = pIDEController->COMGETTER(ControllerType)(&ctlr);
4530 if (FAILED(rc)) throw rc;
4531 switch(ctlr)
4532 {
4533 case StorageControllerType_PIIX3: strVbox = "PIIX3"; break;
4534 case StorageControllerType_PIIX4: strVbox = "PIIX4"; break;
4535 case StorageControllerType_ICH6: strVbox = "ICH6"; break;
4536 }
4537
4538 if (strVbox.length())
4539 {
4540 lIDEControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4541 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
4542 Utf8StrFmt("%d", lIDEControllerIndex),
4543 strVbox,
4544 strVbox);
4545 }
4546 }
4547
4548#ifdef VBOX_WITH_AHCI
4549// <const name="HardDiskControllerSATA" value="7" />
4550 if (!pSATAController.isNull())
4551 {
4552 Utf8Str strVbox = "AHCI";
4553 lSATAControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4554 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
4555 Utf8StrFmt("%d", lSATAControllerIndex),
4556 strVbox,
4557 strVbox);
4558 }
4559#endif // VBOX_WITH_AHCI
4560
4561#ifdef VBOX_WITH_LSILOGIC
4562// <const name="HardDiskControllerSCSI" value="8" />
4563 if (!pSCSIController.isNull())
4564 {
4565 StorageControllerType_T ctlr;
4566 rc = pSCSIController->COMGETTER(ControllerType)(&ctlr);
4567 if (SUCCEEDED(rc))
4568 {
4569 Utf8Str strVbox = "LsiLogic"; // the default in VBox
4570 switch(ctlr)
4571 {
4572 case StorageControllerType_LsiLogic: strVbox = "LsiLogic"; break;
4573 case StorageControllerType_BusLogic: strVbox = "BusLogic"; break;
4574 }
4575 lSCSIControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4576 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
4577 Utf8StrFmt("%d", lSCSIControllerIndex),
4578 strVbox,
4579 strVbox);
4580 }
4581 else
4582 throw rc;
4583 }
4584#endif // VBOX_WITH_LSILOGIC
4585
4586// <const name="HardDiskImage" value="9" />
4587// <const name="Floppy" value="18" />
4588// <const name="CDROM" value="19" />
4589
4590 MediaData::AttachmentList::iterator itA;
4591 for (itA = mMediaData->mAttachments.begin();
4592 itA != mMediaData->mAttachments.end();
4593 ++itA)
4594 {
4595 ComObjPtr<MediumAttachment> pHDA = *itA;
4596
4597 // the attachment's data
4598 ComPtr<IMedium> pMedium;
4599 ComPtr<IStorageController> ctl;
4600 Bstr controllerName;
4601
4602 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
4603 if (FAILED(rc)) throw rc;
4604
4605 rc = GetStorageControllerByName(controllerName, ctl.asOutParam());
4606 if (FAILED(rc)) throw rc;
4607
4608 StorageBus_T storageBus;
4609 DeviceType_T deviceType;
4610 LONG lChannel;
4611 LONG lDevice;
4612
4613 rc = ctl->COMGETTER(Bus)(&storageBus);
4614 if (FAILED(rc)) throw rc;
4615
4616 rc = pHDA->COMGETTER(Type)(&deviceType);
4617 if (FAILED(rc)) throw rc;
4618
4619 rc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
4620 if (FAILED(rc)) throw rc;
4621
4622 rc = pHDA->COMGETTER(Port)(&lChannel);
4623 if (FAILED(rc)) throw rc;
4624
4625 rc = pHDA->COMGETTER(Device)(&lDevice);
4626 if (FAILED(rc)) throw rc;
4627
4628 Utf8Str strTargetVmdkName;
4629 Utf8Str strLocation;
4630 ULONG64 ullSize = 0;
4631
4632 if ( deviceType == DeviceType_HardDisk
4633 && pMedium
4634 )
4635 {
4636 Bstr bstrLocation;
4637 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
4638 if (FAILED(rc)) throw rc;
4639 strLocation = bstrLocation;
4640
4641 Bstr bstrName;
4642 rc = pMedium->COMGETTER(Name)(bstrName.asOutParam());
4643 if (FAILED(rc)) throw rc;
4644
4645 strTargetVmdkName = bstrName;
4646 strTargetVmdkName.stripExt();
4647 strTargetVmdkName.append(".vmdk");
4648
4649 // we need the size of the image so we can give it to addEntry();
4650 // later, on export, the progress weight will be based on this.
4651 // pMedium can be a differencing image though; in that case, we
4652 // need to use the size of the base instead.
4653 ComPtr<IMedium> pBaseMedium;
4654 rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
4655 // returns pMedium if there are no diff images
4656 if (FAILED(rc)) throw rc;
4657
4658 // force reading state, or else size will be returned as 0
4659 MediumState_T ms;
4660 rc = pBaseMedium->RefreshState(&ms);
4661 if (FAILED(rc)) throw rc;
4662
4663 rc = pBaseMedium->COMGETTER(Size)(&ullSize);
4664 if (FAILED(rc)) throw rc;
4665 }
4666
4667 // and how this translates to the virtual system
4668 int32_t lControllerVsys = 0;
4669 LONG lChannelVsys;
4670
4671 switch (storageBus)
4672 {
4673 case StorageBus_IDE:
4674 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
4675 // and it must be updated when that is changed!
4676
4677 if (lChannel == 0 && lDevice == 0) // primary master
4678 lChannelVsys = 0;
4679 else if (lChannel == 0 && lDevice == 1) // primary slave
4680 lChannelVsys = 1;
4681 else if (lChannel == 1 && lDevice == 0) // secondary master; by default this is the CD-ROM but as of VirtualBox 3.1 that can change
4682 lChannelVsys = 2;
4683 else if (lChannel == 1 && lDevice == 1) // secondary slave
4684 lChannelVsys = 3;
4685 else
4686 throw setError(VBOX_E_NOT_SUPPORTED,
4687 tr("Cannot handle medium attachment: channel is %d, device is %d"), lChannel, lDevice);
4688
4689 lControllerVsys = lIDEControllerIndex;
4690 break;
4691
4692 case StorageBus_SATA:
4693 lChannelVsys = lChannel; // should be between 0 and 29
4694 lControllerVsys = lSATAControllerIndex;
4695 break;
4696
4697 case StorageBus_SCSI:
4698 lChannelVsys = lChannel; // should be between 0 and 15
4699 lControllerVsys = lSCSIControllerIndex;
4700 break;
4701
4702 case StorageBus_Floppy:
4703 lChannelVsys = 0;
4704 lControllerVsys = 0;
4705 break;
4706
4707 default:
4708 throw setError(VBOX_E_NOT_SUPPORTED,
4709 tr("Cannot handle medium attachment: storageBus is %d, channel is %d, device is %d"), storageBus, lChannel, lDevice);
4710 break;
4711 }
4712
4713 Utf8StrFmt strExtra("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys);
4714 Utf8Str strEmpty;
4715
4716 switch (deviceType)
4717 {
4718 case DeviceType_HardDisk:
4719 Log(("Adding VirtualSystemDescriptionType_HardDiskImage, disk size: %RI64\n", ullSize));
4720 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
4721 strTargetVmdkName, // disk ID: let's use the name
4722 strTargetVmdkName, // OVF value:
4723 strLocation, // vbox value: media path
4724 (uint32_t)(ullSize / _1M),
4725 strExtra);
4726 break;
4727
4728 case DeviceType_DVD:
4729 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM,
4730 strEmpty, // disk ID
4731 strEmpty, // OVF value
4732 strEmpty, // vbox value
4733 1, // ulSize
4734 strExtra);
4735 break;
4736
4737 case DeviceType_Floppy:
4738 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy,
4739 strEmpty, // disk ID
4740 strEmpty, // OVF value
4741 strEmpty, // vbox value
4742 1, // ulSize
4743 strExtra);
4744 break;
4745 }
4746 }
4747
4748// <const name="NetworkAdapter" />
4749 size_t a;
4750 for (a = 0;
4751 a < SchemaDefs::NetworkAdapterCount;
4752 ++a)
4753 {
4754 ComPtr<INetworkAdapter> pNetworkAdapter;
4755 BOOL fEnabled;
4756 NetworkAdapterType_T adapterType;
4757 NetworkAttachmentType_T attachmentType;
4758
4759 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
4760 if (FAILED(rc)) throw rc;
4761 /* Enable the network card & set the adapter type */
4762 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
4763 if (FAILED(rc)) throw rc;
4764
4765 if (fEnabled)
4766 {
4767 Utf8Str strAttachmentType;
4768
4769 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4770 if (FAILED(rc)) throw rc;
4771
4772 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
4773 if (FAILED(rc)) throw rc;
4774
4775 switch (attachmentType)
4776 {
4777 case NetworkAttachmentType_Null:
4778 strAttachmentType = "Null";
4779 break;
4780
4781 case NetworkAttachmentType_NAT:
4782 strAttachmentType = "NAT";
4783 break;
4784
4785 case NetworkAttachmentType_Bridged:
4786 strAttachmentType = "Bridged";
4787 break;
4788
4789 case NetworkAttachmentType_Internal:
4790 strAttachmentType = "Internal";
4791 break;
4792
4793 case NetworkAttachmentType_HostOnly:
4794 strAttachmentType = "HostOnly";
4795 break;
4796 }
4797
4798 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
4799 "", // ref
4800 strAttachmentType, // orig
4801 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
4802 0,
4803 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
4804 }
4805 }
4806
4807// <const name="USBController" />
4808#ifdef VBOX_WITH_USB
4809 if (fUSBEnabled)
4810 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
4811#endif /* VBOX_WITH_USB */
4812
4813// <const name="SoundCard" />
4814 if (fAudioEnabled)
4815 {
4816 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
4817 "",
4818 "ensoniq1371", // this is what OVFTool writes and VMware supports
4819 Utf8StrFmt("%RI32", audioController));
4820 }
4821
4822 // finally, add the virtual system to the appliance
4823 Appliance *pAppliance = static_cast<Appliance*>(aAppliance);
4824 AutoCaller autoCaller1(pAppliance);
4825 if (FAILED(autoCaller1.rc())) return autoCaller1.rc();
4826
4827 /* We return the new description to the caller */
4828 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
4829 copy.queryInterfaceTo(aDescription);
4830
4831 AutoWriteLock alock(pAppliance COMMA_LOCKVAL_SRC_POS);
4832
4833 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
4834 }
4835 catch(HRESULT arc)
4836 {
4837 rc = arc;
4838 }
4839
4840 return rc;
4841}
4842
4843/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use