VirtualBox

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

Last change on this file since 107438 was 107298, checked in by vboxsync, 5 weeks ago

Main/Appliance: Within IMachine::exportTo() only call IPlatform::getX86()
and IPlatformX86::getCPUProperty() if the VM being exported contains an
x86 CPU.

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