VirtualBox

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

Last change on this file since 45600 was 45600, checked in by vboxsync, 12 years ago

ApplianceImplExport.cpp: Added check for pAudioAdapter->COMGETTER(Enabled) result. Removed unused Bstr variables (confusing). Moved variables to where they are used.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 90.5 KB
Line 
1/* $Id: ApplianceImplExport.cpp 45600 2013-04-18 09:58:31Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2013 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19#include <iprt/path.h>
20#include <iprt/dir.h>
21#include <iprt/param.h>
22#include <iprt/s3.h>
23#include <iprt/manifest.h>
24#include <iprt/tar.h>
25#include <iprt/stream.h>
26
27#include <VBox/version.h>
28
29#include "ApplianceImpl.h"
30#include "VirtualBoxImpl.h"
31
32#include "ProgressImpl.h"
33#include "MachineImpl.h"
34#include "MediumImpl.h"
35#include "MediumFormatImpl.h"
36#include "Global.h"
37#include "SystemPropertiesImpl.h"
38
39#include "AutoCaller.h"
40#include "Logging.h"
41
42#include "ApplianceImplPrivate.h"
43
44using namespace std;
45
46////////////////////////////////////////////////////////////////////////////////
47//
48// IMachine public methods
49//
50////////////////////////////////////////////////////////////////////////////////
51
52// This code is here so we won't have to include the appliance headers in the
53// IMachine implementation, and we also need to access private appliance data.
54
55/**
56* Public method implementation.
57* @param appliance
58* @return
59*/
60STDMETHODIMP Machine::ExportTo(IAppliance *aAppliance, IN_BSTR location, IVirtualSystemDescription **aDescription)
61{
62 HRESULT rc = S_OK;
63
64 if (!aAppliance)
65 return E_POINTER;
66
67 AutoCaller autoCaller(this);
68 if (FAILED(autoCaller.rc())) return autoCaller.rc();
69
70 ComObjPtr<VirtualSystemDescription> pNewDesc;
71
72 try
73 {
74 Appliance *pAppliance = static_cast<Appliance*>(aAppliance);
75 AutoCaller autoCaller1(pAppliance);
76 if (FAILED(autoCaller1.rc())) return autoCaller1.rc();
77
78 LocationInfo locInfo;
79 parseURI(location, locInfo);
80 // create a new virtual system to store in the appliance
81 rc = pNewDesc.createObject();
82 if (FAILED(rc)) throw rc;
83 rc = pNewDesc->init();
84 if (FAILED(rc)) throw rc;
85
86 // store the machine object so we can dump the XML in Appliance::Write()
87 pNewDesc->m->pMachine = this;
88
89 // first, call the COM methods, as they request locks
90 ComPtr<IUSBController> pUsbController;
91 rc = COMGETTER(USBController)(pUsbController.asOutParam());
92 BOOL fUSBEnabled;
93 if (FAILED(rc))
94 fUSBEnabled = false;
95 else
96 {
97 rc = pUsbController->COMGETTER(Enabled)(&fUSBEnabled);
98 if (FAILED(rc)) throw rc;
99 }
100
101 // request the machine lock while accessing internal members
102 AutoReadLock alock1(this COMMA_LOCKVAL_SRC_POS);
103
104 ComPtr<IAudioAdapter> pAudioAdapter = mAudioAdapter;
105 BOOL fAudioEnabled;
106 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
107 if (FAILED(rc)) throw rc;
108 AudioControllerType_T audioController;
109 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
110 if (FAILED(rc)) throw rc;
111
112 // get name
113 Utf8Str strVMName = mUserData->s.strName;
114 // get description
115 Utf8Str strDescription = mUserData->s.strDescription;
116 // get guest OS
117 Utf8Str strOsTypeVBox = mUserData->s.strOsType;
118 // CPU count
119 uint32_t cCPUs = mHWData->mCPUCount;
120 // memory size in MB
121 uint32_t ulMemSizeMB = mHWData->mMemorySize;
122 // VRAM size?
123 // BIOS settings?
124 // 3D acceleration enabled?
125 // hardware virtualization enabled?
126 // nested paging enabled?
127 // HWVirtExVPIDEnabled?
128 // PAEEnabled?
129 // snapshotFolder?
130 // VRDPServer?
131
132 /* Guest OS type */
133 ovf::CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str());
134 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
135 "",
136 Utf8StrFmt("%RI32", cim),
137 strOsTypeVBox);
138
139 /* VM name */
140 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
141 "",
142 strVMName,
143 strVMName);
144
145 // description
146 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
147 "",
148 strDescription,
149 strDescription);
150
151 /* CPU count*/
152 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
153 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
154 "",
155 strCpuCount,
156 strCpuCount);
157
158 /* Memory */
159 Utf8Str strMemory = Utf8StrFmt("%RI64", (uint64_t)ulMemSizeMB * _1M);
160 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
161 "",
162 strMemory,
163 strMemory);
164
165 // the one VirtualBox IDE controller has two channels with two ports each, which is
166 // considered two IDE controllers with two ports each by OVF, so export it as two
167 int32_t lIDEControllerPrimaryIndex = 0;
168 int32_t lIDEControllerSecondaryIndex = 0;
169 int32_t lSATAControllerIndex = 0;
170 int32_t lSCSIControllerIndex = 0;
171
172 /* Fetch all available storage controllers */
173 com::SafeIfaceArray<IStorageController> nwControllers;
174 rc = COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(nwControllers));
175 if (FAILED(rc)) throw rc;
176
177 ComPtr<IStorageController> pIDEController;
178 ComPtr<IStorageController> pSATAController;
179 ComPtr<IStorageController> pSCSIController;
180 ComPtr<IStorageController> pSASController;
181 for (size_t j = 0; j < nwControllers.size(); ++j)
182 {
183 StorageBus_T eType;
184 rc = nwControllers[j]->COMGETTER(Bus)(&eType);
185 if (FAILED(rc)) throw rc;
186 if ( eType == StorageBus_IDE
187 && pIDEController.isNull())
188 pIDEController = nwControllers[j];
189 else if ( eType == StorageBus_SATA
190 && pSATAController.isNull())
191 pSATAController = nwControllers[j];
192 else if ( eType == StorageBus_SCSI
193 && pSATAController.isNull())
194 pSCSIController = nwControllers[j];
195 else if ( eType == StorageBus_SAS
196 && pSASController.isNull())
197 pSASController = nwControllers[j];
198 }
199
200// <const name="HardDiskControllerIDE" value="6" />
201 if (!pIDEController.isNull())
202 {
203 Utf8Str strVbox;
204 StorageControllerType_T ctlr;
205 rc = pIDEController->COMGETTER(ControllerType)(&ctlr);
206 if (FAILED(rc)) throw rc;
207 switch(ctlr)
208 {
209 case StorageControllerType_PIIX3: strVbox = "PIIX3"; break;
210 case StorageControllerType_PIIX4: strVbox = "PIIX4"; break;
211 case StorageControllerType_ICH6: strVbox = "ICH6"; break;
212 }
213
214 if (strVbox.length())
215 {
216 lIDEControllerPrimaryIndex = (int32_t)pNewDesc->m->llDescriptions.size();
217 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
218 Utf8StrFmt("%d", lIDEControllerPrimaryIndex), // strRef
219 strVbox, // aOvfValue
220 strVbox); // aVboxValue
221 lIDEControllerSecondaryIndex = lIDEControllerPrimaryIndex + 1;
222 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
223 Utf8StrFmt("%d", lIDEControllerSecondaryIndex),
224 strVbox,
225 strVbox);
226 }
227 }
228
229// <const name="HardDiskControllerSATA" value="7" />
230 if (!pSATAController.isNull())
231 {
232 Utf8Str strVbox = "AHCI";
233 lSATAControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
234 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
235 Utf8StrFmt("%d", lSATAControllerIndex),
236 strVbox,
237 strVbox);
238 }
239
240// <const name="HardDiskControllerSCSI" value="8" />
241 if (!pSCSIController.isNull())
242 {
243 StorageControllerType_T ctlr;
244 rc = pSCSIController->COMGETTER(ControllerType)(&ctlr);
245 if (SUCCEEDED(rc))
246 {
247 Utf8Str strVbox = "LsiLogic"; // the default in VBox
248 switch(ctlr)
249 {
250 case StorageControllerType_LsiLogic: strVbox = "LsiLogic"; break;
251 case StorageControllerType_BusLogic: strVbox = "BusLogic"; break;
252 }
253 lSCSIControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
254 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
255 Utf8StrFmt("%d", lSCSIControllerIndex),
256 strVbox,
257 strVbox);
258 }
259 else
260 throw rc;
261 }
262
263 if (!pSASController.isNull())
264 {
265 // VirtualBox considers the SAS controller a class of its own but in OVF
266 // it should be a SCSI controller
267 Utf8Str strVbox = "LsiLogicSas";
268 lSCSIControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
269 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSAS,
270 Utf8StrFmt("%d", lSCSIControllerIndex),
271 strVbox,
272 strVbox);
273 }
274
275// <const name="HardDiskImage" value="9" />
276// <const name="Floppy" value="18" />
277// <const name="CDROM" value="19" />
278
279 MediaData::AttachmentList::iterator itA;
280 for (itA = mMediaData->mAttachments.begin();
281 itA != mMediaData->mAttachments.end();
282 ++itA)
283 {
284 ComObjPtr<MediumAttachment> pHDA = *itA;
285
286 // the attachment's data
287 ComPtr<IMedium> pMedium;
288 ComPtr<IStorageController> ctl;
289 Bstr controllerName;
290
291 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
292 if (FAILED(rc)) throw rc;
293
294 rc = GetStorageControllerByName(controllerName.raw(), ctl.asOutParam());
295 if (FAILED(rc)) throw rc;
296
297 StorageBus_T storageBus;
298 DeviceType_T deviceType;
299 LONG lChannel;
300 LONG lDevice;
301
302 rc = ctl->COMGETTER(Bus)(&storageBus);
303 if (FAILED(rc)) throw rc;
304
305 rc = pHDA->COMGETTER(Type)(&deviceType);
306 if (FAILED(rc)) throw rc;
307
308 rc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
309 if (FAILED(rc)) throw rc;
310
311 rc = pHDA->COMGETTER(Port)(&lChannel);
312 if (FAILED(rc)) throw rc;
313
314 rc = pHDA->COMGETTER(Device)(&lDevice);
315 if (FAILED(rc)) throw rc;
316
317 Utf8Str strTargetVmdkName;
318 Utf8Str strLocation;
319 LONG64 llSize = 0;
320
321 if ( deviceType == DeviceType_HardDisk
322 && pMedium
323 )
324 {
325 Bstr bstrLocation;
326 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
327 if (FAILED(rc)) throw rc;
328 strLocation = bstrLocation;
329
330 // find the source's base medium for two things:
331 // 1) we'll use its name to determine the name of the target disk, which is readable,
332 // as opposed to the UUID filename of a differencing image, if pMedium is one
333 // 2) we need the size of the base image so we can give it to addEntry(), and later
334 // on export, the progress will be based on that (and not the diff image)
335 ComPtr<IMedium> pBaseMedium;
336 rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
337 // returns pMedium if there are no diff images
338 if (FAILED(rc)) throw rc;
339
340 Bstr bstrBaseName;
341 rc = pBaseMedium->COMGETTER(Name)(bstrBaseName.asOutParam());
342 if (FAILED(rc)) throw rc;
343
344 Utf8Str strTargetName = Utf8Str(locInfo.strPath).stripPath().stripExt();
345 strTargetVmdkName = Utf8StrFmt("%s-disk%d.vmdk", strTargetName.c_str(), ++pAppliance->m->cDisks);
346
347 // force reading state, or else size will be returned as 0
348 MediumState_T ms;
349 rc = pBaseMedium->RefreshState(&ms);
350 if (FAILED(rc)) throw rc;
351
352 rc = pBaseMedium->COMGETTER(Size)(&llSize);
353 if (FAILED(rc)) throw rc;
354 }
355
356 // and how this translates to the virtual system
357 int32_t lControllerVsys = 0;
358 LONG lChannelVsys;
359
360 switch (storageBus)
361 {
362 case StorageBus_IDE:
363 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
364 // and it must be updated when that is changed!
365 // Before 3.2 we exported one IDE controller with channel 0-3, but we now maintain
366 // compatibility with what VMware does and export two IDE controllers with two channels each
367
368 if (lChannel == 0 && lDevice == 0) // primary master
369 {
370 lControllerVsys = lIDEControllerPrimaryIndex;
371 lChannelVsys = 0;
372 }
373 else if (lChannel == 0 && lDevice == 1) // primary slave
374 {
375 lControllerVsys = lIDEControllerPrimaryIndex;
376 lChannelVsys = 1;
377 }
378 else if (lChannel == 1 && lDevice == 0) // secondary master; by default this is the CD-ROM but as of VirtualBox 3.1 that can change
379 {
380 lControllerVsys = lIDEControllerSecondaryIndex;
381 lChannelVsys = 0;
382 }
383 else if (lChannel == 1 && lDevice == 1) // secondary slave
384 {
385 lControllerVsys = lIDEControllerSecondaryIndex;
386 lChannelVsys = 1;
387 }
388 else
389 throw setError(VBOX_E_NOT_SUPPORTED,
390 tr("Cannot handle medium attachment: channel is %d, device is %d"), lChannel, lDevice);
391 break;
392
393 case StorageBus_SATA:
394 lChannelVsys = lChannel; // should be between 0 and 29
395 lControllerVsys = lSATAControllerIndex;
396 break;
397
398 case StorageBus_SCSI:
399 case StorageBus_SAS:
400 lChannelVsys = lChannel; // should be between 0 and 15
401 lControllerVsys = lSCSIControllerIndex;
402 break;
403
404 case StorageBus_Floppy:
405 lChannelVsys = 0;
406 lControllerVsys = 0;
407 break;
408
409 default:
410 throw setError(VBOX_E_NOT_SUPPORTED,
411 tr("Cannot handle medium attachment: storageBus is %d, channel is %d, device is %d"), storageBus, lChannel, lDevice);
412 break;
413 }
414
415 Utf8StrFmt strExtra("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys);
416 Utf8Str strEmpty;
417
418 switch (deviceType)
419 {
420 case DeviceType_HardDisk:
421 Log(("Adding VirtualSystemDescriptionType_HardDiskImage, disk size: %RI64\n", llSize));
422 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
423 strTargetVmdkName, // disk ID: let's use the name
424 strTargetVmdkName, // OVF value:
425 strLocation, // vbox value: media path
426 (uint32_t)(llSize / _1M),
427 strExtra);
428 break;
429
430 case DeviceType_DVD:
431 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM,
432 strEmpty, // disk ID
433 strEmpty, // OVF value
434 strEmpty, // vbox value
435 1, // ulSize
436 strExtra);
437 break;
438
439 case DeviceType_Floppy:
440 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy,
441 strEmpty, // disk ID
442 strEmpty, // OVF value
443 strEmpty, // vbox value
444 1, // ulSize
445 strExtra);
446 break;
447 }
448 }
449
450// <const name="NetworkAdapter" />
451 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(getChipsetType());
452 size_t a;
453 for (a = 0; a < maxNetworkAdapters; ++a)
454 {
455 ComPtr<INetworkAdapter> pNetworkAdapter;
456 BOOL fEnabled;
457 NetworkAdapterType_T adapterType;
458 NetworkAttachmentType_T attachmentType;
459
460 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
461 if (FAILED(rc)) throw rc;
462 /* Enable the network card & set the adapter type */
463 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
464 if (FAILED(rc)) throw rc;
465
466 if (fEnabled)
467 {
468 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
469 if (FAILED(rc)) throw rc;
470
471 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
472 if (FAILED(rc)) throw rc;
473
474 Utf8Str strAttachmentType = convertNetworkAttachmentTypeToString(attachmentType);
475 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
476 "", // ref
477 strAttachmentType, // orig
478 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
479 0,
480 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
481 }
482 }
483
484// <const name="USBController" />
485#ifdef VBOX_WITH_USB
486 if (fUSBEnabled)
487 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
488#endif /* VBOX_WITH_USB */
489
490// <const name="SoundCard" />
491 if (fAudioEnabled)
492 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
493 "",
494 "ensoniq1371", // this is what OVFTool writes and VMware supports
495 Utf8StrFmt("%RI32", audioController));
496
497 /* We return the new description to the caller */
498 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
499 copy.queryInterfaceTo(aDescription);
500
501 AutoWriteLock alock(pAppliance COMMA_LOCKVAL_SRC_POS);
502 // finally, add the virtual system to the appliance
503 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
504 }
505 catch(HRESULT arc)
506 {
507 rc = arc;
508 }
509
510 return rc;
511}
512
513////////////////////////////////////////////////////////////////////////////////
514//
515// IAppliance public methods
516//
517////////////////////////////////////////////////////////////////////////////////
518
519/**
520 * Public method implementation.
521 * @param format
522 * @param path
523 * @param aProgress
524 * @return
525 */
526STDMETHODIMP Appliance::Write(IN_BSTR format, BOOL fManifest, IN_BSTR path, IProgress **aProgress)
527{
528 if (!path) return E_POINTER;
529 CheckComArgOutPointerValid(aProgress);
530
531 AutoCaller autoCaller(this);
532 if (FAILED(autoCaller.rc())) return autoCaller.rc();
533
534 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
535
536 // do not allow entering this method if the appliance is busy reading or writing
537 if (!isApplianceIdle())
538 return E_ACCESSDENIED;
539
540 // see if we can handle this file; for now we insist it has an ".ovf" extension
541 Utf8Str strPath = path;
542 if (!( strPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
543 || strPath.endsWith(".ova", Utf8Str::CaseInsensitive)))
544 return setError(VBOX_E_FILE_ERROR,
545 tr("Appliance file must have .ovf or .ova extension"));
546
547 m->fManifest = !!fManifest;
548 Utf8Str strFormat(format);
549
550 ovf::OVFVersion_T ovfF;
551 if (strFormat == "ovf-0.9")
552 {
553 ovfF = ovf::OVFVersion_0_9;
554 }
555 else if (strFormat == "ovf-1.0")
556 {
557 ovfF = ovf::OVFVersion_1_0;
558 }
559 else if (strFormat == "ovf-2.0")
560 {
561 ovfF = ovf::OVFVersion_2_0;
562 }
563 else
564 return setError(VBOX_E_FILE_ERROR,
565 tr("Invalid format \"%s\" specified"), strFormat.c_str());
566
567 /* as of OVF 2.0 we have to use SHA256 */
568 m->fSha256 = ovfF >= ovf::OVFVersion_2_0;
569
570 ComObjPtr<Progress> progress;
571 HRESULT rc = S_OK;
572 try
573 {
574 /* Parse all necessary info out of the URI */
575 parseURI(strPath, m->locInfo);
576 rc = writeImpl(ovfF, m->locInfo, progress);
577 }
578 catch (HRESULT aRC)
579 {
580 rc = aRC;
581 }
582
583 if (SUCCEEDED(rc))
584 /* Return progress to the caller */
585 progress.queryInterfaceTo(aProgress);
586
587 return rc;
588}
589
590////////////////////////////////////////////////////////////////////////////////
591//
592// Appliance private methods
593//
594////////////////////////////////////////////////////////////////////////////////
595
596/*******************************************************************************
597 * Export stuff
598 ******************************************************************************/
599
600/**
601 * Implementation for writing out the OVF to disk. This starts a new thread which will call
602 * Appliance::taskThreadWriteOVF().
603 *
604 * This is in a separate private method because it is used from two locations:
605 *
606 * 1) from the public Appliance::Write().
607 *
608 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
609 * called Appliance::writeFSOVA(), which called Appliance::writeImpl(), which then called this again.
610 *
611 * 3) from Appliance::writeS3(), which got called from a previous instance of Appliance::taskThreadWriteOVF().
612 *
613 * @param aFormat
614 * @param aLocInfo
615 * @param aProgress
616 * @return
617 */
618HRESULT Appliance::writeImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
619{
620 HRESULT rc = S_OK;
621 try
622 {
623 rc = setUpProgress(aProgress,
624 BstrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
625 (aLocInfo.storageType == VFSType_File) ? WriteFile : WriteS3);
626
627 /* Initialize our worker task */
628 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress));
629 /* The OVF version to write */
630 task->enFormat = aFormat;
631
632 rc = task->startThread();
633 if (FAILED(rc)) throw rc;
634
635 /* Don't destruct on success */
636 task.release();
637 }
638 catch (HRESULT aRC)
639 {
640 rc = aRC;
641 }
642
643 return rc;
644}
645
646/**
647 * Called from Appliance::writeFS() for creating a XML document for this
648 * Appliance.
649 *
650 * @param writeLock The current write lock.
651 * @param doc The xml document to fill.
652 * @param stack Structure for temporary private
653 * data shared with caller.
654 * @param strPath Path to the target OVF.
655 * instance for which to write XML.
656 * @param enFormat OVF format (0.9 or 1.0).
657 */
658void Appliance::buildXML(AutoWriteLockBase& writeLock,
659 xml::Document &doc,
660 XMLStack &stack,
661 const Utf8Str &strPath,
662 ovf::OVFVersion_T enFormat)
663{
664 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
665
666 pelmRoot->setAttribute("ovf:version", enFormat == ovf::OVFVersion_2_0 ? "2.0"
667 : enFormat == ovf::OVFVersion_1_0 ? "1.0"
668 : "0.9");
669 pelmRoot->setAttribute("xml:lang", "en-US");
670
671 Utf8Str strNamespace;
672
673 if (enFormat == ovf::OVFVersion_0_9)
674 {
675 strNamespace = "http://www.vmware.com/schema/ovf/1/envelope";
676 }
677 else if (enFormat == ovf::OVFVersion_1_0)
678 {
679 strNamespace = "http://schemas.dmtf.org/ovf/envelope/1";
680 }
681 else
682 {
683 strNamespace = "http://schemas.dmtf.org/ovf/envelope/2";
684 }
685
686 pelmRoot->setAttribute("xmlns", strNamespace);
687 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
688
689 // pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
690 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
691 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
692 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
693 pelmRoot->setAttribute("xmlns:vbox", "http://www.virtualbox.org/ovf/machine");
694 // pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
695
696 // <Envelope>/<References>
697 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
698
699 /* <Envelope>/<DiskSection>:
700 <DiskSection>
701 <Info>List of the virtual disks used in the package</Info>
702 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
703 </DiskSection> */
704 xml::ElementNode *pelmDiskSection;
705 if (enFormat == ovf::OVFVersion_0_9)
706 {
707 // <Section xsi:type="ovf:DiskSection_Type">
708 pelmDiskSection = pelmRoot->createChild("Section");
709 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
710 }
711 else
712 pelmDiskSection = pelmRoot->createChild("DiskSection");
713
714 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
715 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
716
717 /* <Envelope>/<NetworkSection>:
718 <NetworkSection>
719 <Info>Logical networks used in the package</Info>
720 <Network ovf:name="VM Network">
721 <Description>The network that the LAMP Service will be available on</Description>
722 </Network>
723 </NetworkSection> */
724 xml::ElementNode *pelmNetworkSection;
725 if (enFormat == ovf::OVFVersion_0_9)
726 {
727 // <Section xsi:type="ovf:NetworkSection_Type">
728 pelmNetworkSection = pelmRoot->createChild("Section");
729 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
730 }
731 else
732 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
733
734 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
735 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
736
737 // and here come the virtual systems:
738
739 // write a collection if we have more than one virtual system _and_ we're
740 // writing OVF 1.0; otherwise fail since ovftool can't import more than
741 // one machine, it seems
742 xml::ElementNode *pelmToAddVirtualSystemsTo;
743 if (m->virtualSystemDescriptions.size() > 1)
744 {
745 if (enFormat == ovf::OVFVersion_0_9)
746 throw setError(VBOX_E_FILE_ERROR,
747 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
748
749 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
750 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
751 }
752 else
753 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
754
755 // this list receives pointers to the XML elements in the machine XML which
756 // might have UUIDs that need fixing after we know the UUIDs of the exported images
757 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
758
759 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
760 /* Iterate through all virtual systems of that appliance */
761 for (it = m->virtualSystemDescriptions.begin();
762 it != m->virtualSystemDescriptions.end();
763 ++it)
764 {
765 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
766 buildXMLForOneVirtualSystem(writeLock,
767 *pelmToAddVirtualSystemsTo,
768 &llElementsWithUuidAttributes,
769 vsdescThis,
770 enFormat,
771 stack); // disks and networks stack
772 }
773
774 // now, fill in the network section we set up empty above according
775 // to the networks we found with the hardware items
776 map<Utf8Str, bool>::const_iterator itN;
777 for (itN = stack.mapNetworks.begin();
778 itN != stack.mapNetworks.end();
779 ++itN)
780 {
781 const Utf8Str &strNetwork = itN->first;
782 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
783 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
784 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
785 }
786
787 // Finally, write out the disk info
788 list<Utf8Str> diskList;
789 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
790 uint32_t ulFile = 1;
791 for (itS = stack.mapDisks.begin();
792 itS != stack.mapDisks.end();
793 ++itS)
794 {
795 const Utf8Str &strDiskID = itS->first;
796 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
797
798 // source path: where the VBox image is
799 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
800 Bstr bstrSrcFilePath(strSrcFilePath);
801
802 // Do NOT check here whether the file exists. FindMedium will figure
803 // that out, and filesystem-based tests are simply wrong in the
804 // general case (think of iSCSI).
805
806 // We need some info from the source disks
807 ComPtr<IMedium> pSourceDisk;
808
809 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
810 HRESULT rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(), DeviceType_HardDisk, AccessMode_ReadWrite, FALSE /* fForceNewUuid */, pSourceDisk.asOutParam());
811 if (FAILED(rc)) throw rc;
812
813 Bstr uuidSource;
814 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
815 if (FAILED(rc)) throw rc;
816 Guid guidSource(uuidSource);
817
818 // output filename
819 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
820 // target path needs to be composed from where the output OVF is
821 Utf8Str strTargetFilePath(strPath);
822 strTargetFilePath.stripFilename();
823 strTargetFilePath.append("/");
824 strTargetFilePath.append(strTargetFileNameOnly);
825
826 // We are always exporting to VMDK stream optimized for now
827 Bstr bstrSrcFormat = L"VMDK";
828
829 diskList.push_back(strTargetFilePath);
830
831 LONG64 cbCapacity = 0; // size reported to guest
832 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
833 if (FAILED(rc)) throw rc;
834 // Todo r=poetzsch: wrong it is reported in bytes ...
835 // capacity is reported in megabytes, so...
836 //cbCapacity *= _1M;
837
838 Guid guidTarget; /* Creates a new uniq number for the target disk. */
839 guidTarget.create();
840
841 // now handle the XML for the disk:
842 Utf8StrFmt strFileRef("file%RI32", ulFile++);
843 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
844 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
845 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
846 pelmFile->setAttribute("ovf:id", strFileRef);
847 // Todo: the actual size is not available at this point of time,
848 // cause the disk will be compressed. The 1.0 standard says this is
849 // optional! 1.1 isn't fully clear if the "gzip" format is used.
850 // Need to be checked. */
851 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
852
853 // add disk to XML Disks section
854 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
855 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
856 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
857 pelmDisk->setAttribute("ovf:diskId", strDiskID);
858 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
859 pelmDisk->setAttribute("ovf:format",
860 (enFormat == ovf::OVFVersion_0_9)
861 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftool chokes
862 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
863 // correct string as communicated to us by VMware (public bug #6612)
864 );
865
866 // add the UUID of the newly target image to the OVF disk element, but in the
867 // vbox: namespace since it's not part of the standard
868 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
869
870 // now, we might have other XML elements from vbox:Machine pointing to this image,
871 // but those would refer to the UUID of the _source_ image (which we created the
872 // export image from); those UUIDs need to be fixed to the export image
873 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
874 for (std::list<xml::ElementNode*>::iterator eit = llElementsWithUuidAttributes.begin();
875 eit != llElementsWithUuidAttributes.end();
876 ++eit)
877 {
878 xml::ElementNode *pelmImage = *eit;
879 Utf8Str strUUID;
880 pelmImage->getAttributeValue("uuid", strUUID);
881 if (strUUID == strGuidSourceCurly)
882 // overwrite existing uuid attribute
883 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
884 }
885 }
886}
887
888/**
889 * Called from Appliance::buildXML() for each virtual system (machine) that
890 * needs XML written out.
891 *
892 * @param writeLock The current write lock.
893 * @param elmToAddVirtualSystemsTo XML element to append elements to.
894 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
895 * with UUID attributes for quick
896 * fixing by caller later
897 * @param vsdescThis The IVirtualSystemDescription
898 * instance for which to write XML.
899 * @param enFormat OVF format (0.9 or 1.0).
900 * @param stack Structure for temporary private
901 * data shared with caller.
902 */
903void Appliance::buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
904 xml::ElementNode &elmToAddVirtualSystemsTo,
905 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
906 ComObjPtr<VirtualSystemDescription> &vsdescThis,
907 ovf::OVFVersion_T enFormat,
908 XMLStack &stack)
909{
910 LogFlowFunc(("ENTER appliance %p\n", this));
911
912 xml::ElementNode *pelmVirtualSystem;
913 if (enFormat == ovf::OVFVersion_0_9)
914 {
915 // <Section xsi:type="ovf:NetworkSection_Type">
916 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
917 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
918 }
919 else
920 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
921
922 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
923
924 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
925 if (llName.size() != 1)
926 throw setError(VBOX_E_NOT_SUPPORTED,
927 tr("Missing VM name"));
928 Utf8Str &strVMName = llName.front()->strVboxCurrent;
929 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
930
931 // product info
932 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
933 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
934 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
935 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
936 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
937 bool fProduct = llProduct.size() && !llProduct.front()->strVboxCurrent.isEmpty();
938 bool fProductUrl = llProductUrl.size() && !llProductUrl.front()->strVboxCurrent.isEmpty();
939 bool fVendor = llVendor.size() && !llVendor.front()->strVboxCurrent.isEmpty();
940 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.front()->strVboxCurrent.isEmpty();
941 bool fVersion = llVersion.size() && !llVersion.front()->strVboxCurrent.isEmpty();
942 if (fProduct ||
943 fProductUrl ||
944 fVersion ||
945 fVendorUrl ||
946 fVersion)
947 {
948 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
949 <Info>Meta-information about the installed software</Info>
950 <Product>VAtest</Product>
951 <Vendor>SUN Microsystems</Vendor>
952 <Version>10.0</Version>
953 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
954 <VendorUrl>http://www.sun.com</VendorUrl>
955 </Section> */
956 xml::ElementNode *pelmAnnotationSection;
957 if (enFormat == ovf::OVFVersion_0_9)
958 {
959 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
960 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
961 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
962 }
963 else
964 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
965
966 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
967 if (fProduct)
968 pelmAnnotationSection->createChild("Product")->addContent(llProduct.front()->strVboxCurrent);
969 if (fVendor)
970 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.front()->strVboxCurrent);
971 if (fVersion)
972 pelmAnnotationSection->createChild("Version")->addContent(llVersion.front()->strVboxCurrent);
973 if (fProductUrl)
974 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.front()->strVboxCurrent);
975 if (fVendorUrl)
976 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.front()->strVboxCurrent);
977 }
978
979 // description
980 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
981 if (llDescription.size() &&
982 !llDescription.front()->strVboxCurrent.isEmpty())
983 {
984 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
985 <Info>A human-readable annotation</Info>
986 <Annotation>Plan 9</Annotation>
987 </Section> */
988 xml::ElementNode *pelmAnnotationSection;
989 if (enFormat == ovf::OVFVersion_0_9)
990 {
991 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
992 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
993 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
994 }
995 else
996 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
997
998 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
999 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.front()->strVboxCurrent);
1000 }
1001
1002 // license
1003 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
1004 if (llLicense.size() &&
1005 !llLicense.front()->strVboxCurrent.isEmpty())
1006 {
1007 /* <EulaSection>
1008 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1009 <License ovf:msgid="1">License terms can go in here.</License>
1010 </EulaSection> */
1011 xml::ElementNode *pelmEulaSection;
1012 if (enFormat == ovf::OVFVersion_0_9)
1013 {
1014 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1015 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1016 }
1017 else
1018 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1019
1020 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1021 pelmEulaSection->createChild("License")->addContent(llLicense.front()->strVboxCurrent);
1022 }
1023
1024 // operating system
1025 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1026 if (llOS.size() != 1)
1027 throw setError(VBOX_E_NOT_SUPPORTED,
1028 tr("Missing OS type"));
1029 /* <OperatingSystemSection ovf:id="82">
1030 <Info>Guest Operating System</Info>
1031 <Description>Linux 2.6.x</Description>
1032 </OperatingSystemSection> */
1033 VirtualSystemDescriptionEntry *pvsdeOS = llOS.front();
1034 xml::ElementNode *pelmOperatingSystemSection;
1035 if (enFormat == ovf::OVFVersion_0_9)
1036 {
1037 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1038 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1039 }
1040 else
1041 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1042
1043 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1044 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1045 Utf8Str strOSDesc;
1046 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1047 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1048 // add the VirtualBox ostype in a custom tag in a different namespace
1049 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1050 pelmVBoxOSType->setAttribute("ovf:required", "false");
1051 pelmVBoxOSType->addContent(pvsdeOS->strVboxCurrent);
1052
1053 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1054 xml::ElementNode *pelmVirtualHardwareSection;
1055 if (enFormat == ovf::OVFVersion_0_9)
1056 {
1057 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1058 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1059 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1060 }
1061 else
1062 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1063
1064 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1065
1066 /* <System>
1067 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1068 <vssd:ElementName>vmware</vssd:ElementName>
1069 <vssd:InstanceID>1</vssd:InstanceID>
1070 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1071 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1072 </System> */
1073 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1074
1075 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1076
1077 // <vssd:InstanceId>0</vssd:InstanceId>
1078 if (enFormat == ovf::OVFVersion_0_9)
1079 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1080 else // capitalization changed...
1081 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1082
1083 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1084 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1085 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1086 const char *pcszHardware = "virtualbox-2.2";
1087 if (enFormat == ovf::OVFVersion_0_9)
1088 // pretend to be vmware compatible then
1089 pcszHardware = "vmx-6";
1090 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1091
1092 // loop thru all description entries twice; once to write out all
1093 // devices _except_ disk images, and a second time to assign the
1094 // disk images; this is because disk images need to reference
1095 // IDE controllers, and we can't know their instance IDs without
1096 // assigning them first
1097
1098 uint32_t idIDEPrimaryController = 0;
1099 int32_t lIDEPrimaryControllerIndex = 0;
1100 uint32_t idIDESecondaryController = 0;
1101 int32_t lIDESecondaryControllerIndex = 0;
1102 uint32_t idSATAController = 0;
1103 int32_t lSATAControllerIndex = 0;
1104 uint32_t idSCSIController = 0;
1105 int32_t lSCSIControllerIndex = 0;
1106
1107 uint32_t ulInstanceID = 1;
1108
1109 uint32_t cDVDs = 0;
1110
1111 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1112 {
1113 int32_t lIndexThis = 0;
1114 list<VirtualSystemDescriptionEntry>::const_iterator itD;
1115 for (itD = vsdescThis->m->llDescriptions.begin();
1116 itD != vsdescThis->m->llDescriptions.end();
1117 ++itD, ++lIndexThis)
1118 {
1119 const VirtualSystemDescriptionEntry &desc = *itD;
1120
1121 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVbox=%s, strExtraConfig=%s\n",
1122 uLoop,
1123 desc.ulIndex,
1124 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1125 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1126 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1127 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1128 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1129 : Utf8StrFmt("%d", desc.type).c_str()),
1130 desc.strRef.c_str(),
1131 desc.strOvf.c_str(),
1132 desc.strVboxCurrent.c_str(),
1133 desc.strExtraConfigCurrent.c_str()));
1134
1135 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1136 Utf8Str strResourceSubType;
1137
1138 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1139 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1140
1141 uint32_t ulParent = 0;
1142
1143 int32_t lVirtualQuantity = -1;
1144 Utf8Str strAllocationUnits;
1145
1146 int32_t lAddress = -1;
1147 int32_t lBusNumber = -1;
1148 int32_t lAddressOnParent = -1;
1149
1150 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1151 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1152 Utf8Str strHostResource;
1153
1154 uint64_t uTemp;
1155
1156 switch (desc.type)
1157 {
1158 case VirtualSystemDescriptionType_CPU:
1159 /* <Item>
1160 <rasd:Caption>1 virtual CPU</rasd:Caption>
1161 <rasd:Description>Number of virtual CPUs</rasd:Description>
1162 <rasd:ElementName>virtual CPU</rasd:ElementName>
1163 <rasd:InstanceID>1</rasd:InstanceID>
1164 <rasd:ResourceType>3</rasd:ResourceType>
1165 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1166 </Item> */
1167 if (uLoop == 1)
1168 {
1169 strDescription = "Number of virtual CPUs";
1170 type = ovf::ResourceType_Processor; // 3
1171 desc.strVboxCurrent.toInt(uTemp);
1172 lVirtualQuantity = (int32_t)uTemp;
1173 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
1174 }
1175 break;
1176
1177 case VirtualSystemDescriptionType_Memory:
1178 /* <Item>
1179 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1180 <rasd:Caption>256 MB of memory</rasd:Caption>
1181 <rasd:Description>Memory Size</rasd:Description>
1182 <rasd:ElementName>Memory</rasd:ElementName>
1183 <rasd:InstanceID>2</rasd:InstanceID>
1184 <rasd:ResourceType>4</rasd:ResourceType>
1185 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1186 </Item> */
1187 if (uLoop == 1)
1188 {
1189 strDescription = "Memory Size";
1190 type = ovf::ResourceType_Memory; // 4
1191 desc.strVboxCurrent.toInt(uTemp);
1192 lVirtualQuantity = (int32_t)(uTemp / _1M);
1193 strAllocationUnits = "MegaBytes";
1194 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
1195 }
1196 break;
1197
1198 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1199 /* <Item>
1200 <rasd:Caption>ideController1</rasd:Caption>
1201 <rasd:Description>IDE Controller</rasd:Description>
1202 <rasd:InstanceId>5</rasd:InstanceId>
1203 <rasd:ResourceType>5</rasd:ResourceType>
1204 <rasd:Address>1</rasd:Address>
1205 <rasd:BusNumber>1</rasd:BusNumber>
1206 </Item> */
1207 if (uLoop == 1)
1208 {
1209 strDescription = "IDE Controller";
1210 type = ovf::ResourceType_IDEController; // 5
1211 strResourceSubType = desc.strVboxCurrent;
1212
1213 if (!lIDEPrimaryControllerIndex)
1214 {
1215 // first IDE controller:
1216 strCaption = "ideController0";
1217 lAddress = 0;
1218 lBusNumber = 0;
1219 // remember this ID
1220 idIDEPrimaryController = ulInstanceID;
1221 lIDEPrimaryControllerIndex = lIndexThis;
1222 }
1223 else
1224 {
1225 // second IDE controller:
1226 strCaption = "ideController1";
1227 lAddress = 1;
1228 lBusNumber = 1;
1229 // remember this ID
1230 idIDESecondaryController = ulInstanceID;
1231 lIDESecondaryControllerIndex = lIndexThis;
1232 }
1233 }
1234 break;
1235
1236 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1237 /* <Item>
1238 <rasd:Caption>sataController0</rasd:Caption>
1239 <rasd:Description>SATA Controller</rasd:Description>
1240 <rasd:InstanceId>4</rasd:InstanceId>
1241 <rasd:ResourceType>20</rasd:ResourceType>
1242 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1243 <rasd:Address>0</rasd:Address>
1244 <rasd:BusNumber>0</rasd:BusNumber>
1245 </Item>
1246 */
1247 if (uLoop == 1)
1248 {
1249 strDescription = "SATA Controller";
1250 strCaption = "sataController0";
1251 type = ovf::ResourceType_OtherStorageDevice; // 20
1252 // it seems that OVFTool always writes these two, and since we can only
1253 // have one SATA controller, we'll use this as well
1254 lAddress = 0;
1255 lBusNumber = 0;
1256
1257 if ( desc.strVboxCurrent.isEmpty() // AHCI is the default in VirtualBox
1258 || (!desc.strVboxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1259 )
1260 strResourceSubType = "AHCI";
1261 else
1262 throw setError(VBOX_E_NOT_SUPPORTED,
1263 tr("Invalid config string \"%s\" in SATA controller"), desc.strVboxCurrent.c_str());
1264
1265 // remember this ID
1266 idSATAController = ulInstanceID;
1267 lSATAControllerIndex = lIndexThis;
1268 }
1269 break;
1270
1271 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1272 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1273 /* <Item>
1274 <rasd:Caption>scsiController0</rasd:Caption>
1275 <rasd:Description>SCSI Controller</rasd:Description>
1276 <rasd:InstanceId>4</rasd:InstanceId>
1277 <rasd:ResourceType>6</rasd:ResourceType>
1278 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1279 <rasd:Address>0</rasd:Address>
1280 <rasd:BusNumber>0</rasd:BusNumber>
1281 </Item>
1282 */
1283 if (uLoop == 1)
1284 {
1285 strDescription = "SCSI Controller";
1286 strCaption = "scsiController0";
1287 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1288 // it seems that OVFTool always writes these two, and since we can only
1289 // have one SATA controller, we'll use this as well
1290 lAddress = 0;
1291 lBusNumber = 0;
1292
1293 if ( desc.strVboxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1294 || (!desc.strVboxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1295 )
1296 strResourceSubType = "lsilogic";
1297 else if (!desc.strVboxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1298 strResourceSubType = "buslogic";
1299 else if (!desc.strVboxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1300 strResourceSubType = "lsilogicsas";
1301 else
1302 throw setError(VBOX_E_NOT_SUPPORTED,
1303 tr("Invalid config string \"%s\" in SCSI/SAS controller"), desc.strVboxCurrent.c_str());
1304
1305 // remember this ID
1306 idSCSIController = ulInstanceID;
1307 lSCSIControllerIndex = lIndexThis;
1308 }
1309 break;
1310
1311 case VirtualSystemDescriptionType_HardDiskImage:
1312 /* <Item>
1313 <rasd:Caption>disk1</rasd:Caption>
1314 <rasd:InstanceId>8</rasd:InstanceId>
1315 <rasd:ResourceType>17</rasd:ResourceType>
1316 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1317 <rasd:Parent>4</rasd:Parent>
1318 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1319 </Item> */
1320 if (uLoop == 2)
1321 {
1322 uint32_t cDisks = stack.mapDisks.size();
1323 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1324
1325 strDescription = "Disk Image";
1326 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1327 type = ovf::ResourceType_HardDisk; // 17
1328
1329 // the following references the "<Disks>" XML block
1330 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1331
1332 // controller=<index>;channel=<c>
1333 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1334 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1335 int32_t lControllerIndex = -1;
1336 if (pos1 != Utf8Str::npos)
1337 {
1338 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1339 if (lControllerIndex == lIDEPrimaryControllerIndex)
1340 ulParent = idIDEPrimaryController;
1341 else if (lControllerIndex == lIDESecondaryControllerIndex)
1342 ulParent = idIDESecondaryController;
1343 else if (lControllerIndex == lSCSIControllerIndex)
1344 ulParent = idSCSIController;
1345 else if (lControllerIndex == lSATAControllerIndex)
1346 ulParent = idSATAController;
1347 }
1348 if (pos2 != Utf8Str::npos)
1349 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1350
1351 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1352 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1353
1354 if ( !ulParent
1355 || lAddressOnParent == -1
1356 )
1357 throw setError(VBOX_E_NOT_SUPPORTED,
1358 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfigCurrent.c_str());
1359
1360 stack.mapDisks[strDiskID] = &desc;
1361 }
1362 break;
1363
1364 case VirtualSystemDescriptionType_Floppy:
1365 if (uLoop == 1)
1366 {
1367 strDescription = "Floppy Drive";
1368 strCaption = "floppy0"; // this is what OVFTool writes
1369 type = ovf::ResourceType_FloppyDrive; // 14
1370 lAutomaticAllocation = 0;
1371 lAddressOnParent = 0; // this is what OVFTool writes
1372 }
1373 break;
1374
1375 case VirtualSystemDescriptionType_CDROM:
1376 if (uLoop == 2)
1377 {
1378 strDescription = "CD-ROM Drive";
1379 strCaption = Utf8StrFmt("cdrom%RI32", ++cDVDs); // OVFTool starts with 1
1380 type = ovf::ResourceType_CDDrive; // 15
1381 lAutomaticAllocation = 1;
1382
1383 // controller=<index>;channel=<c>
1384 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1385 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1386 int32_t lControllerIndex = -1;
1387 if (pos1 != Utf8Str::npos)
1388 {
1389 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1390 if (lControllerIndex == lIDEPrimaryControllerIndex)
1391 ulParent = idIDEPrimaryController;
1392 else if (lControllerIndex == lIDESecondaryControllerIndex)
1393 ulParent = idIDESecondaryController;
1394 else if (lControllerIndex == lSCSIControllerIndex)
1395 ulParent = idSCSIController;
1396 else if (lControllerIndex == lSATAControllerIndex)
1397 ulParent = idSATAController;
1398 }
1399 if (pos2 != Utf8Str::npos)
1400 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1401
1402 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1403 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1404
1405 if ( !ulParent
1406 || lAddressOnParent == -1
1407 )
1408 throw setError(VBOX_E_NOT_SUPPORTED,
1409 tr("Missing or bad extra config string in DVD drive medium: \"%s\""), desc.strExtraConfigCurrent.c_str());
1410
1411 // there is no DVD drive map to update because it is
1412 // handled completely with this entry.
1413 }
1414 break;
1415
1416 case VirtualSystemDescriptionType_NetworkAdapter:
1417 /* <Item>
1418 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1419 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1420 <rasd:Connection>VM Network</rasd:Connection>
1421 <rasd:ElementName>VM network</rasd:ElementName>
1422 <rasd:InstanceID>3</rasd:InstanceID>
1423 <rasd:ResourceType>10</rasd:ResourceType>
1424 </Item> */
1425 if (uLoop == 1)
1426 {
1427 lAutomaticAllocation = 1;
1428 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1429 type = ovf::ResourceType_EthernetAdapter; // 10
1430 /* Set the hardware type to something useful.
1431 * To be compatible with vmware & others we set
1432 * PCNet32 for our PCNet types & E1000 for the
1433 * E1000 cards. */
1434 switch (desc.strVboxCurrent.toInt32())
1435 {
1436 case NetworkAdapterType_Am79C970A:
1437 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1438#ifdef VBOX_WITH_E1000
1439 case NetworkAdapterType_I82540EM:
1440 case NetworkAdapterType_I82545EM:
1441 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1442#endif /* VBOX_WITH_E1000 */
1443 }
1444 strConnection = desc.strOvf;
1445
1446 stack.mapNetworks[desc.strOvf] = true;
1447 }
1448 break;
1449
1450 case VirtualSystemDescriptionType_USBController:
1451 /* <Item ovf:required="false">
1452 <rasd:Caption>usb</rasd:Caption>
1453 <rasd:Description>USB Controller</rasd:Description>
1454 <rasd:InstanceId>3</rasd:InstanceId>
1455 <rasd:ResourceType>23</rasd:ResourceType>
1456 <rasd:Address>0</rasd:Address>
1457 <rasd:BusNumber>0</rasd:BusNumber>
1458 </Item> */
1459 if (uLoop == 1)
1460 {
1461 strDescription = "USB Controller";
1462 strCaption = "usb";
1463 type = ovf::ResourceType_USBController; // 23
1464 lAddress = 0; // this is what OVFTool writes
1465 lBusNumber = 0; // this is what OVFTool writes
1466 }
1467 break;
1468
1469 case VirtualSystemDescriptionType_SoundCard:
1470 /* <Item ovf:required="false">
1471 <rasd:Caption>sound</rasd:Caption>
1472 <rasd:Description>Sound Card</rasd:Description>
1473 <rasd:InstanceId>10</rasd:InstanceId>
1474 <rasd:ResourceType>35</rasd:ResourceType>
1475 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1476 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1477 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1478 </Item> */
1479 if (uLoop == 1)
1480 {
1481 strDescription = "Sound Card";
1482 strCaption = "sound";
1483 type = ovf::ResourceType_SoundCard; // 35
1484 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1485 lAutomaticAllocation = 0;
1486 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1487 }
1488 break;
1489 }
1490
1491 if (type)
1492 {
1493 xml::ElementNode *pItem;
1494
1495 pItem = pelmVirtualHardwareSection->createChild("Item");
1496
1497 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1498 // the elements from the rasd: namespace must be sorted by letter, and VMware
1499 // actually requires this as well (see public bug #6612)
1500
1501 if (lAddress != -1)
1502 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1503
1504 if (lAddressOnParent != -1)
1505 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1506
1507 if (!strAllocationUnits.isEmpty())
1508 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1509
1510 if (lAutomaticAllocation != -1)
1511 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1512
1513 if (lBusNumber != -1)
1514 if (enFormat == ovf::OVFVersion_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool y
1515 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1516
1517 if (!strCaption.isEmpty())
1518 pItem->createChild("rasd:Caption")->addContent(strCaption);
1519
1520 if (!strConnection.isEmpty())
1521 pItem->createChild("rasd:Connection")->addContent(strConnection);
1522
1523 if (!strDescription.isEmpty())
1524 pItem->createChild("rasd:Description")->addContent(strDescription);
1525
1526 if (!strCaption.isEmpty())
1527 if (enFormat == ovf::OVFVersion_1_0)
1528 pItem->createChild("rasd:ElementName")->addContent(strCaption);
1529
1530 if (!strHostResource.isEmpty())
1531 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1532
1533 // <rasd:InstanceID>1</rasd:InstanceID>
1534 xml::ElementNode *pelmInstanceID;
1535 if (enFormat == ovf::OVFVersion_0_9)
1536 pelmInstanceID = pItem->createChild("rasd:InstanceId");
1537 else
1538 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1539 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
1540
1541 if (ulParent)
1542 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1543
1544 if (!strResourceSubType.isEmpty())
1545 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1546
1547 // <rasd:ResourceType>3</rasd:ResourceType>
1548 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1549
1550 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1551 if (lVirtualQuantity != -1)
1552 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1553 }
1554 }
1555 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1556
1557 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1558 // under the vbox: namespace
1559 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1560 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1561 pelmVBoxMachine->setAttribute("ovf:required", "false");
1562 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1563 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1564
1565 // create an empty machine config
1566 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(NULL);
1567
1568 writeLock.release();
1569 try
1570 {
1571 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1572 // fill the machine config
1573 vsdescThis->m->pMachine->copyMachineDataToSettings(*pConfig);
1574 // write the machine config to the vbox:Machine element
1575 pConfig->buildMachineXML(*pelmVBoxMachine,
1576 settings::MachineConfigFile::BuildMachineXML_WriteVboxVersionAttribute
1577 | settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia
1578 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
1579 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1580 pllElementsWithUuidAttributes);
1581 delete pConfig;
1582 }
1583 catch (...)
1584 {
1585 writeLock.acquire();
1586 delete pConfig;
1587 throw;
1588 }
1589 writeLock.acquire();
1590}
1591
1592/**
1593 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1594 * and therefore runs on the OVF/OVA write worker thread. This runs in two contexts:
1595 *
1596 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::writeImpl();
1597 *
1598 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
1599 * called Appliance::writeS3(), which called Appliance::writeImpl(), which then called this. In other
1600 * words, to write to the cloud, the first worker thread first starts a second worker thread to create
1601 * temporary files and then uploads them to the S3 cloud server.
1602 *
1603 * @param pTask
1604 * @return
1605 */
1606HRESULT Appliance::writeFS(TaskOVF *pTask)
1607{
1608 LogFlowFuncEnter();
1609 LogFlowFunc(("ENTER appliance %p\n", this));
1610
1611 AutoCaller autoCaller(this);
1612 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1613
1614 HRESULT rc = S_OK;
1615
1616 // Lock the media tree early to make sure nobody else tries to make changes
1617 // to the tree. Also lock the IAppliance object for writing.
1618 AutoMultiWriteLock2 multiLock(&mVirtualBox->getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1619 // Additional protect the IAppliance object, cause we leave the lock
1620 // when starting the disk export and we don't won't block other
1621 // callers on this lengthy operations.
1622 m->state = Data::ApplianceExporting;
1623
1624 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1625 rc = writeFSOVF(pTask, multiLock);
1626 else
1627 rc = writeFSOVA(pTask, multiLock);
1628
1629 // reset the state so others can call methods again
1630 m->state = Data::ApplianceIdle;
1631
1632 LogFlowFunc(("rc=%Rhrc\n", rc));
1633 LogFlowFuncLeave();
1634 return rc;
1635}
1636
1637HRESULT Appliance::writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1638{
1639 LogFlowFuncEnter();
1640
1641 HRESULT rc = S_OK;
1642
1643 PVDINTERFACEIO pShaIo = 0;
1644 PVDINTERFACEIO pFileIo = 0;
1645 do
1646 {
1647 pShaIo = ShaCreateInterface();
1648 if (!pShaIo)
1649 {
1650 rc = E_OUTOFMEMORY;
1651 break;
1652 }
1653 pFileIo = FileCreateInterface();
1654 if (!pFileIo)
1655 {
1656 rc = E_OUTOFMEMORY;
1657 break;
1658 }
1659
1660 SHASTORAGE storage;
1661 RT_ZERO(storage);
1662 storage.fCreateDigest = m->fManifest;
1663 storage.fSha256 = m->fSha256;
1664 int vrc = VDInterfaceAdd(&pFileIo->Core, "Appliance::IOFile",
1665 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1666 &storage.pVDImageIfaces);
1667 if (RT_FAILURE(vrc))
1668 {
1669 rc = E_FAIL;
1670 break;
1671 }
1672 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1673 } while (0);
1674
1675 /* Cleanup */
1676 if (pShaIo)
1677 RTMemFree(pShaIo);
1678 if (pFileIo)
1679 RTMemFree(pFileIo);
1680
1681 LogFlowFuncLeave();
1682 return rc;
1683}
1684
1685HRESULT Appliance::writeFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1686{
1687 LogFlowFuncEnter();
1688
1689 RTTAR tar;
1690 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL, false);
1691 if (RT_FAILURE(vrc))
1692 return setError(VBOX_E_FILE_ERROR,
1693 tr("Could not create OVA file '%s' (%Rrc)"),
1694 pTask->locInfo.strPath.c_str(), vrc);
1695
1696 HRESULT rc = S_OK;
1697
1698 PVDINTERFACEIO pShaIo = 0;
1699 PVDINTERFACEIO pTarIo = 0;
1700 do
1701 {
1702 pShaIo = ShaCreateInterface();
1703 if (!pShaIo)
1704 {
1705 rc = E_OUTOFMEMORY;
1706 break;
1707 }
1708 pTarIo = TarCreateInterface();
1709 if (!pTarIo)
1710 {
1711 rc = E_OUTOFMEMORY;
1712 break;
1713 }
1714 SHASTORAGE storage;
1715 RT_ZERO(storage);
1716 storage.fCreateDigest = m->fManifest;
1717 storage.fSha256 = m->fSha256;
1718 vrc = VDInterfaceAdd(&pTarIo->Core, "Appliance::IOTar",
1719 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
1720 &storage.pVDImageIfaces);
1721 if (RT_FAILURE(vrc))
1722 {
1723 rc = E_FAIL;
1724 break;
1725 }
1726 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1727 } while (0);
1728
1729 RTTarClose(tar);
1730
1731 /* Cleanup */
1732 if (pShaIo)
1733 RTMemFree(pShaIo);
1734 if (pTarIo)
1735 RTMemFree(pTarIo);
1736
1737 /* Delete ova file on error */
1738 if (FAILED(rc))
1739 RTFileDelete(pTask->locInfo.strPath.c_str());
1740
1741 LogFlowFuncLeave();
1742 return rc;
1743}
1744
1745HRESULT Appliance::writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
1746{
1747 LogFlowFuncEnter();
1748
1749 HRESULT rc = S_OK;
1750
1751 list<STRPAIR> fileList;
1752 try
1753 {
1754 int vrc;
1755 // the XML stack contains two maps for disks and networks, which allows us to
1756 // a) have a list of unique disk names (to make sure the same disk name is only added once)
1757 // and b) keep a list of all networks
1758 XMLStack stack;
1759 // Scope this to free the memory as soon as this is finished
1760 {
1761 // Create a xml document
1762 xml::Document doc;
1763 // Now fully build a valid ovf document in memory
1764 buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
1765 /* Extract the path */
1766 Utf8Str strOvfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".ovf");
1767 // Create a memory buffer containing the XML. */
1768 void *pvBuf = 0;
1769 size_t cbSize;
1770 xml::XmlMemWriter writer;
1771 writer.write(doc, &pvBuf, &cbSize);
1772 if (RT_UNLIKELY(!pvBuf))
1773 throw setError(VBOX_E_FILE_ERROR,
1774 tr("Could not create OVF file '%s'"),
1775 strOvfFile.c_str());
1776 /* Write the ovf file to disk. */
1777 vrc = ShaWriteBuf(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
1778 if (RT_FAILURE(vrc))
1779 throw setError(VBOX_E_FILE_ERROR,
1780 tr("Could not create OVF file '%s' (%Rrc)"),
1781 strOvfFile.c_str(), vrc);
1782 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
1783 }
1784
1785 // We need a proper format description
1786 ComObjPtr<MediumFormat> format;
1787 // Scope for the AutoReadLock
1788 {
1789 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
1790 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
1791 // We are always exporting to VMDK stream optimized for now
1792 format = pSysProps->mediumFormat("VMDK");
1793 if (format.isNull())
1794 throw setError(VBOX_E_NOT_SUPPORTED,
1795 tr("Invalid medium storage format"));
1796 }
1797
1798 // Finally, write out the disks!
1799 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
1800 for (itS = stack.mapDisks.begin();
1801 itS != stack.mapDisks.end();
1802 ++itS)
1803 {
1804 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
1805
1806 // source path: where the VBox image is
1807 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
1808
1809 // Do NOT check here whether the file exists. findHardDisk will
1810 // figure that out, and filesystem-based tests are simply wrong
1811 // in the general case (think of iSCSI).
1812
1813 // clone the disk:
1814 ComObjPtr<Medium> pSourceDisk;
1815
1816 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
1817 rc = mVirtualBox->findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
1818 if (FAILED(rc)) throw rc;
1819
1820 Bstr uuidSource;
1821 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1822 if (FAILED(rc)) throw rc;
1823 Guid guidSource(uuidSource);
1824
1825 // output filename
1826 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1827 // target path needs to be composed from where the output OVF is
1828 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
1829 strTargetFilePath.stripFilename()
1830 .append("/")
1831 .append(strTargetFileNameOnly);
1832
1833 // The exporting requests a lock on the media tree. So leave our lock temporary.
1834 writeLock.release();
1835 try
1836 {
1837 ComObjPtr<Progress> pProgress2;
1838 pProgress2.createObject();
1839 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetFilePath.c_str()).raw(), TRUE);
1840 if (FAILED(rc)) throw rc;
1841
1842 // advance to the next operation
1843 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"), RTPathFilename(strTargetFilePath.c_str())).raw(),
1844 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally
1845
1846 // create a flat copy of the source disk image
1847 rc = pSourceDisk->exportFile(strTargetFilePath.c_str(), format, MediumVariant_VmdkStreamOptimized, pIfIo, pStorage, pProgress2);
1848 if (FAILED(rc)) throw rc;
1849
1850 ComPtr<IProgress> pProgress3(pProgress2);
1851 // now wait for the background disk operation to complete; this throws HRESULTs on error
1852 waitForAsyncProgress(pTask->pProgress, pProgress3);
1853 }
1854 catch (HRESULT rc3)
1855 {
1856 writeLock.acquire();
1857 // Todo: file deletion on error? If not, we can remove that whole try/catch block.
1858 throw rc3;
1859 }
1860 // Finished, lock again (so nobody mess around with the medium tree
1861 // in the meantime)
1862 writeLock.acquire();
1863 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
1864 }
1865
1866 if (m->fManifest)
1867 {
1868 // Create & write the manifest file
1869 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1870 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
1871 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
1872 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally);
1873 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
1874 size_t i = 0;
1875 list<STRPAIR>::const_iterator it1;
1876 for (it1 = fileList.begin();
1877 it1 != fileList.end();
1878 ++it1, ++i)
1879 {
1880 paManifestFiles[i].pszTestFile = (*it1).first.c_str();
1881 paManifestFiles[i].pszTestDigest = (*it1).second.c_str();
1882 }
1883 void *pvBuf;
1884 size_t cbSize;
1885 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
1886 paManifestFiles, fileList.size());
1887 RTMemFree(paManifestFiles);
1888 if (RT_FAILURE(vrc))
1889 throw setError(VBOX_E_FILE_ERROR,
1890 tr("Could not create manifest file '%s' (%Rrc)"),
1891 strMfFileName.c_str(), vrc);
1892 /* Disable digest creation for the manifest file. */
1893 pStorage->fCreateDigest = false;
1894 /* Write the manifest file to disk. */
1895 vrc = ShaWriteBuf(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
1896 RTMemFree(pvBuf);
1897 if (RT_FAILURE(vrc))
1898 throw setError(VBOX_E_FILE_ERROR,
1899 tr("Could not create manifest file '%s' (%Rrc)"),
1900 strMfFilePath.c_str(), vrc);
1901 }
1902 }
1903 catch (RTCError &x) // includes all XML exceptions
1904 {
1905 rc = setError(VBOX_E_FILE_ERROR,
1906 x.what());
1907 }
1908 catch (HRESULT aRC)
1909 {
1910 rc = aRC;
1911 }
1912
1913 /* Cleanup on error */
1914 if (FAILED(rc))
1915 {
1916 list<STRPAIR>::const_iterator it1;
1917 for (it1 = fileList.begin();
1918 it1 != fileList.end();
1919 ++it1)
1920 pIfIo->pfnDelete(pStorage, (*it1).first.c_str());
1921 }
1922
1923 LogFlowFunc(("rc=%Rhrc\n", rc));
1924 LogFlowFuncLeave();
1925
1926 return rc;
1927}
1928
1929#ifdef VBOX_WITH_S3
1930/**
1931 * Worker code for writing out OVF to the cloud. This is called from Appliance::taskThreadWriteOVF()
1932 * in S3 mode and therefore runs on the OVF write worker thread. This then starts a second worker
1933 * thread to create temporary files (see Appliance::writeFS()).
1934 *
1935 * @param pTask
1936 * @return
1937 */
1938HRESULT Appliance::writeS3(TaskOVF *pTask)
1939{
1940 LogFlowFuncEnter();
1941 LogFlowFunc(("Appliance %p\n", this));
1942
1943 AutoCaller autoCaller(this);
1944 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1945
1946 HRESULT rc = S_OK;
1947
1948 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1949
1950 int vrc = VINF_SUCCESS;
1951 RTS3 hS3 = NIL_RTS3;
1952 char szOSTmpDir[RTPATH_MAX];
1953 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1954 /* The template for the temporary directory created below */
1955 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1956 list< pair<Utf8Str, ULONG> > filesList;
1957
1958 // todo:
1959 // - usable error codes
1960 // - seems snapshot filenames are problematic {uuid}.vdi
1961 try
1962 {
1963 /* Extract the bucket */
1964 Utf8Str tmpPath = pTask->locInfo.strPath;
1965 Utf8Str bucket;
1966 parseBucket(tmpPath, bucket);
1967
1968 /* We need a temporary directory which we can put the OVF file & all
1969 * disk images in */
1970 vrc = RTDirCreateTemp(pszTmpDir, 0700);
1971 if (RT_FAILURE(vrc))
1972 throw setError(VBOX_E_FILE_ERROR,
1973 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1974
1975 /* The temporary name of the target OVF file */
1976 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1977
1978 /* Prepare the temporary writing of the OVF */
1979 ComObjPtr<Progress> progress;
1980 /* Create a temporary file based location info for the sub task */
1981 LocationInfo li;
1982 li.strPath = strTmpOvf;
1983 rc = writeImpl(pTask->enFormat, li, progress);
1984 if (FAILED(rc)) throw rc;
1985
1986 /* Unlock the appliance for the writing thread */
1987 appLock.release();
1988 /* Wait until the writing is done, but report the progress back to the
1989 caller */
1990 ComPtr<IProgress> progressInt(progress);
1991 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1992
1993 /* Again lock the appliance for the next steps */
1994 appLock.acquire();
1995
1996 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
1997 if (RT_FAILURE(vrc))
1998 throw setError(VBOX_E_FILE_ERROR,
1999 tr("Cannot find source file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
2000 /* Add the OVF file */
2001 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightForXmlOperation)); /* Use 1% of the total for the OVF file upload */
2002 /* Add the manifest file */
2003 if (m->fManifest)
2004 {
2005 Utf8Str strMfFile = Utf8Str(strTmpOvf).stripExt().append(".mf");
2006 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightForXmlOperation)); /* Use 1% of the total for the manifest file upload */
2007 }
2008
2009 /* Now add every disks of every virtual system */
2010 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2011 for (it = m->virtualSystemDescriptions.begin();
2012 it != m->virtualSystemDescriptions.end();
2013 ++it)
2014 {
2015 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2016 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2017 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2018 for (itH = avsdeHDs.begin();
2019 itH != avsdeHDs.end();
2020 ++itH)
2021 {
2022 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
2023 /* Target path needs to be composed from where the output OVF is */
2024 Utf8Str strTargetFilePath(strTmpOvf);
2025 strTargetFilePath.stripFilename();
2026 strTargetFilePath.append("/");
2027 strTargetFilePath.append(strTargetFileNameOnly);
2028 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
2029 if (RT_FAILURE(vrc))
2030 throw setError(VBOX_E_FILE_ERROR,
2031 tr("Cannot find source file '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2032 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
2033 }
2034 }
2035 /* Next we have to upload the OVF & all disk images */
2036 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2037 if (RT_FAILURE(vrc))
2038 throw setError(VBOX_E_IPRT_ERROR,
2039 tr("Cannot create S3 service handler"));
2040 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2041
2042 /* Upload all files */
2043 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2044 {
2045 const pair<Utf8Str, ULONG> &s = (*it1);
2046 char *pszFilename = RTPathFilename(s.first.c_str());
2047 /* Advance to the next operation */
2048 pTask->pProgress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename).raw(), s.second);
2049 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
2050 if (RT_FAILURE(vrc))
2051 {
2052 if (vrc == VERR_S3_CANCELED)
2053 break;
2054 else if (vrc == VERR_S3_ACCESS_DENIED)
2055 throw setError(E_ACCESSDENIED,
2056 tr("Cannot upload file '%s' to S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
2057 else if (vrc == VERR_S3_NOT_FOUND)
2058 throw setError(VBOX_E_FILE_ERROR,
2059 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
2060 else
2061 throw setError(VBOX_E_IPRT_ERROR,
2062 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
2063 }
2064 }
2065 }
2066 catch(HRESULT aRC)
2067 {
2068 rc = aRC;
2069 }
2070 /* Cleanup */
2071 RTS3Destroy(hS3);
2072 /* Delete all files which where temporary created */
2073 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2074 {
2075 const char *pszFilePath = (*it1).first.c_str();
2076 if (RTPathExists(pszFilePath))
2077 {
2078 vrc = RTFileDelete(pszFilePath);
2079 if (RT_FAILURE(vrc))
2080 rc = setError(VBOX_E_FILE_ERROR,
2081 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2082 }
2083 }
2084 /* Delete the temporary directory */
2085 if (RTPathExists(pszTmpDir))
2086 {
2087 vrc = RTDirRemove(pszTmpDir);
2088 if (RT_FAILURE(vrc))
2089 rc = setError(VBOX_E_FILE_ERROR,
2090 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2091 }
2092 if (pszTmpDir)
2093 RTStrFree(pszTmpDir);
2094
2095 LogFlowFunc(("rc=%Rhrc\n", rc));
2096 LogFlowFuncLeave();
2097
2098 return rc;
2099}
2100#endif /* VBOX_WITH_S3 */
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