VirtualBox

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

Last change on this file since 86648 was 86648, checked in by vboxsync, 5 years ago

bugref:9781. Added the placeholder @@VBOX_COND_GUEST_VERSION[>(required version)]@@. Updated the templates. Removed the obsolete function getGuestOSConditional().

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

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