VirtualBox

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

Last change on this file since 103131 was 101472, checked in by vboxsync, 12 months ago

FE/VBoxManage,FE/Qt,Main/{VirtualBox.xidl,Appliance}: Add the ability to
export and import VMs which contain an NVMe storage controller.
bugref:10159 ticketref:19320

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

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