VirtualBox

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

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

bugref:9152. divided the OCI/OPC/OVF tasks into the separate threads.

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

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