VirtualBox

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

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

Main: Don't use Logging.h.

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