VirtualBox

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

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

OCI: Fix EOL accident.

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

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