VirtualBox

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

Last change on this file since 86115 was 85364, checked in by vboxsync, 4 years ago

Main/Appliance: remove #include which currently causes some dependency trouble (but shouldn't - either way, it's good to avoid rebuild of many files, just because the subversion revison number has changed)

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