VirtualBox

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

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

Main: a couple of whitespace fixes

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