VirtualBox

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

Last change on this file since 98307 was 98307, checked in by vboxsync, 2 years ago

Runtime/RTS3: Retire unused implementation, can be resurrected if required

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

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