VirtualBox

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

Last change on this file since 67254 was 67254, checked in by vboxsync, 7 years ago

Main/ApplianceExport: Set special user and group names and IDs in the TAR output so the vbox version can be easily identified. Also normalize the file mode mask in the TAR output a little. Hope no OVF/OPC reader are offended by this...

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