VirtualBox

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

Last change on this file since 75267 was 75038, checked in by vboxsync, 6 years ago

OCI: G/c VBOX_WITH_CLOUD_PROVIDERS_NO_COMMANDS ifdefs and related code.

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