VirtualBox

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

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

bugref:9242. "OCI" part was removed from VirtualSystemDescriptionType except CloudOCIVCN and CloudOCISubnet because they are OCI specific.

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