VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/ApplianceImplExport.cpp@ 100841

Last change on this file since 100841 was 99604, checked in by vboxsync, 20 months ago

bugref:10314. bugref:10278. Reverted VSD RAM unit to bytes and fixed other places where MB unit was used.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 125.8 KB
Line 
1/* $Id: ApplianceImplExport.cpp 99604 2023-05-04 13:53:06Z vboxsync $ */
2/** @file
3 * IAppliance and IVirtualSystem COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2008-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28#define LOG_GROUP LOG_GROUP_MAIN_APPLIANCE
29#include <iprt/buildconfig.h>
30#include <iprt/path.h>
31#include <iprt/dir.h>
32#include <iprt/param.h>
33#include <iprt/manifest.h>
34#include <iprt/stream.h>
35#include <iprt/zip.h>
36
37#include <iprt/formats/tar.h>
38
39#include <VBox/version.h>
40
41#include "ApplianceImpl.h"
42#include "VirtualBoxImpl.h"
43#include "ProgressImpl.h"
44#include "MachineImpl.h"
45#include "MediumImpl.h"
46#include "LoggingNew.h"
47#include "Global.h"
48#include "MediumFormatImpl.h"
49#include "SystemPropertiesImpl.h"
50
51#include "AutoCaller.h"
52
53#include "ApplianceImplPrivate.h"
54
55using namespace std;
56
57////////////////////////////////////////////////////////////////////////////////
58//
59// IMachine public methods
60//
61////////////////////////////////////////////////////////////////////////////////
62
63// This code is here so we won't have to include the appliance headers in the
64// IMachine implementation, and we also need to access private appliance data.
65
66/**
67* Public method implementation.
68* @param aAppliance Appliance object.
69* @param aLocation Where to store the appliance.
70* @param aDescription Appliance description.
71* @return
72*/
73HRESULT Machine::exportTo(const ComPtr<IAppliance> &aAppliance, const com::Utf8Str &aLocation,
74 ComPtr<IVirtualSystemDescription> &aDescription)
75{
76 HRESULT hrc = S_OK;
77
78 if (!aAppliance)
79 return E_POINTER;
80
81 ComObjPtr<VirtualSystemDescription> pNewDesc;
82
83 try
84 {
85 IAppliance *iAppliance = aAppliance;
86 Appliance *pAppliance = static_cast<Appliance*>(iAppliance);
87
88 LocationInfo locInfo;
89 i_parseURI(aLocation, locInfo);
90
91 Utf8Str strBasename(locInfo.strPath);
92 strBasename.stripPath().stripSuffix();
93 if (locInfo.strPath.endsWith(".tar.gz", Utf8Str::CaseSensitive))
94 strBasename.stripSuffix();
95
96 // create a new virtual system to store in the appliance
97 hrc = pNewDesc.createObject();
98 if (FAILED(hrc)) throw hrc;
99 hrc = pNewDesc->init();
100 if (FAILED(hrc)) throw hrc;
101
102 // store the machine object so we can dump the XML in Appliance::Write()
103 pNewDesc->m->pMachine = this;
104
105#ifdef VBOX_WITH_USB
106 // first, call the COM methods, as they request locks
107 BOOL fUSBEnabled = FALSE;
108 com::SafeIfaceArray<IUSBController> usbControllers;
109 hrc = COMGETTER(USBControllers)(ComSafeArrayAsOutParam(usbControllers));
110 if (SUCCEEDED(hrc))
111 {
112 for (unsigned i = 0; i < usbControllers.size(); ++i)
113 {
114 USBControllerType_T enmType;
115
116 hrc = usbControllers[i]->COMGETTER(Type)(&enmType);
117 if (FAILED(hrc)) throw hrc;
118
119 if (enmType == USBControllerType_OHCI)
120 fUSBEnabled = TRUE;
121 }
122 }
123#endif /* VBOX_WITH_USB */
124
125 // request the machine lock while accessing internal members
126 AutoReadLock alock1(this COMMA_LOCKVAL_SRC_POS);
127
128 ComPtr<IAudioAdapter> pAudioAdapter;
129 hrc = mAudioSettings->COMGETTER(Adapter)(pAudioAdapter.asOutParam());
130 if (FAILED(hrc)) throw hrc;
131 BOOL fAudioEnabled;
132 hrc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
133 if (FAILED(hrc)) throw hrc;
134 AudioControllerType_T audioController;
135 hrc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
136 if (FAILED(hrc)) throw hrc;
137
138 // get name
139 Utf8Str strVMName = mUserData->s.strName;
140 // get description
141 Utf8Str strDescription = mUserData->s.strDescription;
142 // get guest OS
143 Utf8Str strOsTypeVBox = mUserData->s.strOsType;
144 // CPU count
145 uint32_t cCPUs = mHWData->mCPUCount;
146 // memory size in MB
147 uint32_t ulMemSizeMB = mHWData->mMemorySize;
148 // VRAM size?
149 // BIOS settings?
150 // 3D acceleration enabled?
151 // hardware virtualization enabled?
152 // nested paging enabled?
153 // HWVirtExVPIDEnabled?
154 // PAEEnabled?
155 // Long mode enabled?
156 BOOL fLongMode;
157 hrc = GetCPUProperty(CPUPropertyType_LongMode, &fLongMode);
158 if (FAILED(hrc)) throw hrc;
159
160 // snapshotFolder?
161 // VRDPServer?
162
163 /* Guest OS type */
164 ovf::CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str(), fLongMode);
165 pNewDesc->i_addEntry(VirtualSystemDescriptionType_OS,
166 "",
167 Utf8StrFmt("%RI32", cim),
168 strOsTypeVBox);
169
170 /* VM name */
171 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Name,
172 "",
173 strVMName,
174 strVMName);
175
176 // description
177 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Description,
178 "",
179 strDescription,
180 strDescription);
181
182 /* CPU count*/
183 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
184 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CPU,
185 "",
186 strCpuCount,
187 strCpuCount);
188
189 /* Memory, it's alway stored in bytes in VSD according to the old internal agreement within the team */
190 Utf8Str strMemory = Utf8StrFmt("%RI64", (uint64_t)ulMemSizeMB * _1M);
191 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Memory,
192 "",
193 strMemory,
194 strMemory);
195
196 // the one VirtualBox IDE controller has two channels with two ports each, which is
197 // considered two IDE controllers with two ports each by OVF, so export it as two
198 int32_t lIDEControllerPrimaryIndex = 0;
199 int32_t lIDEControllerSecondaryIndex = 0;
200 int32_t lSATAControllerIndex = 0;
201 int32_t lSCSIControllerIndex = 0;
202 int32_t lVirtioSCSIControllerIndex = 0;
203
204 /* Fetch all available storage controllers */
205 com::SafeIfaceArray<IStorageController> nwControllers;
206 hrc = COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(nwControllers));
207 if (FAILED(hrc)) throw hrc;
208
209 ComPtr<IStorageController> pIDEController;
210 ComPtr<IStorageController> pSATAController;
211 ComPtr<IStorageController> pSCSIController;
212 ComPtr<IStorageController> pVirtioSCSIController;
213 ComPtr<IStorageController> pSASController;
214 for (size_t j = 0; j < nwControllers.size(); ++j)
215 {
216 StorageBus_T eType;
217 hrc = nwControllers[j]->COMGETTER(Bus)(&eType);
218 if (FAILED(hrc)) throw hrc;
219 if ( eType == StorageBus_IDE
220 && pIDEController.isNull())
221 pIDEController = nwControllers[j];
222 else if ( eType == StorageBus_SATA
223 && pSATAController.isNull())
224 pSATAController = nwControllers[j];
225 else if ( eType == StorageBus_SCSI
226 && pSCSIController.isNull())
227 pSCSIController = nwControllers[j];
228 else if ( eType == StorageBus_SAS
229 && pSASController.isNull())
230 pSASController = nwControllers[j];
231 else if ( eType == StorageBus_VirtioSCSI
232 && pVirtioSCSIController.isNull())
233 pVirtioSCSIController = nwControllers[j];
234 }
235
236// <const name="HardDiskControllerIDE" value="6" />
237 if (!pIDEController.isNull())
238 {
239 StorageControllerType_T ctlr;
240 hrc = pIDEController->COMGETTER(ControllerType)(&ctlr);
241 if (FAILED(hrc)) throw hrc;
242
243 Utf8Str strVBox;
244 switch (ctlr)
245 {
246 case StorageControllerType_PIIX3: strVBox = "PIIX3"; break;
247 case StorageControllerType_PIIX4: strVBox = "PIIX4"; break;
248 case StorageControllerType_ICH6: strVBox = "ICH6"; break;
249 default: break; /* Shut up MSC. */
250 }
251
252 if (strVBox.length())
253 {
254 lIDEControllerPrimaryIndex = (int32_t)pNewDesc->m->maDescriptions.size();
255 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
256 Utf8StrFmt("%d", lIDEControllerPrimaryIndex), // strRef
257 strVBox, // aOvfValue
258 strVBox); // aVBoxValue
259 lIDEControllerSecondaryIndex = lIDEControllerPrimaryIndex + 1;
260 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
261 Utf8StrFmt("%d", lIDEControllerSecondaryIndex),
262 strVBox,
263 strVBox);
264 }
265 }
266
267// <const name="HardDiskControllerSATA" value="7" />
268 if (!pSATAController.isNull())
269 {
270 Utf8Str strVBox = "AHCI";
271 lSATAControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
272 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
273 Utf8StrFmt("%d", lSATAControllerIndex),
274 strVBox,
275 strVBox);
276 }
277
278// <const name="HardDiskControllerSCSI" value="8" />
279 if (!pSCSIController.isNull())
280 {
281 StorageControllerType_T ctlr;
282 hrc = pSCSIController->COMGETTER(ControllerType)(&ctlr);
283 if (SUCCEEDED(hrc))
284 {
285 Utf8Str strVBox = "LsiLogic"; // the default in VBox
286 switch (ctlr)
287 {
288 case StorageControllerType_LsiLogic: strVBox = "LsiLogic"; break;
289 case StorageControllerType_BusLogic: strVBox = "BusLogic"; break;
290 default: break; /* Shut up MSC. */
291 }
292 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
293 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
294 Utf8StrFmt("%d", lSCSIControllerIndex),
295 strVBox,
296 strVBox);
297 }
298 else
299 throw hrc;
300 }
301
302 if (!pSASController.isNull())
303 {
304 // VirtualBox considers the SAS controller a class of its own but in OVF
305 // it should be a SCSI controller
306 Utf8Str strVBox = "LsiLogicSas";
307 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
308 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSAS,
309 Utf8StrFmt("%d", lSCSIControllerIndex),
310 strVBox,
311 strVBox);
312 }
313
314 if (!pVirtioSCSIController.isNull())
315 {
316 StorageControllerType_T ctlr;
317 hrc = pVirtioSCSIController->COMGETTER(ControllerType)(&ctlr);
318 if (SUCCEEDED(hrc))
319 {
320 Utf8Str strVBox = "VirtioSCSI"; // the default in VBox
321 switch (ctlr)
322 {
323 case StorageControllerType_VirtioSCSI: strVBox = "VirtioSCSI"; break;
324 default: break; /* Shut up MSC. */
325 }
326 lVirtioSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
327 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerVirtioSCSI,
328 Utf8StrFmt("%d", lVirtioSCSIControllerIndex),
329 strVBox,
330 strVBox);
331 }
332 else
333 throw hrc;
334 }
335
336// <const name="HardDiskImage" value="9" />
337// <const name="Floppy" value="18" />
338// <const name="CDROM" value="19" />
339
340 for (MediumAttachmentList::const_iterator
341 it = mMediumAttachments->begin();
342 it != mMediumAttachments->end();
343 ++it)
344 {
345 ComObjPtr<MediumAttachment> pHDA = *it;
346
347 // the attachment's data
348 ComPtr<IMedium> pMedium;
349 ComPtr<IStorageController> ctl;
350 Bstr controllerName;
351
352 hrc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
353 if (FAILED(hrc)) throw hrc;
354
355 hrc = GetStorageControllerByName(controllerName.raw(), ctl.asOutParam());
356 if (FAILED(hrc)) throw hrc;
357
358 StorageBus_T storageBus;
359 DeviceType_T deviceType;
360 LONG lChannel;
361 LONG lDevice;
362
363 hrc = ctl->COMGETTER(Bus)(&storageBus);
364 if (FAILED(hrc)) throw hrc;
365
366 hrc = pHDA->COMGETTER(Type)(&deviceType);
367 if (FAILED(hrc)) throw hrc;
368
369 hrc = pHDA->COMGETTER(Port)(&lChannel);
370 if (FAILED(hrc)) throw hrc;
371
372 hrc = pHDA->COMGETTER(Device)(&lDevice);
373 if (FAILED(hrc)) throw hrc;
374
375 hrc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
376 if (FAILED(hrc)) throw hrc;
377 if (pMedium.isNull())
378 {
379 Utf8Str strStBus;
380 if ( storageBus == StorageBus_IDE)
381 strStBus = "IDE";
382 else if ( storageBus == StorageBus_SATA)
383 strStBus = "SATA";
384 else if ( storageBus == StorageBus_SCSI)
385 strStBus = "SCSI";
386 else if ( storageBus == StorageBus_SAS)
387 strStBus = "SAS";
388 else if ( storageBus == StorageBus_VirtioSCSI)
389 strStBus = "VirtioSCSI";
390
391 LogRel(("Warning: skip the medium (bus: %s, slot: %d, port: %d). No storage device attached.\n",
392 strStBus.c_str(), lDevice, lChannel));
393 continue;
394 }
395
396 Utf8Str strTargetImageName;
397 Utf8Str strLocation;
398 LONG64 llSize = 0;
399
400 if ( deviceType == DeviceType_HardDisk
401 && pMedium)
402 {
403 Bstr bstrLocation;
404
405 hrc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
406 if (FAILED(hrc)) throw hrc;
407 strLocation = bstrLocation;
408
409 // find the source's base medium for two things:
410 // 1) we'll use its name to determine the name of the target disk, which is readable,
411 // as opposed to the UUID filename of a differencing image, if pMedium is one
412 // 2) we need the size of the base image so we can give it to addEntry(), and later
413 // on export, the progress will be based on that (and not the diff image)
414 ComPtr<IMedium> pBaseMedium;
415 hrc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
416 // returns pMedium if there are no diff images
417 if (FAILED(hrc)) throw hrc;
418
419 strTargetImageName = Utf8StrFmt("%s-disk%.3d.vmdk", strBasename.c_str(), ++pAppliance->m->cDisks);
420 if (strTargetImageName.length() > RTZIPTAR_NAME_MAX)
421 throw setError(VBOX_E_NOT_SUPPORTED,
422 tr("Cannot attach disk '%s' -- file name too long"), strTargetImageName.c_str());
423
424 // force reading state, or else size will be returned as 0
425 MediumState_T ms;
426 hrc = pBaseMedium->RefreshState(&ms);
427 if (FAILED(hrc)) throw hrc;
428
429 hrc = pBaseMedium->COMGETTER(Size)(&llSize);
430 if (FAILED(hrc)) throw hrc;
431
432 /* If the medium is encrypted add the key identifier to the list. */
433 IMedium *iBaseMedium = pBaseMedium;
434 Medium *pBase = static_cast<Medium*>(iBaseMedium);
435 const com::Utf8Str strKeyId = pBase->i_getKeyId();
436 if (!strKeyId.isEmpty())
437 {
438 IMedium *iMedium = pMedium;
439 Medium *pMed = static_cast<Medium*>(iMedium);
440 com::Guid mediumUuid = pMed->i_getId();
441 bool fKnown = false;
442
443 /* Check whether the ID is already in our sequence, add it otherwise. */
444 for (unsigned i = 0; i < pAppliance->m->m_vecPasswordIdentifiers.size(); i++)
445 {
446 if (strKeyId.equals(pAppliance->m->m_vecPasswordIdentifiers[i]))
447 {
448 fKnown = true;
449 break;
450 }
451 }
452
453 if (!fKnown)
454 {
455 GUIDVEC vecMediumIds;
456
457 vecMediumIds.push_back(mediumUuid);
458 pAppliance->m->m_vecPasswordIdentifiers.push_back(strKeyId);
459 pAppliance->m->m_mapPwIdToMediumIds.insert(std::pair<com::Utf8Str, GUIDVEC>(strKeyId, vecMediumIds));
460 }
461 else
462 {
463 std::map<com::Utf8Str, GUIDVEC>::iterator itMap = pAppliance->m->m_mapPwIdToMediumIds.find(strKeyId);
464 if (itMap == pAppliance->m->m_mapPwIdToMediumIds.end())
465 throw setError(E_FAIL, tr("Internal error adding a medium UUID to the map"));
466 itMap->second.push_back(mediumUuid);
467 }
468 }
469 }
470 else if ( deviceType == DeviceType_DVD
471 && pMedium)
472 {
473 /*
474 * check the minimal rules to grant access to export an image
475 * 1. no host drive CD/DVD image
476 * 2. the image must be accessible and readable
477 * 3. only ISO image is exported
478 */
479
480 //1. no host drive CD/DVD image
481 BOOL fHostDrive = false;
482 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
483 if (FAILED(hrc)) throw hrc;
484
485 if(fHostDrive)
486 continue;
487
488 //2. the image must be accessible and readable
489 MediumState_T ms;
490 hrc = pMedium->RefreshState(&ms);
491 if (FAILED(hrc)) throw hrc;
492
493 if (ms != MediumState_Created)
494 continue;
495
496 //3. only ISO image is exported
497 Bstr bstrLocation;
498 hrc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
499 if (FAILED(hrc)) throw hrc;
500
501 strLocation = bstrLocation;
502
503 Utf8Str ext = strLocation;
504 ext.assignEx(RTPathSuffix(strLocation.c_str()));//returns extension with dot (".iso")
505
506 int eq = ext.compare(".iso", Utf8Str::CaseInsensitive);
507 if (eq != 0)
508 continue;
509
510 strTargetImageName = Utf8StrFmt("%s-disk%.3d.iso", strBasename.c_str(), ++pAppliance->m->cDisks);
511 if (strTargetImageName.length() > RTZIPTAR_NAME_MAX)
512 throw setError(VBOX_E_NOT_SUPPORTED,
513 tr("Cannot attach image '%s' -- file name too long"), strTargetImageName.c_str());
514
515 hrc = pMedium->COMGETTER(Size)(&llSize);
516 if (FAILED(hrc)) throw hrc;
517 }
518 // and how this translates to the virtual system
519 int32_t lControllerVsys = 0;
520 LONG lChannelVsys;
521
522 switch (storageBus)
523 {
524 case StorageBus_IDE:
525 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
526 // and it must be updated when that is changed!
527 // Before 3.2 we exported one IDE controller with channel 0-3, but we now maintain
528 // compatibility with what VMware does and export two IDE controllers with two channels each
529
530 if (lChannel == 0 && lDevice == 0) // primary master
531 {
532 lControllerVsys = lIDEControllerPrimaryIndex;
533 lChannelVsys = 0;
534 }
535 else if (lChannel == 0 && lDevice == 1) // primary slave
536 {
537 lControllerVsys = lIDEControllerPrimaryIndex;
538 lChannelVsys = 1;
539 }
540 else if (lChannel == 1 && lDevice == 0) // secondary master; by default this is the CD-ROM but
541 // as of VirtualBox 3.1 that can change
542 {
543 lControllerVsys = lIDEControllerSecondaryIndex;
544 lChannelVsys = 0;
545 }
546 else if (lChannel == 1 && lDevice == 1) // secondary slave
547 {
548 lControllerVsys = lIDEControllerSecondaryIndex;
549 lChannelVsys = 1;
550 }
551 else
552 throw setError(VBOX_E_NOT_SUPPORTED,
553 tr("Cannot handle medium attachment: channel is %d, device is %d"), lChannel, lDevice);
554 break;
555
556 case StorageBus_SATA:
557 lChannelVsys = lChannel; // should be between 0 and 29
558 lControllerVsys = lSATAControllerIndex;
559 break;
560
561 case StorageBus_VirtioSCSI:
562 lChannelVsys = lChannel; // should be between 0 and 255
563 lControllerVsys = lVirtioSCSIControllerIndex;
564 break;
565
566 case StorageBus_SCSI:
567 case StorageBus_SAS:
568 lChannelVsys = lChannel; // should be between 0 and 15
569 lControllerVsys = lSCSIControllerIndex;
570 break;
571
572 case StorageBus_Floppy:
573 lChannelVsys = 0;
574 lControllerVsys = 0;
575 break;
576
577 default:
578 throw setError(VBOX_E_NOT_SUPPORTED,
579 tr("Cannot handle medium attachment: storageBus is %d, channel is %d, device is %d"),
580 storageBus, lChannel, lDevice);
581 }
582
583 Utf8StrFmt strExtra("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys);
584 Utf8Str strEmpty;
585
586 switch (deviceType)
587 {
588 case DeviceType_HardDisk:
589 Log(("Adding VirtualSystemDescriptionType_HardDiskImage, disk size: %RI64\n", llSize));
590 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskImage,
591 strTargetImageName, // disk ID: let's use the name
592 strTargetImageName, // OVF value:
593 strLocation, // vbox value: media path
594 (uint32_t)(llSize / _1M),
595 strExtra);
596 break;
597
598 case DeviceType_DVD:
599 Log(("Adding VirtualSystemDescriptionType_CDROM, disk size: %RI64\n", llSize));
600 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CDROM,
601 strTargetImageName, // disk ID
602 strTargetImageName, // OVF value
603 strLocation, // vbox value
604 (uint32_t)(llSize / _1M),// ulSize
605 strExtra);
606 break;
607
608 case DeviceType_Floppy:
609 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Floppy,
610 strEmpty, // disk ID
611 strEmpty, // OVF value
612 strEmpty, // vbox value
613 1, // ulSize
614 strExtra);
615 break;
616
617 default: break; /* Shut up MSC. */
618 }
619 }
620
621// <const name="NetworkAdapter" />
622 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(i_getChipsetType());
623 size_t a;
624 for (a = 0; a < maxNetworkAdapters; ++a)
625 {
626 ComPtr<INetworkAdapter> pNetworkAdapter;
627 hrc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
628 if (FAILED(hrc)) throw hrc;
629
630 /* Enable the network card & set the adapter type */
631 BOOL fEnabled;
632 hrc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
633 if (FAILED(hrc)) throw hrc;
634
635 if (fEnabled)
636 {
637 NetworkAdapterType_T adapterType;
638 hrc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
639 if (FAILED(hrc)) throw hrc;
640
641 NetworkAttachmentType_T attachmentType;
642 hrc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
643 if (FAILED(hrc)) throw hrc;
644
645 Utf8Str strAttachmentType = convertNetworkAttachmentTypeToString(attachmentType);
646 pNewDesc->i_addEntry(VirtualSystemDescriptionType_NetworkAdapter,
647 "", // ref
648 strAttachmentType, // orig
649 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
650 0,
651 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
652 }
653 }
654
655// <const name="USBController" />
656#ifdef VBOX_WITH_USB
657 if (fUSBEnabled)
658 pNewDesc->i_addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
659#endif /* VBOX_WITH_USB */
660
661// <const name="SoundCard" />
662 if (fAudioEnabled)
663 pNewDesc->i_addEntry(VirtualSystemDescriptionType_SoundCard,
664 "",
665 "ensoniq1371", // this is what OVFTool writes and VMware supports
666 Utf8StrFmt("%RI32", audioController));
667
668 /* We return the new description to the caller */
669 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
670 copy.queryInterfaceTo(aDescription.asOutParam());
671
672 AutoWriteLock alock(pAppliance COMMA_LOCKVAL_SRC_POS);
673 // finally, add the virtual system to the appliance
674 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
675 }
676 catch(HRESULT arc)
677 {
678 hrc = arc;
679 }
680
681 return hrc;
682}
683
684////////////////////////////////////////////////////////////////////////////////
685//
686// IAppliance public methods
687//
688////////////////////////////////////////////////////////////////////////////////
689
690/**
691 * Public method implementation.
692 * @param aFormat Appliance format.
693 * @param aOptions Export options.
694 * @param aPath Path to write the appliance to.
695 * @param aProgress Progress object.
696 * @return
697 */
698HRESULT Appliance::write(const com::Utf8Str &aFormat,
699 const std::vector<ExportOptions_T> &aOptions,
700 const com::Utf8Str &aPath,
701 ComPtr<IProgress> &aProgress)
702{
703 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
704
705 m->optListExport.clear();
706 if (aOptions.size())
707 {
708 for (size_t i = 0; i < aOptions.size(); ++i)
709 {
710 m->optListExport.insert(i, aOptions[i]);
711 }
712 }
713
714 HRESULT hrc = S_OK;
715// AssertReturn(!(m->optListExport.contains(ExportOptions_CreateManifest)
716// && m->optListExport.contains(ExportOptions_ExportDVDImages)), E_INVALIDARG);
717
718 /* Parse all necessary info out of the URI */
719 i_parseURI(aPath, m->locInfo);
720
721 if (m->locInfo.storageType == VFSType_Cloud)
722 {
723 hrc = S_OK;
724 ComObjPtr<Progress> progress;
725 try
726 {
727 hrc = i_writeCloudImpl(m->locInfo, progress);
728 }
729 catch (HRESULT hrcXcpt)
730 {
731 hrc = hrcXcpt;
732 }
733
734 if (SUCCEEDED(hrc))
735 /* Return progress to the caller */
736 progress.queryInterfaceTo(aProgress.asOutParam());
737 }
738 else
739 {
740 m->fExportISOImages = m->optListExport.contains(ExportOptions_ExportDVDImages);
741
742 if (!m->fExportISOImages)/* remove all ISO images from VirtualSystemDescription */
743 {
744 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
745 it = m->virtualSystemDescriptions.begin();
746 it != m->virtualSystemDescriptions.end();
747 ++it)
748 {
749 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
750 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
751 std::list<VirtualSystemDescriptionEntry*>::const_iterator itSkipped = skipped.begin();
752 while (itSkipped != skipped.end())
753 {
754 (*itSkipped)->skipIt = true;
755 ++itSkipped;
756 }
757 }
758 }
759
760 // do not allow entering this method if the appliance is busy reading or writing
761 if (!i_isApplianceIdle())
762 return E_ACCESSDENIED;
763
764 // figure the export format. We exploit the unknown version value for oracle public cloud.
765 ovf::OVFVersion_T ovfF;
766 if (aFormat == "ovf-0.9")
767 ovfF = ovf::OVFVersion_0_9;
768 else if (aFormat == "ovf-1.0")
769 ovfF = ovf::OVFVersion_1_0;
770 else if (aFormat == "ovf-2.0")
771 ovfF = ovf::OVFVersion_2_0;
772 else if (aFormat == "opc-1.0")
773 ovfF = ovf::OVFVersion_unknown;
774 else
775 return setError(VBOX_E_FILE_ERROR,
776 tr("Invalid format \"%s\" specified"), aFormat.c_str());
777
778 // Check the extension.
779 if (ovfF == ovf::OVFVersion_unknown)
780 {
781 if (!aPath.endsWith(".tar.gz", Utf8Str::CaseInsensitive))
782 return setError(VBOX_E_FILE_ERROR,
783 tr("OPC appliance file must have .tar.gz extension"));
784 }
785 else if ( !aPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
786 && !aPath.endsWith(".ova", Utf8Str::CaseInsensitive))
787 return setError(VBOX_E_FILE_ERROR, tr("Appliance file must have .ovf or .ova extension"));
788
789
790 /* As of OVF 2.0 we have to use SHA-256 in the manifest. */
791 m->fManifest = m->optListExport.contains(ExportOptions_CreateManifest);
792 if (m->fManifest)
793 m->fDigestTypes = ovfF >= ovf::OVFVersion_2_0 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1;
794 Assert(m->hOurManifest == NIL_RTMANIFEST);
795
796 /* Check whether all passwords are supplied or error out. */
797 if (m->m_cPwProvided < m->m_vecPasswordIdentifiers.size())
798 return setError(VBOX_E_INVALID_OBJECT_STATE,
799 tr("Appliance export failed because not all passwords were provided for all encrypted media"));
800
801 ComObjPtr<Progress> progress;
802 hrc = S_OK;
803 try
804 {
805 /* Parse all necessary info out of the URI */
806 i_parseURI(aPath, m->locInfo);
807
808 switch (ovfF)
809 {
810 case ovf::OVFVersion_unknown:
811 hrc = i_writeOPCImpl(ovfF, m->locInfo, progress);
812 break;
813 default:
814 hrc = i_writeImpl(ovfF, m->locInfo, progress);
815 break;
816 }
817
818 }
819 catch (HRESULT hrcXcpt)
820 {
821 hrc = hrcXcpt;
822 }
823
824 if (SUCCEEDED(hrc))
825 /* Return progress to the caller */
826 progress.queryInterfaceTo(aProgress.asOutParam());
827 }
828
829 return hrc;
830}
831
832////////////////////////////////////////////////////////////////////////////////
833//
834// Appliance private methods
835//
836////////////////////////////////////////////////////////////////////////////////
837
838/*******************************************************************************
839 * Export stuff
840 ******************************************************************************/
841
842/**
843 * Implementation for writing out the OVF to disk. This starts a new thread which will call
844 * Appliance::taskThreadWriteOVF().
845 *
846 * This is in a separate private method because it is used from two locations:
847 *
848 * 1) from the public Appliance::Write().
849 *
850 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl(), which
851 * called Appliance::i_writeFSOVA(), which called Appliance::i_writeImpl(), which then called this again.
852 *
853 * @param aFormat
854 * @param aLocInfo
855 * @param aProgress
856 * @return
857 */
858HRESULT Appliance::i_writeImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
859{
860 /* Prepare progress object: */
861 HRESULT hrc;
862 try
863 {
864 hrc = i_setUpProgress(aProgress,
865 Utf8StrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
866 aLocInfo.storageType == VFSType_File ? WriteFile : WriteS3);
867 }
868 catch (std::bad_alloc &) /* only Utf8StrFmt */
869 {
870 hrc = E_OUTOFMEMORY;
871 }
872 if (SUCCEEDED(hrc))
873 {
874 /* Create our worker task: */
875 TaskOVF *pTask = NULL;
876 try
877 {
878 pTask = new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress);
879 }
880 catch (std::bad_alloc &)
881 {
882 return E_OUTOFMEMORY;
883 }
884
885 /* The OVF version to produce: */
886 pTask->enFormat = aFormat;
887
888 /* Start the thread: */
889 hrc = pTask->createThread();
890 pTask = NULL;
891 }
892 return hrc;
893}
894
895
896HRESULT Appliance::i_writeCloudImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
897{
898 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
899 it = m->virtualSystemDescriptions.begin();
900 it != m->virtualSystemDescriptions.end();
901 ++it)
902 {
903 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
904 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
905 std::list<VirtualSystemDescriptionEntry*>::const_iterator itSkipped = skipped.begin();
906 while (itSkipped != skipped.end())
907 {
908 (*itSkipped)->skipIt = true;
909 ++itSkipped;
910 }
911
912 //remove all disks from the VirtualSystemDescription exept one
913 skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
914 itSkipped = skipped.begin();
915
916 Utf8Str strBootLocation;
917 while (itSkipped != skipped.end())
918 {
919 if (strBootLocation.isEmpty())
920 strBootLocation = (*itSkipped)->strVBoxCurrent;
921 else
922 (*itSkipped)->skipIt = true;
923 ++itSkipped;
924 }
925
926 //just in case
927 if (vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage).empty())
928 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("There are no images to export to Cloud after preparation steps"));
929
930 /*
931 * Fills out the OCI settings
932 */
933 std::list<VirtualSystemDescriptionEntry*> profileName
934 = vsdescThis->i_findByType(VirtualSystemDescriptionType_CloudProfileName);
935 if (profileName.size() > 1)
936 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("Cloud: More than one profile name was found."));
937 if (profileName.empty())
938 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("Cloud: Profile name wasn't specified."));
939
940 if (profileName.front()->strVBoxCurrent.isEmpty())
941 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("Cloud: Cloud user profile name is empty"));
942
943 LogRel(("profile name: %s\n", profileName.front()->strVBoxCurrent.c_str()));
944 }
945
946 // Create a progress object here otherwise Task won't be created successfully
947 HRESULT hrc = aProgress.createObject();
948 if (SUCCEEDED(hrc))
949 {
950 if (aLocInfo.strProvider.equals("OCI"))
951 hrc = aProgress->init(mVirtualBox, static_cast<IAppliance *>(this),
952 Utf8Str(tr("Exporting VM to Cloud...")),
953 TRUE /* aCancelable */,
954 5, // ULONG cOperations,
955 1000, // ULONG ulTotalOperationsWeight,
956 Utf8Str(tr("Exporting VM to Cloud...")), // aFirstOperationDescription
957 10); // ULONG ulFirstOperationWeight
958 else
959 hrc = setError(VBOX_E_NOT_SUPPORTED,
960 tr("Only \"OCI\" cloud provider is supported for now. \"%s\" isn't supported."),
961 aLocInfo.strProvider.c_str());
962 if (SUCCEEDED(hrc))
963 {
964 /* Initialize the worker task: */
965 TaskCloud *pTask = NULL;
966 try
967 {
968 pTask = new Appliance::TaskCloud(this, TaskCloud::Export, aLocInfo, aProgress);
969 }
970 catch (std::bad_alloc &)
971 {
972 pTask = NULL;
973 hrc = E_OUTOFMEMORY;
974 }
975 if (SUCCEEDED(hrc))
976 {
977 /* Kick off the worker task: */
978 hrc = pTask->createThread();
979 pTask = NULL;
980 }
981 }
982 }
983 return hrc;
984}
985
986HRESULT Appliance::i_writeOPCImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
987{
988 RT_NOREF(aFormat);
989
990 /* Prepare progress object: */
991 HRESULT hrc;
992 try
993 {
994 hrc = i_setUpProgress(aProgress,
995 Utf8StrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
996 aLocInfo.storageType == VFSType_File ? WriteFile : WriteS3);
997 }
998 catch (std::bad_alloc &) /* only Utf8StrFmt */
999 {
1000 hrc = E_OUTOFMEMORY;
1001 }
1002 if (SUCCEEDED(hrc))
1003 {
1004 /* Create our worker task: */
1005 TaskOPC *pTask = NULL;
1006 try
1007 {
1008 pTask = new Appliance::TaskOPC(this, TaskOPC::Export, aLocInfo, aProgress);
1009 }
1010 catch (std::bad_alloc &)
1011 {
1012 return E_OUTOFMEMORY;
1013 }
1014
1015 /* Kick it off: */
1016 hrc = pTask->createThread();
1017 pTask = NULL;
1018 }
1019 return hrc;
1020}
1021
1022
1023/**
1024 * Called from Appliance::i_writeFS() for creating a XML document for this
1025 * Appliance.
1026 *
1027 * @param writeLock The current write lock.
1028 * @param doc The xml document to fill.
1029 * @param stack Structure for temporary private
1030 * data shared with caller.
1031 * @param strPath Path to the target OVF.
1032 * instance for which to write XML.
1033 * @param enFormat OVF format (0.9 or 1.0).
1034 */
1035void Appliance::i_buildXML(AutoWriteLockBase& writeLock,
1036 xml::Document &doc,
1037 XMLStack &stack,
1038 const Utf8Str &strPath,
1039 ovf::OVFVersion_T enFormat)
1040{
1041 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
1042
1043 pelmRoot->setAttribute("ovf:version", enFormat == ovf::OVFVersion_2_0 ? "2.0"
1044 : enFormat == ovf::OVFVersion_1_0 ? "1.0"
1045 : "0.9");
1046 pelmRoot->setAttribute("xml:lang", "en-US");
1047
1048 Utf8Str strNamespace;
1049
1050 if (enFormat == ovf::OVFVersion_0_9)
1051 {
1052 strNamespace = ovf::OVF09_URI_string;
1053 }
1054 else if (enFormat == ovf::OVFVersion_1_0)
1055 {
1056 strNamespace = ovf::OVF10_URI_string;
1057 }
1058 else
1059 {
1060 strNamespace = ovf::OVF20_URI_string;
1061 }
1062
1063 pelmRoot->setAttribute("xmlns", strNamespace);
1064 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
1065
1066 // pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
1067 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
1068 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
1069 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
1070 pelmRoot->setAttribute("xmlns:vbox", "http://www.virtualbox.org/ovf/machine");
1071 // pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
1072
1073 if (enFormat == ovf::OVFVersion_2_0)
1074 {
1075 pelmRoot->setAttribute("xmlns:epasd",
1076 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_EthernetPortAllocationSettingData.xsd");
1077 pelmRoot->setAttribute("xmlns:sasd",
1078 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_StorageAllocationSettingData.xsd");
1079 }
1080
1081 // <Envelope>/<References>
1082 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
1083
1084 /* <Envelope>/<DiskSection>:
1085 <DiskSection>
1086 <Info>List of the virtual disks used in the package</Info>
1087 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
1088 </DiskSection> */
1089 xml::ElementNode *pelmDiskSection;
1090 if (enFormat == ovf::OVFVersion_0_9)
1091 {
1092 // <Section xsi:type="ovf:DiskSection_Type">
1093 pelmDiskSection = pelmRoot->createChild("Section");
1094 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
1095 }
1096 else
1097 pelmDiskSection = pelmRoot->createChild("DiskSection");
1098
1099 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
1100 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
1101
1102 /* <Envelope>/<NetworkSection>:
1103 <NetworkSection>
1104 <Info>Logical networks used in the package</Info>
1105 <Network ovf:name="VM Network">
1106 <Description>The network that the LAMP Service will be available on</Description>
1107 </Network>
1108 </NetworkSection> */
1109 xml::ElementNode *pelmNetworkSection;
1110 if (enFormat == ovf::OVFVersion_0_9)
1111 {
1112 // <Section xsi:type="ovf:NetworkSection_Type">
1113 pelmNetworkSection = pelmRoot->createChild("Section");
1114 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
1115 }
1116 else
1117 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
1118
1119 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
1120 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
1121
1122 // and here come the virtual systems:
1123
1124 // write a collection if we have more than one virtual system _and_ we're
1125 // writing OVF 1.0; otherwise fail since ovftool can't import more than
1126 // one machine, it seems
1127 xml::ElementNode *pelmToAddVirtualSystemsTo;
1128 if (m->virtualSystemDescriptions.size() > 1)
1129 {
1130 if (enFormat == ovf::OVFVersion_0_9)
1131 throw setError(VBOX_E_FILE_ERROR,
1132 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
1133
1134 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
1135 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
1136 }
1137 else
1138 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
1139
1140 // this list receives pointers to the XML elements in the machine XML which
1141 // might have UUIDs that need fixing after we know the UUIDs of the exported images
1142 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
1143 uint32_t ulFile = 1;
1144 /* Iterate through all virtual systems of that appliance */
1145 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
1146 itV = m->virtualSystemDescriptions.begin();
1147 itV != m->virtualSystemDescriptions.end();
1148 ++itV)
1149 {
1150 ComObjPtr<VirtualSystemDescription> vsdescThis = *itV;
1151 i_buildXMLForOneVirtualSystem(writeLock,
1152 *pelmToAddVirtualSystemsTo,
1153 &llElementsWithUuidAttributes,
1154 vsdescThis,
1155 enFormat,
1156 stack); // disks and networks stack
1157
1158 list<Utf8Str> diskList;
1159
1160 for (list<Utf8Str>::const_iterator
1161 itDisk = stack.mapDiskSequenceForOneVM.begin();
1162 itDisk != stack.mapDiskSequenceForOneVM.end();
1163 ++itDisk)
1164 {
1165 const Utf8Str &strDiskID = *itDisk;
1166 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
1167
1168 // source path: where the VBox image is
1169 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
1170 Bstr bstrSrcFilePath(strSrcFilePath);
1171
1172 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1173 if (strSrcFilePath.isEmpty() ||
1174 pDiskEntry->skipIt == true)
1175 continue;
1176
1177 // Do NOT check here whether the file exists. FindMedium will figure
1178 // that out, and filesystem-based tests are simply wrong in the
1179 // general case (think of iSCSI).
1180
1181 // We need some info from the source disks
1182 ComPtr<IMedium> pSourceDisk;
1183 //DeviceType_T deviceType = DeviceType_HardDisk;// by default
1184
1185 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
1186
1187 HRESULT hrc;
1188
1189 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
1190 {
1191 hrc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
1192 DeviceType_HardDisk,
1193 AccessMode_ReadWrite,
1194 FALSE /* fForceNewUuid */,
1195 pSourceDisk.asOutParam());
1196 if (FAILED(hrc))
1197 throw hrc;
1198 }
1199 else if (pDiskEntry->type == VirtualSystemDescriptionType_CDROM)//may be, this is CD/DVD
1200 {
1201 hrc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
1202 DeviceType_DVD,
1203 AccessMode_ReadOnly,
1204 FALSE,
1205 pSourceDisk.asOutParam());
1206 if (FAILED(hrc))
1207 throw hrc;
1208 }
1209
1210 Bstr uuidSource;
1211 hrc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1212 if (FAILED(hrc)) throw hrc;
1213 Guid guidSource(uuidSource);
1214
1215 // output filename
1216 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1217
1218 // target path needs to be composed from where the output OVF is
1219 Utf8Str strTargetFilePath(strPath);
1220 strTargetFilePath.stripFilename();
1221 strTargetFilePath.append("/");
1222 strTargetFilePath.append(strTargetFileNameOnly);
1223
1224 // We are always exporting to VMDK stream optimized for now
1225 //Bstr bstrSrcFormat = L"VMDK";//not used
1226
1227 diskList.push_back(strTargetFilePath);
1228
1229 LONG64 cbCapacity = 0; // size reported to guest
1230 hrc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
1231 if (FAILED(hrc)) throw hrc;
1232 /// @todo r=poetzsch: wrong it is reported in bytes ...
1233 // capacity is reported in megabytes, so...
1234 //cbCapacity *= _1M;
1235
1236 Guid guidTarget; /* Creates a new uniq number for the target disk. */
1237 guidTarget.create();
1238
1239 // now handle the XML for the disk:
1240 Utf8StrFmt strFileRef("file%RI32", ulFile++);
1241 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
1242 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
1243 pelmFile->setAttribute("ovf:id", strFileRef);
1244 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
1245 /// @todo the actual size is not available at this point of time,
1246 // cause the disk will be compressed. The 1.0 standard says this is
1247 // optional! 1.1 isn't fully clear if the "gzip" format is used.
1248 // Need to be checked. */
1249 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
1250
1251 // add disk to XML Disks section
1252 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
1253 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
1254 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
1255 pelmDisk->setAttribute("ovf:diskId", strDiskID);
1256 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
1257
1258 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)//deviceType == DeviceType_HardDisk
1259 {
1260 pelmDisk->setAttribute("ovf:format",
1261 (enFormat == ovf::OVFVersion_0_9)
1262 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftoo
1263 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
1264 // correct string as communicated to us by VMware (public bug #6612)
1265 );
1266 }
1267 else //pDiskEntry->type == VirtualSystemDescriptionType_CDROM, deviceType == DeviceType_DVD
1268 {
1269 pelmDisk->setAttribute("ovf:format",
1270 "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
1271 );
1272 }
1273
1274 // add the UUID of the newly target image to the OVF disk element, but in the
1275 // vbox: namespace since it's not part of the standard
1276 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
1277
1278 // now, we might have other XML elements from vbox:Machine pointing to this image,
1279 // but those would refer to the UUID of the _source_ image (which we created the
1280 // export image from); those UUIDs need to be fixed to the export image
1281 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
1282 for (std::list<xml::ElementNode*>::const_iterator
1283 it = llElementsWithUuidAttributes.begin();
1284 it != llElementsWithUuidAttributes.end();
1285 ++it)
1286 {
1287 xml::ElementNode *pelmImage = *it;
1288 Utf8Str strUUID;
1289 pelmImage->getAttributeValue("uuid", strUUID);
1290 if (strUUID == strGuidSourceCurly)
1291 // overwrite existing uuid attribute
1292 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
1293 }
1294 }
1295 llElementsWithUuidAttributes.clear();
1296 stack.mapDiskSequenceForOneVM.clear();
1297 }
1298
1299 // now, fill in the network section we set up empty above according
1300 // to the networks we found with the hardware items
1301 for (map<Utf8Str, bool>::const_iterator
1302 it = stack.mapNetworks.begin();
1303 it != stack.mapNetworks.end();
1304 ++it)
1305 {
1306 const Utf8Str &strNetwork = it->first;
1307 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
1308 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
1309 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
1310 }
1311
1312}
1313
1314/**
1315 * Called from Appliance::i_buildXML() for each virtual system (machine) that
1316 * needs XML written out.
1317 *
1318 * @param writeLock The current write lock.
1319 * @param elmToAddVirtualSystemsTo XML element to append elements to.
1320 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
1321 * with UUID attributes for quick
1322 * fixing by caller later
1323 * @param vsdescThis The IVirtualSystemDescription
1324 * instance for which to write XML.
1325 * @param enFormat OVF format (0.9 or 1.0).
1326 * @param stack Structure for temporary private
1327 * data shared with caller.
1328 */
1329void Appliance::i_buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
1330 xml::ElementNode &elmToAddVirtualSystemsTo,
1331 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
1332 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1333 ovf::OVFVersion_T enFormat,
1334 XMLStack &stack)
1335{
1336 LogFlowFunc(("ENTER appliance %p\n", this));
1337
1338 xml::ElementNode *pelmVirtualSystem;
1339 if (enFormat == ovf::OVFVersion_0_9)
1340 {
1341 // <Section xsi:type="ovf:NetworkSection_Type">
1342 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
1343 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
1344 }
1345 else
1346 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
1347
1348 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
1349
1350 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
1351 if (llName.empty())
1352 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing VM name"));
1353 Utf8Str &strVMName = llName.back()->strVBoxCurrent;
1354 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
1355
1356 // product info
1357 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->i_findByType(VirtualSystemDescriptionType_Product);
1358 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_ProductUrl);
1359 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->i_findByType(VirtualSystemDescriptionType_Vendor);
1360 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_VendorUrl);
1361 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->i_findByType(VirtualSystemDescriptionType_Version);
1362 bool fProduct = llProduct.size() && !llProduct.back()->strVBoxCurrent.isEmpty();
1363 bool fProductUrl = llProductUrl.size() && !llProductUrl.back()->strVBoxCurrent.isEmpty();
1364 bool fVendor = llVendor.size() && !llVendor.back()->strVBoxCurrent.isEmpty();
1365 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.back()->strVBoxCurrent.isEmpty();
1366 bool fVersion = llVersion.size() && !llVersion.back()->strVBoxCurrent.isEmpty();
1367 if (fProduct || fProductUrl || fVendor || fVendorUrl || fVersion)
1368 {
1369 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1370 <Info>Meta-information about the installed software</Info>
1371 <Product>VAtest</Product>
1372 <Vendor>SUN Microsystems</Vendor>
1373 <Version>10.0</Version>
1374 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
1375 <VendorUrl>http://www.sun.com</VendorUrl>
1376 </Section> */
1377 xml::ElementNode *pelmAnnotationSection;
1378 if (enFormat == ovf::OVFVersion_0_9)
1379 {
1380 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1381 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1382 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
1383 }
1384 else
1385 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
1386
1387 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
1388 if (fProduct)
1389 pelmAnnotationSection->createChild("Product")->addContent(llProduct.back()->strVBoxCurrent);
1390 if (fVendor)
1391 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.back()->strVBoxCurrent);
1392 if (fVersion)
1393 pelmAnnotationSection->createChild("Version")->addContent(llVersion.back()->strVBoxCurrent);
1394 if (fProductUrl)
1395 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.back()->strVBoxCurrent);
1396 if (fVendorUrl)
1397 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.back()->strVBoxCurrent);
1398 }
1399
1400 // description
1401 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
1402 if (llDescription.size() &&
1403 !llDescription.back()->strVBoxCurrent.isEmpty())
1404 {
1405 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1406 <Info>A human-readable annotation</Info>
1407 <Annotation>Plan 9</Annotation>
1408 </Section> */
1409 xml::ElementNode *pelmAnnotationSection;
1410 if (enFormat == ovf::OVFVersion_0_9)
1411 {
1412 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1413 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1414 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
1415 }
1416 else
1417 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
1418
1419 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1420 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.back()->strVBoxCurrent);
1421 }
1422
1423 // license
1424 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->i_findByType(VirtualSystemDescriptionType_License);
1425 if (llLicense.size() &&
1426 !llLicense.back()->strVBoxCurrent.isEmpty())
1427 {
1428 /* <EulaSection>
1429 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1430 <License ovf:msgid="1">License terms can go in here.</License>
1431 </EulaSection> */
1432 xml::ElementNode *pelmEulaSection;
1433 if (enFormat == ovf::OVFVersion_0_9)
1434 {
1435 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1436 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1437 }
1438 else
1439 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1440
1441 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1442 pelmEulaSection->createChild("License")->addContent(llLicense.back()->strVBoxCurrent);
1443 }
1444
1445 // operating system
1446 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
1447 if (llOS.empty())
1448 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing OS type"));
1449 /* <OperatingSystemSection ovf:id="82">
1450 <Info>Guest Operating System</Info>
1451 <Description>Linux 2.6.x</Description>
1452 </OperatingSystemSection> */
1453 VirtualSystemDescriptionEntry *pvsdeOS = llOS.back();
1454 xml::ElementNode *pelmOperatingSystemSection;
1455 if (enFormat == ovf::OVFVersion_0_9)
1456 {
1457 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1458 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1459 }
1460 else
1461 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1462
1463 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1464 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1465 Utf8Str strOSDesc;
1466 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1467 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1468 // add the VirtualBox ostype in a custom tag in a different namespace
1469 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1470 pelmVBoxOSType->setAttribute("ovf:required", "false");
1471 pelmVBoxOSType->addContent(pvsdeOS->strVBoxCurrent);
1472
1473 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1474 xml::ElementNode *pelmVirtualHardwareSection;
1475 if (enFormat == ovf::OVFVersion_0_9)
1476 {
1477 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1478 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1479 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1480 }
1481 else
1482 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1483
1484 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1485
1486 /* <System>
1487 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1488 <vssd:ElementName>vmware</vssd:ElementName>
1489 <vssd:InstanceID>1</vssd:InstanceID>
1490 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1491 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1492 </System> */
1493 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1494
1495 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1496
1497 // <vssd:InstanceId>0</vssd:InstanceId>
1498 if (enFormat == ovf::OVFVersion_0_9)
1499 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1500 else // capitalization changed...
1501 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1502
1503 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1504 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1505 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1506 const char *pcszHardware = "virtualbox-2.2";
1507 if (enFormat == ovf::OVFVersion_0_9)
1508 // pretend to be vmware compatible then
1509 pcszHardware = "vmx-6";
1510 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1511
1512 // loop thru all description entries twice; once to write out all
1513 // devices _except_ disk images, and a second time to assign the
1514 // disk images; this is because disk images need to reference
1515 // IDE controllers, and we can't know their instance IDs without
1516 // assigning them first
1517
1518 uint32_t idIDEPrimaryController = 0;
1519 int32_t lIDEPrimaryControllerIndex = 0;
1520 uint32_t idIDESecondaryController = 0;
1521 int32_t lIDESecondaryControllerIndex = 0;
1522 uint32_t idSATAController = 0;
1523 int32_t lSATAControllerIndex = 0;
1524 uint32_t idSCSIController = 0;
1525 int32_t lSCSIControllerIndex = 0;
1526 uint32_t idVirtioSCSIController = 0;
1527 int32_t lVirtioSCSIControllerIndex = 0;
1528
1529 uint32_t ulInstanceID = 1;
1530
1531 uint32_t cDVDs = 0;
1532
1533 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1534 {
1535 int32_t lIndexThis = 0;
1536 for (vector<VirtualSystemDescriptionEntry>::const_iterator
1537 it = vsdescThis->m->maDescriptions.begin();
1538 it != vsdescThis->m->maDescriptions.end();
1539 ++it, ++lIndexThis)
1540 {
1541 const VirtualSystemDescriptionEntry &desc = *it;
1542
1543 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVBox=%s, strExtraConfig=%s\n",
1544 uLoop,
1545 desc.ulIndex,
1546 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1547 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1548 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1549 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1550 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1551 : Utf8StrFmt("%d", desc.type).c_str()),
1552 desc.strRef.c_str(),
1553 desc.strOvf.c_str(),
1554 desc.strVBoxCurrent.c_str(),
1555 desc.strExtraConfigCurrent.c_str()));
1556
1557 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1558 Utf8Str strResourceSubType;
1559
1560 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1561 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1562
1563 uint32_t ulParent = 0;
1564
1565 int32_t lVirtualQuantity = -1;
1566 Utf8Str strAllocationUnits;
1567
1568 int32_t lAddress = -1;
1569 int32_t lBusNumber = -1;
1570 int32_t lAddressOnParent = -1;
1571
1572 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1573 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1574 Utf8Str strHostResource;
1575
1576 uint64_t uTemp;
1577
1578 ovf::VirtualHardwareItem vhi;
1579 ovf::StorageItem si;
1580 ovf::EthernetPortItem epi;
1581
1582 switch (desc.type)
1583 {
1584 case VirtualSystemDescriptionType_CPU:
1585 /* <Item>
1586 <rasd:Caption>1 virtual CPU</rasd:Caption>
1587 <rasd:Description>Number of virtual CPUs</rasd:Description>
1588 <rasd:ElementName>virtual CPU</rasd:ElementName>
1589 <rasd:InstanceID>1</rasd:InstanceID>
1590 <rasd:ResourceType>3</rasd:ResourceType>
1591 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1592 </Item> */
1593 if (uLoop == 1)
1594 {
1595 strDescription = "Number of virtual CPUs";
1596 type = ovf::ResourceType_Processor; // 3
1597 desc.strVBoxCurrent.toInt(uTemp);
1598 lVirtualQuantity = (int32_t)uTemp;
1599 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool
1600 // won't eat the item
1601 }
1602 break;
1603
1604 case VirtualSystemDescriptionType_Memory:
1605 /* <Item>
1606 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1607 <rasd:Caption>256 MB of memory</rasd:Caption>
1608 <rasd:Description>Memory Size</rasd:Description>
1609 <rasd:ElementName>Memory</rasd:ElementName>
1610 <rasd:InstanceID>2</rasd:InstanceID>
1611 <rasd:ResourceType>4</rasd:ResourceType>
1612 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1613 </Item> */
1614 if (uLoop == 1)
1615 {
1616 strDescription = "Memory Size";
1617 type = ovf::ResourceType_Memory; // 4
1618 desc.strVBoxCurrent.toInt(uTemp);
1619 /* It's alway stored in bytes in VSD according to the old internal agreement within the team */
1620 lVirtualQuantity = (int32_t)(uTemp / _1M);
1621 strAllocationUnits = "MegaBytes";
1622 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool
1623 // won't eat the item
1624 }
1625 break;
1626
1627 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1628 /* <Item>
1629 <rasd:Caption>ideController1</rasd:Caption>
1630 <rasd:Description>IDE Controller</rasd:Description>
1631 <rasd:InstanceId>5</rasd:InstanceId>
1632 <rasd:ResourceType>5</rasd:ResourceType>
1633 <rasd:Address>1</rasd:Address>
1634 <rasd:BusNumber>1</rasd:BusNumber>
1635 </Item> */
1636 if (uLoop == 1)
1637 {
1638 strDescription = "IDE Controller";
1639 type = ovf::ResourceType_IDEController; // 5
1640 strResourceSubType = desc.strVBoxCurrent;
1641
1642 if (!lIDEPrimaryControllerIndex)
1643 {
1644 // first IDE controller:
1645 strCaption = "ideController0";
1646 lAddress = 0;
1647 lBusNumber = 0;
1648 // remember this ID
1649 idIDEPrimaryController = ulInstanceID;
1650 lIDEPrimaryControllerIndex = lIndexThis;
1651 }
1652 else
1653 {
1654 // second IDE controller:
1655 strCaption = "ideController1";
1656 lAddress = 1;
1657 lBusNumber = 1;
1658 // remember this ID
1659 idIDESecondaryController = ulInstanceID;
1660 lIDESecondaryControllerIndex = lIndexThis;
1661 }
1662 }
1663 break;
1664
1665 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1666 /* <Item>
1667 <rasd:Caption>sataController0</rasd:Caption>
1668 <rasd:Description>SATA Controller</rasd:Description>
1669 <rasd:InstanceId>4</rasd:InstanceId>
1670 <rasd:ResourceType>20</rasd:ResourceType>
1671 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1672 <rasd:Address>0</rasd:Address>
1673 <rasd:BusNumber>0</rasd:BusNumber>
1674 </Item>
1675 */
1676 if (uLoop == 1)
1677 {
1678 strDescription = "SATA Controller";
1679 strCaption = "sataController0";
1680 type = ovf::ResourceType_OtherStorageDevice; // 20
1681 // it seems that OVFTool always writes these two, and since we can only
1682 // have one SATA controller, we'll use this as well
1683 lAddress = 0;
1684 lBusNumber = 0;
1685
1686 if ( desc.strVBoxCurrent.isEmpty() // AHCI is the default in VirtualBox
1687 || (!desc.strVBoxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1688 )
1689 strResourceSubType = "AHCI";
1690 else
1691 throw setError(VBOX_E_NOT_SUPPORTED,
1692 tr("Invalid config string \"%s\" in SATA controller"), desc.strVBoxCurrent.c_str());
1693
1694 // remember this ID
1695 idSATAController = ulInstanceID;
1696 lSATAControllerIndex = lIndexThis;
1697 }
1698 break;
1699
1700 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1701 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1702 /* <Item>
1703 <rasd:Caption>scsiController0</rasd:Caption>
1704 <rasd:Description>SCSI Controller</rasd:Description>
1705 <rasd:InstanceId>4</rasd:InstanceId>
1706 <rasd:ResourceType>6</rasd:ResourceType>
1707 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1708 <rasd:Address>0</rasd:Address>
1709 <rasd:BusNumber>0</rasd:BusNumber>
1710 </Item>
1711 */
1712 if (uLoop == 1)
1713 {
1714 strDescription = "SCSI Controller";
1715 strCaption = "scsiController0";
1716 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1717 // it seems that OVFTool always writes these two, and since we can only
1718 // have one SATA controller, we'll use this as well
1719 lAddress = 0;
1720 lBusNumber = 0;
1721
1722 if ( desc.strVBoxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1723 || (!desc.strVBoxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1724 )
1725 strResourceSubType = "lsilogic";
1726 else if (!desc.strVBoxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1727 strResourceSubType = "buslogic";
1728 else if (!desc.strVBoxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1729 strResourceSubType = "lsilogicsas";
1730 else
1731 throw setError(VBOX_E_NOT_SUPPORTED,
1732 tr("Invalid config string \"%s\" in SCSI/SAS controller"),
1733 desc.strVBoxCurrent.c_str());
1734
1735 // remember this ID
1736 idSCSIController = ulInstanceID;
1737 lSCSIControllerIndex = lIndexThis;
1738 }
1739 break;
1740
1741
1742 case VirtualSystemDescriptionType_HardDiskControllerVirtioSCSI:
1743 /* <Item>
1744 <rasd:Caption>VirtioSCSIController0</rasd:Caption>
1745 <rasd:Description>VirtioSCSI Controller</rasd:Description>
1746 <rasd:InstanceId>4</rasd:InstanceId>
1747 <rasd:ResourceType>20</rasd:ResourceType>
1748 <rasd:Address>0</rasd:Address>
1749 <rasd:BusNumber>0</rasd:BusNumber>
1750 </Item>
1751 */
1752 if (uLoop == 1)
1753 {
1754 strDescription = "VirtioSCSI Controller";
1755 strCaption = "virtioSCSIController0";
1756 type = ovf::ResourceType_OtherStorageDevice; // 20
1757 lAddress = 0;
1758 lBusNumber = 0;
1759 strResourceSubType = "VirtioSCSI";
1760 // remember this ID
1761 idVirtioSCSIController = ulInstanceID;
1762 lVirtioSCSIControllerIndex = lIndexThis;
1763 }
1764 break;
1765
1766 case VirtualSystemDescriptionType_HardDiskImage:
1767 /* <Item>
1768 <rasd:Caption>disk1</rasd:Caption>
1769 <rasd:InstanceId>8</rasd:InstanceId>
1770 <rasd:ResourceType>17</rasd:ResourceType>
1771 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1772 <rasd:Parent>4</rasd:Parent>
1773 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1774 </Item> */
1775 if (uLoop == 2)
1776 {
1777 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1778 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1779
1780 strDescription = "Disk Image";
1781 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1782 type = ovf::ResourceType_HardDisk; // 17
1783
1784 // the following references the "<Disks>" XML block
1785 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1786
1787 // controller=<index>;channel=<c>
1788 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1789 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1790 int32_t lControllerIndex = -1;
1791 if (pos1 != Utf8Str::npos)
1792 {
1793 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1794 if (lControllerIndex == lIDEPrimaryControllerIndex)
1795 ulParent = idIDEPrimaryController;
1796 else if (lControllerIndex == lIDESecondaryControllerIndex)
1797 ulParent = idIDESecondaryController;
1798 else if (lControllerIndex == lSCSIControllerIndex)
1799 ulParent = idSCSIController;
1800 else if (lControllerIndex == lSATAControllerIndex)
1801 ulParent = idSATAController;
1802 else if (lControllerIndex == lVirtioSCSIControllerIndex)
1803 ulParent = idVirtioSCSIController;
1804 }
1805 if (pos2 != Utf8Str::npos)
1806 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1807
1808 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1809 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex,
1810 ulParent, lAddressOnParent));
1811
1812 if ( !ulParent
1813 || lAddressOnParent == -1
1814 )
1815 throw setError(VBOX_E_NOT_SUPPORTED,
1816 tr("Missing or bad extra config string in hard disk image: \"%s\""),
1817 desc.strExtraConfigCurrent.c_str());
1818 stack.mapDisks[strDiskID] = &desc;
1819
1820 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1821 //in the OVF description file.
1822 stack.mapDiskSequence.push_back(strDiskID);
1823 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1824 }
1825 break;
1826
1827 case VirtualSystemDescriptionType_Floppy:
1828 if (uLoop == 1)
1829 {
1830 strDescription = "Floppy Drive";
1831 strCaption = "floppy0"; // this is what OVFTool writes
1832 type = ovf::ResourceType_FloppyDrive; // 14
1833 lAutomaticAllocation = 0;
1834 lAddressOnParent = 0; // this is what OVFTool writes
1835 }
1836 break;
1837
1838 case VirtualSystemDescriptionType_CDROM:
1839 /* <Item>
1840 <rasd:Caption>cdrom1</rasd:Caption>
1841 <rasd:InstanceId>8</rasd:InstanceId>
1842 <rasd:ResourceType>15</rasd:ResourceType>
1843 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1844 <rasd:Parent>4</rasd:Parent>
1845 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1846 </Item> */
1847 if (uLoop == 2)
1848 {
1849 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1850 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDisks);
1851 ++cDVDs;
1852 strDescription = "CD-ROM Drive";
1853 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1854 type = ovf::ResourceType_CDDrive; // 15
1855 lAutomaticAllocation = 1;
1856
1857 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1858 if (desc.strVBoxCurrent.isNotEmpty() &&
1859 desc.skipIt == false)
1860 {
1861 // the following references the "<Disks>" XML block
1862 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1863 }
1864
1865 // controller=<index>;channel=<c>
1866 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1867 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1868 int32_t lControllerIndex = -1;
1869 if (pos1 != Utf8Str::npos)
1870 {
1871 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1872 if (lControllerIndex == lIDEPrimaryControllerIndex)
1873 ulParent = idIDEPrimaryController;
1874 else if (lControllerIndex == lIDESecondaryControllerIndex)
1875 ulParent = idIDESecondaryController;
1876 else if (lControllerIndex == lSCSIControllerIndex)
1877 ulParent = idSCSIController;
1878 else if (lControllerIndex == lSATAControllerIndex)
1879 ulParent = idSATAController;
1880 }
1881 if (pos2 != Utf8Str::npos)
1882 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1883
1884 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1885 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex,
1886 lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1887
1888 if ( !ulParent
1889 || lAddressOnParent == -1
1890 )
1891 throw setError(VBOX_E_NOT_SUPPORTED,
1892 tr("Missing or bad extra config string in DVD drive medium: \"%s\""),
1893 desc.strExtraConfigCurrent.c_str());
1894
1895 stack.mapDisks[strDiskID] = &desc;
1896
1897 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1898 //in the OVF description file.
1899 stack.mapDiskSequence.push_back(strDiskID);
1900 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1901 // there is no DVD drive map to update because it is
1902 // handled completely with this entry.
1903 }
1904 break;
1905
1906 case VirtualSystemDescriptionType_NetworkAdapter:
1907 /* <Item>
1908 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1909 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1910 <rasd:Connection>VM Network</rasd:Connection>
1911 <rasd:ElementName>VM network</rasd:ElementName>
1912 <rasd:InstanceID>3</rasd:InstanceID>
1913 <rasd:ResourceType>10</rasd:ResourceType>
1914 </Item> */
1915 if (uLoop == 2)
1916 {
1917 lAutomaticAllocation = 1;
1918 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1919 type = ovf::ResourceType_EthernetAdapter; // 10
1920 /* Set the hardware type to something useful.
1921 * To be compatible with vmware & others we set
1922 * PCNet32 for our PCNet types & E1000 for the
1923 * E1000 cards. */
1924 switch (desc.strVBoxCurrent.toInt32())
1925 {
1926 case NetworkAdapterType_Am79C970A:
1927 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1928#ifdef VBOX_WITH_E1000
1929 case NetworkAdapterType_I82540EM:
1930 case NetworkAdapterType_I82545EM:
1931 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1932#endif /* VBOX_WITH_E1000 */
1933 }
1934 strConnection = desc.strOvf;
1935
1936 stack.mapNetworks[desc.strOvf] = true;
1937 }
1938 break;
1939
1940 case VirtualSystemDescriptionType_USBController:
1941 /* <Item ovf:required="false">
1942 <rasd:Caption>usb</rasd:Caption>
1943 <rasd:Description>USB Controller</rasd:Description>
1944 <rasd:InstanceId>3</rasd:InstanceId>
1945 <rasd:ResourceType>23</rasd:ResourceType>
1946 <rasd:Address>0</rasd:Address>
1947 <rasd:BusNumber>0</rasd:BusNumber>
1948 </Item> */
1949 if (uLoop == 1)
1950 {
1951 strDescription = "USB Controller";
1952 strCaption = "usb";
1953 type = ovf::ResourceType_USBController; // 23
1954 lAddress = 0; // this is what OVFTool writes
1955 lBusNumber = 0; // this is what OVFTool writes
1956 }
1957 break;
1958
1959 case VirtualSystemDescriptionType_SoundCard:
1960 /* <Item ovf:required="false">
1961 <rasd:Caption>sound</rasd:Caption>
1962 <rasd:Description>Sound Card</rasd:Description>
1963 <rasd:InstanceId>10</rasd:InstanceId>
1964 <rasd:ResourceType>35</rasd:ResourceType>
1965 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1966 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1967 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1968 </Item> */
1969 if (uLoop == 1)
1970 {
1971 strDescription = "Sound Card";
1972 strCaption = "sound";
1973 type = ovf::ResourceType_SoundCard; // 35
1974 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1975 lAutomaticAllocation = 0;
1976 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1977 }
1978 break;
1979
1980 default: break; /* Shut up MSC. */
1981 }
1982
1983 if (type)
1984 {
1985 xml::ElementNode *pItem;
1986 xml::ElementNode *pItemHelper;
1987 RTCString itemElement;
1988 RTCString itemElementHelper;
1989
1990 if (enFormat == ovf::OVFVersion_2_0)
1991 {
1992 if(uLoop == 2)
1993 {
1994 if (desc.type == VirtualSystemDescriptionType_NetworkAdapter)
1995 {
1996 itemElement = "epasd:";
1997 pItem = pelmVirtualHardwareSection->createChild("EthernetPortItem");
1998 }
1999 else if (desc.type == VirtualSystemDescriptionType_CDROM ||
2000 desc.type == VirtualSystemDescriptionType_HardDiskImage)
2001 {
2002 itemElement = "sasd:";
2003 pItem = pelmVirtualHardwareSection->createChild("StorageItem");
2004 }
2005 else
2006 pItem = NULL;
2007 }
2008 else
2009 {
2010 itemElement = "rasd:";
2011 pItem = pelmVirtualHardwareSection->createChild("Item");
2012 }
2013 }
2014 else
2015 {
2016 itemElement = "rasd:";
2017 pItem = pelmVirtualHardwareSection->createChild("Item");
2018 }
2019
2020 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
2021 // the elements from the rasd: namespace must be sorted by letter, and VMware
2022 // actually requires this as well (see public bug #6612)
2023
2024 if (lAddress != -1)
2025 {
2026 //pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
2027 itemElementHelper = itemElement;
2028 pItemHelper = pItem->createChild(itemElementHelper.append("Address").c_str());
2029 pItemHelper->addContent(Utf8StrFmt("%d", lAddress));
2030 }
2031
2032 if (lAddressOnParent != -1)
2033 {
2034 //pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
2035 itemElementHelper = itemElement;
2036 pItemHelper = pItem->createChild(itemElementHelper.append("AddressOnParent").c_str());
2037 pItemHelper->addContent(Utf8StrFmt("%d", lAddressOnParent));
2038 }
2039
2040 if (!strAllocationUnits.isEmpty())
2041 {
2042 //pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
2043 itemElementHelper = itemElement;
2044 pItemHelper = pItem->createChild(itemElementHelper.append("AllocationUnits").c_str());
2045 pItemHelper->addContent(strAllocationUnits);
2046 }
2047
2048 if (lAutomaticAllocation != -1)
2049 {
2050 //pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
2051 itemElementHelper = itemElement;
2052 pItemHelper = pItem->createChild(itemElementHelper.append("AutomaticAllocation").c_str());
2053 pItemHelper->addContent((lAutomaticAllocation) ? "true" : "false" );
2054 }
2055
2056 if (lBusNumber != -1)
2057 {
2058 if (enFormat == ovf::OVFVersion_0_9)
2059 {
2060 // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool
2061 //pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
2062 itemElementHelper = itemElement;
2063 pItemHelper = pItem->createChild(itemElementHelper.append("BusNumber").c_str());
2064 pItemHelper->addContent(Utf8StrFmt("%d", lBusNumber));
2065 }
2066 }
2067
2068 if (!strCaption.isEmpty())
2069 {
2070 //pItem->createChild("rasd:Caption")->addContent(strCaption);
2071 itemElementHelper = itemElement;
2072 pItemHelper = pItem->createChild(itemElementHelper.append("Caption").c_str());
2073 pItemHelper->addContent(strCaption);
2074 }
2075
2076 if (!strConnection.isEmpty())
2077 {
2078 //pItem->createChild("rasd:Connection")->addContent(strConnection);
2079 itemElementHelper = itemElement;
2080 pItemHelper = pItem->createChild(itemElementHelper.append("Connection").c_str());
2081 pItemHelper->addContent(strConnection);
2082 }
2083
2084 if (!strDescription.isEmpty())
2085 {
2086 //pItem->createChild("rasd:Description")->addContent(strDescription);
2087 itemElementHelper = itemElement;
2088 pItemHelper = pItem->createChild(itemElementHelper.append("Description").c_str());
2089 pItemHelper->addContent(strDescription);
2090 }
2091
2092 if (!strCaption.isEmpty())
2093 {
2094 if (enFormat == ovf::OVFVersion_1_0)
2095 {
2096 //pItem->createChild("rasd:ElementName")->addContent(strCaption);
2097 itemElementHelper = itemElement;
2098 pItemHelper = pItem->createChild(itemElementHelper.append("ElementName").c_str());
2099 pItemHelper->addContent(strCaption);
2100 }
2101 }
2102
2103 if (!strHostResource.isEmpty())
2104 {
2105 //pItem->createChild("rasd:HostResource")->addContent(strHostResource);
2106 itemElementHelper = itemElement;
2107 pItemHelper = pItem->createChild(itemElementHelper.append("HostResource").c_str());
2108 pItemHelper->addContent(strHostResource);
2109 }
2110
2111 {
2112 // <rasd:InstanceID>1</rasd:InstanceID>
2113 itemElementHelper = itemElement;
2114 if (enFormat == ovf::OVFVersion_0_9)
2115 //pelmInstanceID = pItem->createChild("rasd:InstanceId");
2116 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceId").c_str());
2117 else
2118 //pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
2119 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceID").c_str());
2120
2121 pItemHelper->addContent(Utf8StrFmt("%d", ulInstanceID++));
2122 }
2123
2124 if (ulParent)
2125 {
2126 //pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
2127 itemElementHelper = itemElement;
2128 pItemHelper = pItem->createChild(itemElementHelper.append("Parent").c_str());
2129 pItemHelper->addContent(Utf8StrFmt("%d", ulParent));
2130 }
2131
2132 if (!strResourceSubType.isEmpty())
2133 {
2134 //pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
2135 itemElementHelper = itemElement;
2136 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceSubType").c_str());
2137 pItemHelper->addContent(strResourceSubType);
2138 }
2139
2140 {
2141 // <rasd:ResourceType>3</rasd:ResourceType>
2142 //pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
2143 itemElementHelper = itemElement;
2144 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceType").c_str());
2145 pItemHelper->addContent(Utf8StrFmt("%d", type));
2146 }
2147
2148 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2149 if (lVirtualQuantity != -1)
2150 {
2151 //pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2152 itemElementHelper = itemElement;
2153 pItemHelper = pItem->createChild(itemElementHelper.append("VirtualQuantity").c_str());
2154 pItemHelper->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2155 }
2156 }
2157 }
2158 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
2159
2160 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
2161 // under the vbox: namespace
2162 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
2163 // ovf:required="false" tells other OVF parsers that they can ignore this thing
2164 pelmVBoxMachine->setAttribute("ovf:required", "false");
2165 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
2166 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
2167
2168 // create an empty machine config
2169 // use the same settings version as the current VM settings file
2170 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(&vsdescThis->m->pMachine->i_getSettingsFileFull());
2171
2172 writeLock.release();
2173 try
2174 {
2175 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
2176 // fill the machine config
2177 vsdescThis->m->pMachine->i_copyMachineDataToSettings(*pConfig);
2178 pConfig->machineUserData.strName = strVMName;
2179
2180 // Apply export tweaks to machine settings
2181 bool fStripAllMACs = m->optListExport.contains(ExportOptions_StripAllMACs);
2182 bool fStripAllNonNATMACs = m->optListExport.contains(ExportOptions_StripAllNonNATMACs);
2183 if (fStripAllMACs || fStripAllNonNATMACs)
2184 {
2185 for (settings::NetworkAdaptersList::iterator
2186 it = pConfig->hardwareMachine.llNetworkAdapters.begin();
2187 it != pConfig->hardwareMachine.llNetworkAdapters.end();
2188 ++it)
2189 {
2190 settings::NetworkAdapter &nic = *it;
2191 if (fStripAllMACs || (fStripAllNonNATMACs && nic.mode != NetworkAttachmentType_NAT))
2192 nic.strMACAddress.setNull();
2193 }
2194 }
2195
2196 // write the machine config to the vbox:Machine element
2197 pConfig->buildMachineXML(*pelmVBoxMachine,
2198 settings::MachineConfigFile::BuildMachineXML_WriteVBoxVersionAttribute
2199 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
2200 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
2201 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
2202 pllElementsWithUuidAttributes);
2203 delete pConfig;
2204 }
2205 catch (...)
2206 {
2207 writeLock.acquire();
2208 delete pConfig;
2209 throw;
2210 }
2211 writeLock.acquire();
2212}
2213
2214/**
2215 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
2216 * and therefore runs on the OVF/OVA write worker thread.
2217 *
2218 * This runs in one context:
2219 *
2220 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl();
2221 *
2222 * @param pTask
2223 * @return
2224 */
2225HRESULT Appliance::i_writeFS(TaskOVF *pTask)
2226{
2227 LogFlowFuncEnter();
2228 LogFlowFunc(("ENTER appliance %p\n", this));
2229
2230 AutoCaller autoCaller(this);
2231 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
2232
2233 HRESULT hrc = S_OK;
2234
2235 // Lock the media tree early to make sure nobody else tries to make changes
2236 // to the tree. Also lock the IAppliance object for writing.
2237 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
2238 // Additional protect the IAppliance object, cause we leave the lock
2239 // when starting the disk export and we don't won't block other
2240 // callers on this lengthy operations.
2241 m->state = ApplianceExporting;
2242
2243 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
2244 hrc = i_writeFSOVF(pTask, multiLock);
2245 else
2246 hrc = i_writeFSOVA(pTask, multiLock);
2247
2248 // reset the state so others can call methods again
2249 m->state = ApplianceIdle;
2250
2251 LogFlowFunc(("hrc=%Rhrc\n", hrc));
2252 LogFlowFuncLeave();
2253 return hrc;
2254}
2255
2256HRESULT Appliance::i_writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
2257{
2258 LogFlowFuncEnter();
2259
2260 /*
2261 * Create write-to-dir file system stream for the target directory.
2262 * This unifies the disk access with the TAR based OVA variant.
2263 */
2264 HRESULT hrc;
2265 int vrc;
2266 RTVFSFSSTREAM hVfsFss2Dir = NIL_RTVFSFSSTREAM;
2267 try
2268 {
2269 Utf8Str strTargetDir(pTask->locInfo.strPath);
2270 strTargetDir.stripFilename();
2271 vrc = RTVfsFsStrmToNormalDir(strTargetDir.c_str(), 0 /*fFlags*/, &hVfsFss2Dir);
2272 if (RT_SUCCESS(vrc))
2273 hrc = S_OK;
2274 else
2275 hrc = setErrorVrc(vrc, tr("Failed to open directory '%s' (%Rrc)"), strTargetDir.c_str(), vrc);
2276 }
2277 catch (std::bad_alloc &)
2278 {
2279 hrc = E_OUTOFMEMORY;
2280 }
2281 if (SUCCEEDED(hrc))
2282 {
2283 /*
2284 * Join i_writeFSOVA. On failure, delete (undo) anything we might
2285 * have written to the disk before failing.
2286 */
2287 hrc = i_writeFSImpl(pTask, writeLock, hVfsFss2Dir);
2288 if (FAILED(hrc))
2289 RTVfsFsStrmToDirUndo(hVfsFss2Dir);
2290 RTVfsFsStrmRelease(hVfsFss2Dir);
2291 }
2292
2293 LogFlowFuncLeave();
2294 return hrc;
2295}
2296
2297HRESULT Appliance::i_writeFSOVA(TaskOVF *pTask, AutoWriteLockBase &writeLock)
2298{
2299 LogFlowFuncEnter();
2300
2301 /*
2302 * Open the output file and attach a TAR creator to it.
2303 * The OVF 1.1.0 spec specifies the TAR format to be compatible with USTAR
2304 * according to POSIX 1003.1-2008. We use the 1988 spec here as it's the
2305 * only variant we currently implement.
2306 */
2307 HRESULT hrc;
2308 RTVFSIOSTREAM hVfsIosTar;
2309 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
2310 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2311 &hVfsIosTar);
2312 if (RT_SUCCESS(vrc))
2313 {
2314 RTVFSFSSTREAM hVfsFssTar;
2315 vrc = RTZipTarFsStreamToIoStream(hVfsIosTar, RTZIPTARFORMAT_USTAR, 0 /*fFlags*/, &hVfsFssTar);
2316 RTVfsIoStrmRelease(hVfsIosTar);
2317 if (RT_SUCCESS(vrc))
2318 {
2319 RTZipTarFsStreamSetFileMode(hVfsFssTar, 0660, 0440);
2320 RTZipTarFsStreamSetOwner(hVfsFssTar, VBOX_VERSION_MAJOR,
2321 pTask->enFormat == ovf::OVFVersion_0_9 ? "vboxovf09"
2322 : pTask->enFormat == ovf::OVFVersion_1_0 ? "vboxovf10"
2323 : pTask->enFormat == ovf::OVFVersion_2_0 ? "vboxovf20"
2324 : "vboxovf");
2325 RTZipTarFsStreamSetGroup(hVfsFssTar, VBOX_VERSION_MINOR,
2326 Utf8StrFmt("vbox_v" RT_XSTR(VBOX_VERSION_MAJOR) "." RT_XSTR(VBOX_VERSION_MINOR) "."
2327 RT_XSTR(VBOX_VERSION_BUILD) "r%RU32", RTBldCfgRevision()).c_str());
2328
2329 hrc = i_writeFSImpl(pTask, writeLock, hVfsFssTar);
2330 RTVfsFsStrmRelease(hVfsFssTar);
2331 }
2332 else
2333 hrc = setErrorVrc(vrc, tr("Failed create TAR creator for '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2334
2335 /* Delete the OVA on failure. */
2336 if (FAILED(hrc))
2337 RTFileDelete(pTask->locInfo.strPath.c_str());
2338 }
2339 else
2340 hrc = setErrorVrc(vrc, tr("Failed to open '%s' for writing (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2341
2342 LogFlowFuncLeave();
2343 return hrc;
2344}
2345
2346/**
2347 * Upload the image to the OCI Storage service, next import the
2348 * uploaded image into internal OCI image format and launch an
2349 * instance with this image in the OCI Compute service.
2350 */
2351HRESULT Appliance::i_exportCloudImpl(TaskCloud *pTask)
2352{
2353 LogFlowFuncEnter();
2354
2355 HRESULT hrc = S_OK;
2356 ComPtr<ICloudProviderManager> cpm;
2357 hrc = mVirtualBox->COMGETTER(CloudProviderManager)(cpm.asOutParam());
2358 if (FAILED(hrc))
2359 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud provider manager object wasn't found"), __FUNCTION__);
2360
2361 Utf8Str strProviderName = pTask->locInfo.strProvider;
2362 ComPtr<ICloudProvider> cloudProvider;
2363 ComPtr<ICloudProfile> cloudProfile;
2364 hrc = cpm->GetProviderByShortName(Bstr(strProviderName.c_str()).raw(), cloudProvider.asOutParam());
2365
2366 if (FAILED(hrc))
2367 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud provider object wasn't found"), __FUNCTION__);
2368
2369 ComPtr<IVirtualSystemDescription> vsd = m->virtualSystemDescriptions.front();
2370
2371 com::SafeArray<VirtualSystemDescriptionType_T> retTypes;
2372 com::SafeArray<BSTR> aRefs;
2373 com::SafeArray<BSTR> aOvfValues;
2374 com::SafeArray<BSTR> aVBoxValues;
2375 com::SafeArray<BSTR> aExtraConfigValues;
2376
2377 hrc = vsd->GetDescriptionByType(VirtualSystemDescriptionType_CloudProfileName,
2378 ComSafeArrayAsOutParam(retTypes),
2379 ComSafeArrayAsOutParam(aRefs),
2380 ComSafeArrayAsOutParam(aOvfValues),
2381 ComSafeArrayAsOutParam(aVBoxValues),
2382 ComSafeArrayAsOutParam(aExtraConfigValues));
2383 if (FAILED(hrc))
2384 return hrc;
2385
2386 Utf8Str profileName(aVBoxValues[0]);
2387 if (profileName.isEmpty())
2388 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud user profile name wasn't found"), __FUNCTION__);
2389
2390 hrc = cloudProvider->GetProfileByName(aVBoxValues[0], cloudProfile.asOutParam());
2391 if (FAILED(hrc))
2392 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud profile object wasn't found"), __FUNCTION__);
2393
2394 ComObjPtr<ICloudClient> cloudClient;
2395 hrc = cloudProfile->CreateCloudClient(cloudClient.asOutParam());
2396 if (FAILED(hrc))
2397 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud client object wasn't found"), __FUNCTION__);
2398
2399 if (m->virtualSystemDescriptions.size() == 1)
2400 {
2401 ComPtr<IVirtualBox> VBox(mVirtualBox);
2402 hrc = cloudClient->ExportVM(m->virtualSystemDescriptions.front(), pTask->pProgress);
2403 }
2404 else
2405 hrc = setErrorVrc(VERR_MISMATCH, tr("Export to Cloud isn't supported for more than one VM instance."));
2406
2407 LogFlowFuncLeave();
2408 return hrc;
2409}
2410
2411
2412/**
2413 * Writes the Oracle Public Cloud appliance.
2414 *
2415 * It expect raw disk images inside a gzipped tarball. We enable sparse files
2416 * to save diskspace on the target host system.
2417 */
2418HRESULT Appliance::i_writeFSOPC(TaskOPC *pTask)
2419{
2420 LogFlowFuncEnter();
2421 HRESULT hrc = S_OK;
2422
2423 // Lock the media tree early to make sure nobody else tries to make changes
2424 // to the tree. Also lock the IAppliance object for writing.
2425 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
2426 // Additional protect the IAppliance object, cause we leave the lock
2427 // when starting the disk export and we don't won't block other
2428 // callers on this lengthy operations.
2429 m->state = ApplianceExporting;
2430
2431 /*
2432 * We're duplicating parts of i_writeFSImpl here because that's simpler
2433 * and creates less spaghetti code.
2434 */
2435 std::list<Utf8Str> lstTarballs;
2436
2437 /*
2438 * Use i_buildXML to build a stack of disk images. We don't care about the XML doc here.
2439 */
2440 XMLStack stack;
2441 {
2442 xml::Document doc;
2443 i_buildXML(multiLock, doc, stack, pTask->locInfo.strPath, ovf::OVFVersion_2_0);
2444 }
2445
2446 /*
2447 * Process the disk images.
2448 */
2449 unsigned cTarballs = 0;
2450 for (list<Utf8Str>::const_iterator it = stack.mapDiskSequence.begin();
2451 it != stack.mapDiskSequence.end();
2452 ++it)
2453 {
2454 const Utf8Str &strDiskID = *it;
2455 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2456 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent; // where the VBox image is
2457
2458 /*
2459 * Some skipping.
2460 */
2461 if (pDiskEntry->skipIt)
2462 continue;
2463
2464 /* Skip empty media (DVD-ROM, floppy). */
2465 if (strSrcFilePath.isEmpty())
2466 continue;
2467
2468 /* Only deal with harddisk and DVD-ROMs, skip any floppies for now. */
2469 if ( pDiskEntry->type != VirtualSystemDescriptionType_HardDiskImage
2470 && pDiskEntry->type != VirtualSystemDescriptionType_CDROM)
2471 continue;
2472
2473 /*
2474 * Locate the Medium object for this entry (by location/path).
2475 */
2476 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2477 ComObjPtr<Medium> ptrSourceDisk;
2478 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2479 hrc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true /*aSetError*/, &ptrSourceDisk);
2480 else
2481 hrc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD, NULL /*aId*/, strSrcFilePath,
2482 true /*aSetError*/, &ptrSourceDisk);
2483 if (FAILED(hrc))
2484 break;
2485 if (strSrcFilePath.isEmpty())
2486 continue;
2487
2488 /*
2489 * Figure out the names.
2490 */
2491
2492 /* The name inside the tarball. Replace the suffix of harddisk images with ".img". */
2493 Utf8Str strInsideName = pDiskEntry->strOvf;
2494 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2495 strInsideName.stripSuffix().append(".img");
2496
2497 /* The first tarball we create uses the specified name. Subsequent
2498 takes the name from the disk entry or something. */
2499 Utf8Str strTarballPath = pTask->locInfo.strPath;
2500 if (cTarballs > 0)
2501 {
2502 strTarballPath.stripFilename().append(RTPATH_SLASH_STR).append(pDiskEntry->strOvf);
2503 const char *pszExt = RTPathSuffix(pDiskEntry->strOvf.c_str());
2504 if (pszExt && pszExt[0] == '.' && pszExt[1] != '\0')
2505 {
2506 strTarballPath.stripSuffix();
2507 if (pDiskEntry->type != VirtualSystemDescriptionType_HardDiskImage)
2508 strTarballPath.append("_").append(&pszExt[1]);
2509 }
2510 strTarballPath.append(".tar.gz");
2511 }
2512 cTarballs++;
2513
2514 /*
2515 * Create the tar output stream.
2516 */
2517 RTVFSIOSTREAM hVfsIosFile;
2518 int vrc = RTVfsIoStrmOpenNormal(strTarballPath.c_str(),
2519 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2520 &hVfsIosFile);
2521 if (RT_SUCCESS(vrc))
2522 {
2523 RTVFSIOSTREAM hVfsIosGzip = NIL_RTVFSIOSTREAM;
2524 vrc = RTZipGzipCompressIoStream(hVfsIosFile, 0 /*fFlags*/, 6 /*uLevel*/, &hVfsIosGzip);
2525 RTVfsIoStrmRelease(hVfsIosFile);
2526
2527 /** @todo insert I/O thread here between gzip and the tar creator. Needs
2528 * implementing. */
2529
2530 RTVFSFSSTREAM hVfsFssTar = NIL_RTVFSFSSTREAM;
2531 if (RT_SUCCESS(vrc))
2532 vrc = RTZipTarFsStreamToIoStream(hVfsIosGzip, RTZIPTARFORMAT_GNU, RTZIPTAR_C_SPARSE, &hVfsFssTar);
2533 RTVfsIoStrmRelease(hVfsIosGzip);
2534 if (RT_SUCCESS(vrc))
2535 {
2536 RTZipTarFsStreamSetFileMode(hVfsFssTar, 0660, 0440);
2537 RTZipTarFsStreamSetOwner(hVfsFssTar, VBOX_VERSION_MAJOR, "vboxopc10");
2538 RTZipTarFsStreamSetGroup(hVfsFssTar, VBOX_VERSION_MINOR,
2539 Utf8StrFmt("vbox_v" RT_XSTR(VBOX_VERSION_MAJOR) "." RT_XSTR(VBOX_VERSION_MINOR) "."
2540 RT_XSTR(VBOX_VERSION_BUILD) "r%RU32", RTBldCfgRevision()).c_str());
2541
2542 /*
2543 * Let the Medium code do the heavy work.
2544 *
2545 * The exporting requests a lock on the media tree. So temporarily
2546 * leave the appliance lock.
2547 */
2548 multiLock.release();
2549
2550 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%Rbn'"), strTarballPath.c_str()).raw(),
2551 pDiskEntry->ulSizeMB); // operation's weight, as set up
2552 // with the IProgress originally
2553 hrc = ptrSourceDisk->i_addRawToFss(strInsideName.c_str(), m->m_pSecretKeyStore, hVfsFssTar,
2554 pTask->pProgress, true /*fSparse*/);
2555
2556 multiLock.acquire();
2557 if (SUCCEEDED(hrc))
2558 {
2559 /*
2560 * Complete and close the tarball.
2561 */
2562 vrc = RTVfsFsStrmEnd(hVfsFssTar);
2563 RTVfsFsStrmRelease(hVfsFssTar);
2564 hVfsFssTar = NIL_RTVFSFSSTREAM;
2565 if (RT_SUCCESS(vrc))
2566 {
2567 /* Remember the tarball name for cleanup. */
2568 try
2569 {
2570 lstTarballs.push_back(strTarballPath.c_str());
2571 strTarballPath.setNull();
2572 }
2573 catch (std::bad_alloc &)
2574 { hrc = E_OUTOFMEMORY; }
2575 }
2576 else
2577 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc,
2578 tr("Error completing TAR file '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2579 }
2580 }
2581 else
2582 hrc = setErrorVrc(vrc, tr("Failed to TAR creator instance for '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2583
2584 if (FAILED(hrc) && strTarballPath.isNotEmpty())
2585 RTFileDelete(strTarballPath.c_str());
2586 }
2587 else
2588 hrc = setErrorVrc(vrc, tr("Failed to create '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2589 if (FAILED(hrc))
2590 break;
2591 }
2592
2593 /*
2594 * Delete output files on failure.
2595 */
2596 if (FAILED(hrc))
2597 for (list<Utf8Str>::const_iterator it = lstTarballs.begin(); it != lstTarballs.end(); ++it)
2598 RTFileDelete(it->c_str());
2599
2600 // reset the state so others can call methods again
2601 m->state = ApplianceIdle;
2602
2603 LogFlowFuncLeave();
2604 return hrc;
2605
2606}
2607
2608HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase &writeLock, RTVFSFSSTREAM hVfsFssDst)
2609{
2610 LogFlowFuncEnter();
2611
2612 HRESULT hrc = S_OK;
2613 int vrc;
2614 try
2615 {
2616 // the XML stack contains two maps for disks and networks, which allows us to
2617 // a) have a list of unique disk names (to make sure the same disk name is only added once)
2618 // and b) keep a list of all networks
2619 XMLStack stack;
2620 // Scope this to free the memory as soon as this is finished
2621 {
2622 /* Construct the OVF name. */
2623 Utf8Str strOvfFile(pTask->locInfo.strPath);
2624 strOvfFile.stripPath().stripSuffix().append(".ovf");
2625
2626 /* Render a valid ovf document into a memory buffer. The unknown
2627 version upgrade relates to the OPC hack up in Appliance::write(). */
2628 xml::Document doc;
2629 i_buildXML(writeLock, doc, stack, pTask->locInfo.strPath,
2630 pTask->enFormat != ovf::OVFVersion_unknown ? pTask->enFormat : ovf::OVFVersion_2_0);
2631
2632 void *pvBuf = NULL;
2633 size_t cbSize = 0;
2634 xml::XmlMemWriter writer;
2635 writer.write(doc, &pvBuf, &cbSize);
2636 if (RT_UNLIKELY(!pvBuf))
2637 throw setError(VBOX_E_FILE_ERROR, tr("Could not create OVF file '%s'"), strOvfFile.c_str());
2638
2639 /* Write the ovf file to "disk". */
2640 hrc = i_writeBufferToFile(hVfsFssDst, strOvfFile.c_str(), pvBuf, cbSize);
2641 if (FAILED(hrc))
2642 throw hrc;
2643 }
2644
2645 // We need a proper format description
2646 ComObjPtr<MediumFormat> formatTemp;
2647
2648 ComObjPtr<MediumFormat> format;
2649 // Scope for the AutoReadLock
2650 {
2651 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2652 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2653 // We are always exporting to VMDK stream optimized for now
2654 formatTemp = pSysProps->i_mediumFormatFromExtension("iso");
2655
2656 format = pSysProps->i_mediumFormat("VMDK");
2657 if (format.isNull())
2658 throw setError(VBOX_E_NOT_SUPPORTED,
2659 tr("Invalid medium storage format"));
2660 }
2661
2662 // Finally, write out the disks!
2663 //use the list stack.mapDiskSequence where the disks were put as the "VirtualSystem"s had been placed
2664 //in the OVF description file. I.e. we have one "VirtualSystem" in the OVF file, we extract all disks
2665 //attached to it. And these disks are stored in the stack.mapDiskSequence. Next we shift to the next
2666 //"VirtualSystem" and repeat the operation.
2667 //And here we go through the list and extract all disks in the same sequence
2668 for (list<Utf8Str>::const_iterator
2669 it = stack.mapDiskSequence.begin();
2670 it != stack.mapDiskSequence.end();
2671 ++it)
2672 {
2673 const Utf8Str &strDiskID = *it;
2674 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2675
2676 // source path: where the VBox image is
2677 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
2678
2679 //skip empty Medium. In common, It's may be empty CD/DVD
2680 if (strSrcFilePath.isEmpty() ||
2681 pDiskEntry->skipIt == true)
2682 continue;
2683
2684 // Do NOT check here whether the file exists. findHardDisk will
2685 // figure that out, and filesystem-based tests are simply wrong
2686 // in the general case (think of iSCSI).
2687
2688 // clone the disk:
2689 ComObjPtr<Medium> pSourceDisk;
2690
2691 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2692
2693 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2694 {
2695 hrc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2696 if (FAILED(hrc)) throw hrc;
2697 }
2698 else//may be CD or DVD
2699 {
2700 hrc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD,
2701 NULL,
2702 strSrcFilePath,
2703 true,
2704 &pSourceDisk);
2705 if (FAILED(hrc)) throw hrc;
2706 }
2707
2708 Bstr uuidSource;
2709 hrc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2710 if (FAILED(hrc)) throw hrc;
2711 Guid guidSource(uuidSource);
2712
2713 // output filename
2714 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2715
2716 // target path needs to be composed from where the output OVF is
2717 const Utf8Str &strTargetFilePath = strTargetFileNameOnly;
2718
2719 // The exporting requests a lock on the media tree. So leave our lock temporary.
2720 writeLock.release();
2721 try
2722 {
2723 // advance to the next operation
2724 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"),
2725 RTPathFilename(strTargetFilePath.c_str())).raw(),
2726 pDiskEntry->ulSizeMB); // operation's weight, as set up
2727 // with the IProgress originally
2728
2729 // create a flat copy of the source disk image
2730 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2731 {
2732 /*
2733 * Export a disk image.
2734 */
2735 /* For compressed VMDK fun, we let i_exportFile produce the image bytes. */
2736 RTVFSIOSTREAM hVfsIosDst;
2737 vrc = RTVfsFsStrmPushFile(hVfsFssDst, strTargetFilePath.c_str(), UINT64_MAX,
2738 NULL /*paObjInfo*/, 0 /*cObjInfo*/, RTVFSFSSTRM_PUSH_F_STREAM, &hVfsIosDst);
2739 if (RT_FAILURE(vrc))
2740 throw setErrorVrc(vrc, tr("RTVfsFsStrmPushFile failed for '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2741 hVfsIosDst = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosDst, strTargetFilePath.c_str(),
2742 false /*fRead*/);
2743 if (hVfsIosDst == NIL_RTVFSIOSTREAM)
2744 throw setError(E_FAIL, "i_manifestSetupDigestCalculationForGivenIoStream(%s)", strTargetFilePath.c_str());
2745
2746 hrc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2747 format,
2748 MediumVariant_VmdkStreamOptimized,
2749 m->m_pSecretKeyStore,
2750 hVfsIosDst,
2751 pTask->pProgress);
2752 RTVfsIoStrmRelease(hVfsIosDst);
2753 }
2754 else
2755 {
2756 /*
2757 * Copy CD/DVD/floppy image.
2758 */
2759 Assert(pDiskEntry->type == VirtualSystemDescriptionType_CDROM);
2760 hrc = pSourceDisk->i_addRawToFss(strTargetFilePath.c_str(), m->m_pSecretKeyStore, hVfsFssDst,
2761 pTask->pProgress, false /*fSparse*/);
2762 }
2763 if (FAILED(hrc)) throw hrc;
2764 }
2765 catch (HRESULT rc3)
2766 {
2767 writeLock.acquire();
2768 /// @todo file deletion on error? If not, we can remove that whole try/catch block.
2769 throw rc3;
2770 }
2771 // Finished, lock again (so nobody mess around with the medium tree
2772 // in the meantime)
2773 writeLock.acquire();
2774 }
2775
2776 if (m->fManifest)
2777 {
2778 // Create & write the manifest file
2779 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
2780 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2781 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2782 m->ulWeightForManifestOperation); // operation's weight, as set up
2783 // with the IProgress originally);
2784 /* Create a memory I/O stream and write the manifest to it. */
2785 RTVFSIOSTREAM hVfsIosManifest;
2786 vrc = RTVfsMemIoStrmCreate(NIL_RTVFSIOSTREAM, _1K, &hVfsIosManifest);
2787 if (RT_FAILURE(vrc))
2788 throw setErrorVrc(vrc, tr("RTVfsMemIoStrmCreate failed (%Rrc)"), vrc);
2789 if (m->hOurManifest != NIL_RTMANIFEST) /* In case it's empty. */
2790 vrc = RTManifestWriteStandard(m->hOurManifest, hVfsIosManifest);
2791 if (RT_SUCCESS(vrc))
2792 {
2793 /* Rewind the stream and add it to the output. */
2794 size_t cbIgnored;
2795 vrc = RTVfsIoStrmReadAt(hVfsIosManifest, 0 /*offset*/, &cbIgnored, 0, true /*fBlocking*/, &cbIgnored);
2796 if (RT_SUCCESS(vrc))
2797 {
2798 RTVFSOBJ hVfsObjManifest = RTVfsObjFromIoStream(hVfsIosManifest);
2799 vrc = RTVfsFsStrmAdd(hVfsFssDst, strMfFileName.c_str(), hVfsObjManifest, 0 /*fFlags*/);
2800 if (RT_SUCCESS(vrc))
2801 hrc = S_OK;
2802 else
2803 hrc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for the manifest (%Rrc)"), vrc);
2804 }
2805 else
2806 hrc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2807 }
2808 else
2809 hrc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2810 RTVfsIoStrmRelease(hVfsIosManifest);
2811 if (FAILED(hrc))
2812 throw hrc;
2813 }
2814 }
2815 catch (RTCError &x) // includes all XML exceptions
2816 {
2817 hrc = setError(VBOX_E_FILE_ERROR, x.what());
2818 }
2819 catch (HRESULT hrcXcpt)
2820 {
2821 hrc = hrcXcpt;
2822 }
2823
2824 LogFlowFunc(("hrc=%Rhrc\n", hrc));
2825 LogFlowFuncLeave();
2826
2827 return hrc;
2828}
2829
2830
2831/**
2832 * Writes a memory buffer to a file in the output file system stream.
2833 *
2834 * @returns COM status code.
2835 * @param hVfsFssDst The file system stream to add the file to.
2836 * @param pszFilename The file name (w/ path if desired).
2837 * @param pvContent Pointer to buffer containing the file content.
2838 * @param cbContent Size of the content.
2839 */
2840HRESULT Appliance::i_writeBufferToFile(RTVFSFSSTREAM hVfsFssDst, const char *pszFilename, const void *pvContent, size_t cbContent)
2841{
2842 /*
2843 * Create a VFS file around the memory, converting it to a base VFS object handle.
2844 */
2845 HRESULT hrc;
2846 RTVFSIOSTREAM hVfsIosSrc;
2847 int vrc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pvContent, cbContent, &hVfsIosSrc);
2848 if (RT_SUCCESS(vrc))
2849 {
2850 hVfsIosSrc = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosSrc, pszFilename);
2851 AssertReturn(hVfsIosSrc != NIL_RTVFSIOSTREAM,
2852 setErrorVrc(vrc, "i_manifestSetupDigestCalculationForGivenIoStream"));
2853
2854 RTVFSOBJ hVfsObj = RTVfsObjFromIoStream(hVfsIosSrc);
2855 RTVfsIoStrmRelease(hVfsIosSrc);
2856 AssertReturn(hVfsObj != NIL_RTVFSOBJ, E_FAIL);
2857
2858 /*
2859 * Add it to the stream.
2860 */
2861 vrc = RTVfsFsStrmAdd(hVfsFssDst, pszFilename, hVfsObj, 0);
2862 RTVfsObjRelease(hVfsObj);
2863 if (RT_SUCCESS(vrc))
2864 hrc = S_OK;
2865 else
2866 hrc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for '%s' (%Rrc)"), pszFilename, vrc);
2867 }
2868 else
2869 hrc = setErrorVrc(vrc, "RTVfsIoStrmFromBuffer");
2870 return hrc;
2871}
2872
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