VirtualBox

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

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

Main: backing out r57728 + r57730 which burn on windows

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

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