VirtualBox

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

Last change on this file since 41105 was 41105, checked in by vboxsync, 13 years ago

use openMedium instead of findMedium

  • 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 41105 2012-05-01 18:14:46Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2011 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::Export(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 OVFFormat ovfF;
556 if (strFormat == "ovf-0.9")
557 ovfF = OVF_0_9;
558 else if (strFormat == "ovf-1.0")
559 ovfF = OVF_1_0;
560 else if (strFormat == "ovf-2.0")
561 ovfF = OVF_2_0;
562 else
563 return setError(VBOX_E_FILE_ERROR,
564 tr("Invalid format \"%s\" specified"), strFormat.c_str());
565
566 /* as of OVF 2.0 we have to use SHA256 */
567 m->fSha256 = ovfF >= OVF_2_0;
568
569 ComObjPtr<Progress> progress;
570 HRESULT rc = S_OK;
571 try
572 {
573 /* Parse all necessary info out of the URI */
574 parseURI(strPath, m->locInfo);
575 rc = writeImpl(ovfF, m->locInfo, progress);
576 }
577 catch (HRESULT aRC)
578 {
579 rc = aRC;
580 }
581
582 if (SUCCEEDED(rc))
583 /* Return progress to the caller */
584 progress.queryInterfaceTo(aProgress);
585
586 return rc;
587}
588
589////////////////////////////////////////////////////////////////////////////////
590//
591// Appliance private methods
592//
593////////////////////////////////////////////////////////////////////////////////
594
595/*******************************************************************************
596 * Export stuff
597 ******************************************************************************/
598
599/**
600 * Implementation for writing out the OVF to disk. This starts a new thread which will call
601 * Appliance::taskThreadWriteOVF().
602 *
603 * This is in a separate private method because it is used from two locations:
604 *
605 * 1) from the public Appliance::Write().
606 *
607 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
608 * called Appliance::writeFSOVA(), which called Appliance::writeImpl(), which then called this again.
609 *
610 * 3) from Appliance::writeS3(), which got called from a previous instance of Appliance::taskThreadWriteOVF().
611 *
612 * @param aFormat
613 * @param aLocInfo
614 * @param aProgress
615 * @return
616 */
617HRESULT Appliance::writeImpl(OVFFormat aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
618{
619 HRESULT rc = S_OK;
620 try
621 {
622 rc = setUpProgress(aProgress,
623 BstrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
624 (aLocInfo.storageType == VFSType_File) ? WriteFile : WriteS3);
625
626 /* Initialize our worker task */
627 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress));
628 /* The OVF version to write */
629 task->enFormat = aFormat;
630
631 rc = task->startThread();
632 if (FAILED(rc)) throw rc;
633
634 /* Don't destruct on success */
635 task.release();
636 }
637 catch (HRESULT aRC)
638 {
639 rc = aRC;
640 }
641
642 return rc;
643}
644
645/**
646 * Called from Appliance::writeFS() for creating a XML document for this
647 * Appliance.
648 *
649 * @param writeLock The current write lock.
650 * @param doc The xml document to fill.
651 * @param stack Structure for temporary private
652 * data shared with caller.
653 * @param strPath Path to the target OVF.
654 * instance for which to write XML.
655 * @param enFormat OVF format (0.9 or 1.0).
656 */
657void Appliance::buildXML(AutoWriteLockBase& writeLock,
658 xml::Document &doc,
659 XMLStack &stack,
660 const Utf8Str &strPath,
661 OVFFormat enFormat)
662{
663 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
664
665 pelmRoot->setAttribute("ovf:version", enFormat == OVF_2_0 ? "2.0"
666 : enFormat == OVF_1_0 ? "1.0"
667 : "0.9");
668 pelmRoot->setAttribute("xml:lang", "en-US");
669
670 Utf8Str strNamespace = (enFormat == OVF_0_9)
671 ? "http://www.vmware.com/schema/ovf/1/envelope" // 0.9
672 : "http://schemas.dmtf.org/ovf/envelope/1"; // 1.0
673 pelmRoot->setAttribute("xmlns", strNamespace);
674 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
675
676 // pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
677 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
678 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
679 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
680 pelmRoot->setAttribute("xmlns:vbox", "http://www.virtualbox.org/ovf/machine");
681 // pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
682
683 // <Envelope>/<References>
684 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
685
686 /* <Envelope>/<DiskSection>:
687 <DiskSection>
688 <Info>List of the virtual disks used in the package</Info>
689 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
690 </DiskSection> */
691 xml::ElementNode *pelmDiskSection;
692 if (enFormat == OVF_0_9)
693 {
694 // <Section xsi:type="ovf:DiskSection_Type">
695 pelmDiskSection = pelmRoot->createChild("Section");
696 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
697 }
698 else
699 pelmDiskSection = pelmRoot->createChild("DiskSection");
700
701 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
702 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
703
704 /* <Envelope>/<NetworkSection>:
705 <NetworkSection>
706 <Info>Logical networks used in the package</Info>
707 <Network ovf:name="VM Network">
708 <Description>The network that the LAMP Service will be available on</Description>
709 </Network>
710 </NetworkSection> */
711 xml::ElementNode *pelmNetworkSection;
712 if (enFormat == OVF_0_9)
713 {
714 // <Section xsi:type="ovf:NetworkSection_Type">
715 pelmNetworkSection = pelmRoot->createChild("Section");
716 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
717 }
718 else
719 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
720
721 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
722 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
723
724 // and here come the virtual systems:
725
726 // write a collection if we have more than one virtual system _and_ we're
727 // writing OVF 1.0; otherwise fail since ovftool can't import more than
728 // one machine, it seems
729 xml::ElementNode *pelmToAddVirtualSystemsTo;
730 if (m->virtualSystemDescriptions.size() > 1)
731 {
732 if (enFormat == OVF_0_9)
733 throw setError(VBOX_E_FILE_ERROR,
734 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
735
736 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
737 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
738 }
739 else
740 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
741
742 // this list receives pointers to the XML elements in the machine XML which
743 // might have UUIDs that need fixing after we know the UUIDs of the exported images
744 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
745
746 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
747 /* Iterate through all virtual systems of that appliance */
748 for (it = m->virtualSystemDescriptions.begin();
749 it != m->virtualSystemDescriptions.end();
750 ++it)
751 {
752 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
753 buildXMLForOneVirtualSystem(writeLock,
754 *pelmToAddVirtualSystemsTo,
755 &llElementsWithUuidAttributes,
756 vsdescThis,
757 enFormat,
758 stack); // disks and networks stack
759 }
760
761 // now, fill in the network section we set up empty above according
762 // to the networks we found with the hardware items
763 map<Utf8Str, bool>::const_iterator itN;
764 for (itN = stack.mapNetworks.begin();
765 itN != stack.mapNetworks.end();
766 ++itN)
767 {
768 const Utf8Str &strNetwork = itN->first;
769 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
770 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
771 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
772 }
773
774 // Finally, write out the disk info
775 list<Utf8Str> diskList;
776 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
777 uint32_t ulFile = 1;
778 for (itS = stack.mapDisks.begin();
779 itS != stack.mapDisks.end();
780 ++itS)
781 {
782 const Utf8Str &strDiskID = itS->first;
783 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
784
785 // source path: where the VBox image is
786 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
787 Bstr bstrSrcFilePath(strSrcFilePath);
788
789 // Do NOT check here whether the file exists. FindMedium will figure
790 // that out, and filesystem-based tests are simply wrong in the
791 // general case (think of iSCSI).
792
793 // We need some info from the source disks
794 ComPtr<IMedium> pSourceDisk;
795
796 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
797
798#if 0 // Substitute call to FindMedium to OpenMedium
799 HRESULT rc = mVirtualBox->FindMedium(bstrSrcFilePath.raw(), DeviceType_HardDisk, pSourceDisk.asOutParam());
800#endif
801 HRESULT rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
802 DeviceType_HardDisk,
803 AccessMode_ReadWrite,
804 FALSE /* fForceNewUuid */,
805 pSourceDisk.asOutParam());
806 if (FAILED(rc)) throw rc;
807
808 Bstr uuidSource;
809 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
810 if (FAILED(rc)) throw rc;
811 Guid guidSource(uuidSource);
812
813 // output filename
814 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
815 // target path needs to be composed from where the output OVF is
816 Utf8Str strTargetFilePath(strPath);
817 strTargetFilePath.stripFilename();
818 strTargetFilePath.append("/");
819 strTargetFilePath.append(strTargetFileNameOnly);
820
821 // We are always exporting to VMDK stream optimized for now
822 Bstr bstrSrcFormat = L"VMDK";
823
824 diskList.push_back(strTargetFilePath);
825
826 LONG64 cbCapacity = 0; // size reported to guest
827 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
828 if (FAILED(rc)) throw rc;
829 // Todo r=poetzsch: wrong it is reported in bytes ...
830 // capacity is reported in megabytes, so...
831 //cbCapacity *= _1M;
832
833 Guid guidTarget; /* Creates a new uniq number for the target disk. */
834 guidTarget.create();
835
836 // now handle the XML for the disk:
837 Utf8StrFmt strFileRef("file%RI32", ulFile++);
838 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
839 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
840 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
841 pelmFile->setAttribute("ovf:id", strFileRef);
842 // Todo: the actual size is not available at this point of time,
843 // cause the disk will be compressed. The 1.0 standard says this is
844 // optional! 1.1 isn't fully clear if the "gzip" format is used.
845 // Need to be checked. */
846 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
847
848 // add disk to XML Disks section
849 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
850 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
851 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
852 pelmDisk->setAttribute("ovf:diskId", strDiskID);
853 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
854 pelmDisk->setAttribute("ovf:format",
855 (enFormat == OVF_0_9)
856 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftool chokes
857 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
858 // correct string as communicated to us by VMware (public bug #6612)
859 );
860
861 // add the UUID of the newly target image to the OVF disk element, but in the
862 // vbox: namespace since it's not part of the standard
863 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
864
865 // now, we might have other XML elements from vbox:Machine pointing to this image,
866 // but those would refer to the UUID of the _source_ image (which we created the
867 // export image from); those UUIDs need to be fixed to the export image
868 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
869 for (std::list<xml::ElementNode*>::iterator eit = llElementsWithUuidAttributes.begin();
870 eit != llElementsWithUuidAttributes.end();
871 ++eit)
872 {
873 xml::ElementNode *pelmImage = *eit;
874 Utf8Str strUUID;
875 pelmImage->getAttributeValue("uuid", strUUID);
876 if (strUUID == strGuidSourceCurly)
877 // overwrite existing uuid attribute
878 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
879 }
880 }
881}
882
883/**
884 * Called from Appliance::buildXML() for each virtual system (machine) that
885 * needs XML written out.
886 *
887 * @param writeLock The current write lock.
888 * @param elmToAddVirtualSystemsTo XML element to append elements to.
889 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
890 * with UUID attributes for quick
891 * fixing by caller later
892 * @param vsdescThis The IVirtualSystemDescription
893 * instance for which to write XML.
894 * @param enFormat OVF format (0.9 or 1.0).
895 * @param stack Structure for temporary private
896 * data shared with caller.
897 */
898void Appliance::buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
899 xml::ElementNode &elmToAddVirtualSystemsTo,
900 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
901 ComObjPtr<VirtualSystemDescription> &vsdescThis,
902 OVFFormat enFormat,
903 XMLStack &stack)
904{
905 LogFlowFunc(("ENTER appliance %p\n", this));
906
907 xml::ElementNode *pelmVirtualSystem;
908 if (enFormat == OVF_0_9)
909 {
910 // <Section xsi:type="ovf:NetworkSection_Type">
911 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
912 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
913 }
914 else
915 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
916
917 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
918
919 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
920 if (llName.size() != 1)
921 throw setError(VBOX_E_NOT_SUPPORTED,
922 tr("Missing VM name"));
923 Utf8Str &strVMName = llName.front()->strVboxCurrent;
924 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
925
926 // product info
927 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
928 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
929 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
930 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
931 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
932 bool fProduct = llProduct.size() && !llProduct.front()->strVboxCurrent.isEmpty();
933 bool fProductUrl = llProductUrl.size() && !llProductUrl.front()->strVboxCurrent.isEmpty();
934 bool fVendor = llVendor.size() && !llVendor.front()->strVboxCurrent.isEmpty();
935 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.front()->strVboxCurrent.isEmpty();
936 bool fVersion = llVersion.size() && !llVersion.front()->strVboxCurrent.isEmpty();
937 if (fProduct ||
938 fProductUrl ||
939 fVersion ||
940 fVendorUrl ||
941 fVersion)
942 {
943 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
944 <Info>Meta-information about the installed software</Info>
945 <Product>VAtest</Product>
946 <Vendor>SUN Microsystems</Vendor>
947 <Version>10.0</Version>
948 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
949 <VendorUrl>http://www.sun.com</VendorUrl>
950 </Section> */
951 xml::ElementNode *pelmAnnotationSection;
952 if (enFormat == OVF_0_9)
953 {
954 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
955 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
956 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
957 }
958 else
959 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
960
961 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
962 if (fProduct)
963 pelmAnnotationSection->createChild("Product")->addContent(llProduct.front()->strVboxCurrent);
964 if (fVendor)
965 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.front()->strVboxCurrent);
966 if (fVersion)
967 pelmAnnotationSection->createChild("Version")->addContent(llVersion.front()->strVboxCurrent);
968 if (fProductUrl)
969 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.front()->strVboxCurrent);
970 if (fVendorUrl)
971 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.front()->strVboxCurrent);
972 }
973
974 // description
975 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
976 if (llDescription.size() &&
977 !llDescription.front()->strVboxCurrent.isEmpty())
978 {
979 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
980 <Info>A human-readable annotation</Info>
981 <Annotation>Plan 9</Annotation>
982 </Section> */
983 xml::ElementNode *pelmAnnotationSection;
984 if (enFormat == OVF_0_9)
985 {
986 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
987 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
988 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
989 }
990 else
991 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
992
993 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
994 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.front()->strVboxCurrent);
995 }
996
997 // license
998 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
999 if (llLicense.size() &&
1000 !llLicense.front()->strVboxCurrent.isEmpty())
1001 {
1002 /* <EulaSection>
1003 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1004 <License ovf:msgid="1">License terms can go in here.</License>
1005 </EulaSection> */
1006 xml::ElementNode *pelmEulaSection;
1007 if (enFormat == OVF_0_9)
1008 {
1009 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1010 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1011 }
1012 else
1013 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1014
1015 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1016 pelmEulaSection->createChild("License")->addContent(llLicense.front()->strVboxCurrent);
1017 }
1018
1019 // operating system
1020 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1021 if (llOS.size() != 1)
1022 throw setError(VBOX_E_NOT_SUPPORTED,
1023 tr("Missing OS type"));
1024 /* <OperatingSystemSection ovf:id="82">
1025 <Info>Guest Operating System</Info>
1026 <Description>Linux 2.6.x</Description>
1027 </OperatingSystemSection> */
1028 VirtualSystemDescriptionEntry *pvsdeOS = llOS.front();
1029 xml::ElementNode *pelmOperatingSystemSection;
1030 if (enFormat == OVF_0_9)
1031 {
1032 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1033 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1034 }
1035 else
1036 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1037
1038 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1039 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1040 Utf8Str strOSDesc;
1041 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1042 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1043 // add the VirtualBox ostype in a custom tag in a different namespace
1044 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1045 pelmVBoxOSType->setAttribute("ovf:required", "false");
1046 pelmVBoxOSType->addContent(pvsdeOS->strVboxCurrent);
1047
1048 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1049 xml::ElementNode *pelmVirtualHardwareSection;
1050 if (enFormat == OVF_0_9)
1051 {
1052 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1053 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1054 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1055 }
1056 else
1057 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1058
1059 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1060
1061 /* <System>
1062 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1063 <vssd:ElementName>vmware</vssd:ElementName>
1064 <vssd:InstanceID>1</vssd:InstanceID>
1065 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1066 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1067 </System> */
1068 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1069
1070 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1071
1072 // <vssd:InstanceId>0</vssd:InstanceId>
1073 if (enFormat == OVF_0_9)
1074 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1075 else // capitalization changed...
1076 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1077
1078 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1079 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1080 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1081 const char *pcszHardware = "virtualbox-2.2";
1082 if (enFormat == OVF_0_9)
1083 // pretend to be vmware compatible then
1084 pcszHardware = "vmx-6";
1085 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1086
1087 // loop thru all description entries twice; once to write out all
1088 // devices _except_ disk images, and a second time to assign the
1089 // disk images; this is because disk images need to reference
1090 // IDE controllers, and we can't know their instance IDs without
1091 // assigning them first
1092
1093 uint32_t idIDEPrimaryController = 0;
1094 int32_t lIDEPrimaryControllerIndex = 0;
1095 uint32_t idIDESecondaryController = 0;
1096 int32_t lIDESecondaryControllerIndex = 0;
1097 uint32_t idSATAController = 0;
1098 int32_t lSATAControllerIndex = 0;
1099 uint32_t idSCSIController = 0;
1100 int32_t lSCSIControllerIndex = 0;
1101
1102 uint32_t ulInstanceID = 1;
1103
1104 uint32_t cDVDs = 0;
1105
1106 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1107 {
1108 int32_t lIndexThis = 0;
1109 list<VirtualSystemDescriptionEntry>::const_iterator itD;
1110 for (itD = vsdescThis->m->llDescriptions.begin();
1111 itD != vsdescThis->m->llDescriptions.end();
1112 ++itD, ++lIndexThis)
1113 {
1114 const VirtualSystemDescriptionEntry &desc = *itD;
1115
1116 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVbox=%s, strExtraConfig=%s\n",
1117 uLoop,
1118 desc.ulIndex,
1119 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1120 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1121 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1122 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1123 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1124 : Utf8StrFmt("%d", desc.type).c_str()),
1125 desc.strRef.c_str(),
1126 desc.strOvf.c_str(),
1127 desc.strVboxCurrent.c_str(),
1128 desc.strExtraConfigCurrent.c_str()));
1129
1130 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1131 Utf8Str strResourceSubType;
1132
1133 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1134 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1135
1136 uint32_t ulParent = 0;
1137
1138 int32_t lVirtualQuantity = -1;
1139 Utf8Str strAllocationUnits;
1140
1141 int32_t lAddress = -1;
1142 int32_t lBusNumber = -1;
1143 int32_t lAddressOnParent = -1;
1144
1145 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1146 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1147 Utf8Str strHostResource;
1148
1149 uint64_t uTemp;
1150
1151 switch (desc.type)
1152 {
1153 case VirtualSystemDescriptionType_CPU:
1154 /* <Item>
1155 <rasd:Caption>1 virtual CPU</rasd:Caption>
1156 <rasd:Description>Number of virtual CPUs</rasd:Description>
1157 <rasd:ElementName>virtual CPU</rasd:ElementName>
1158 <rasd:InstanceID>1</rasd:InstanceID>
1159 <rasd:ResourceType>3</rasd:ResourceType>
1160 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1161 </Item> */
1162 if (uLoop == 1)
1163 {
1164 strDescription = "Number of virtual CPUs";
1165 type = ovf::ResourceType_Processor; // 3
1166 desc.strVboxCurrent.toInt(uTemp);
1167 lVirtualQuantity = (int32_t)uTemp;
1168 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
1169 }
1170 break;
1171
1172 case VirtualSystemDescriptionType_Memory:
1173 /* <Item>
1174 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1175 <rasd:Caption>256 MB of memory</rasd:Caption>
1176 <rasd:Description>Memory Size</rasd:Description>
1177 <rasd:ElementName>Memory</rasd:ElementName>
1178 <rasd:InstanceID>2</rasd:InstanceID>
1179 <rasd:ResourceType>4</rasd:ResourceType>
1180 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1181 </Item> */
1182 if (uLoop == 1)
1183 {
1184 strDescription = "Memory Size";
1185 type = ovf::ResourceType_Memory; // 4
1186 desc.strVboxCurrent.toInt(uTemp);
1187 lVirtualQuantity = (int32_t)(uTemp / _1M);
1188 strAllocationUnits = "MegaBytes";
1189 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
1190 }
1191 break;
1192
1193 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1194 /* <Item>
1195 <rasd:Caption>ideController1</rasd:Caption>
1196 <rasd:Description>IDE Controller</rasd:Description>
1197 <rasd:InstanceId>5</rasd:InstanceId>
1198 <rasd:ResourceType>5</rasd:ResourceType>
1199 <rasd:Address>1</rasd:Address>
1200 <rasd:BusNumber>1</rasd:BusNumber>
1201 </Item> */
1202 if (uLoop == 1)
1203 {
1204 strDescription = "IDE Controller";
1205 type = ovf::ResourceType_IDEController; // 5
1206 strResourceSubType = desc.strVboxCurrent;
1207
1208 if (!lIDEPrimaryControllerIndex)
1209 {
1210 // first IDE controller:
1211 strCaption = "ideController0";
1212 lAddress = 0;
1213 lBusNumber = 0;
1214 // remember this ID
1215 idIDEPrimaryController = ulInstanceID;
1216 lIDEPrimaryControllerIndex = lIndexThis;
1217 }
1218 else
1219 {
1220 // second IDE controller:
1221 strCaption = "ideController1";
1222 lAddress = 1;
1223 lBusNumber = 1;
1224 // remember this ID
1225 idIDESecondaryController = ulInstanceID;
1226 lIDESecondaryControllerIndex = lIndexThis;
1227 }
1228 }
1229 break;
1230
1231 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1232 /* <Item>
1233 <rasd:Caption>sataController0</rasd:Caption>
1234 <rasd:Description>SATA Controller</rasd:Description>
1235 <rasd:InstanceId>4</rasd:InstanceId>
1236 <rasd:ResourceType>20</rasd:ResourceType>
1237 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1238 <rasd:Address>0</rasd:Address>
1239 <rasd:BusNumber>0</rasd:BusNumber>
1240 </Item>
1241 */
1242 if (uLoop == 1)
1243 {
1244 strDescription = "SATA Controller";
1245 strCaption = "sataController0";
1246 type = ovf::ResourceType_OtherStorageDevice; // 20
1247 // it seems that OVFTool always writes these two, and since we can only
1248 // have one SATA controller, we'll use this as well
1249 lAddress = 0;
1250 lBusNumber = 0;
1251
1252 if ( desc.strVboxCurrent.isEmpty() // AHCI is the default in VirtualBox
1253 || (!desc.strVboxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1254 )
1255 strResourceSubType = "AHCI";
1256 else
1257 throw setError(VBOX_E_NOT_SUPPORTED,
1258 tr("Invalid config string \"%s\" in SATA controller"), desc.strVboxCurrent.c_str());
1259
1260 // remember this ID
1261 idSATAController = ulInstanceID;
1262 lSATAControllerIndex = lIndexThis;
1263 }
1264 break;
1265
1266 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1267 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1268 /* <Item>
1269 <rasd:Caption>scsiController0</rasd:Caption>
1270 <rasd:Description>SCSI Controller</rasd:Description>
1271 <rasd:InstanceId>4</rasd:InstanceId>
1272 <rasd:ResourceType>6</rasd:ResourceType>
1273 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1274 <rasd:Address>0</rasd:Address>
1275 <rasd:BusNumber>0</rasd:BusNumber>
1276 </Item>
1277 */
1278 if (uLoop == 1)
1279 {
1280 strDescription = "SCSI Controller";
1281 strCaption = "scsiController0";
1282 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1283 // it seems that OVFTool always writes these two, and since we can only
1284 // have one SATA controller, we'll use this as well
1285 lAddress = 0;
1286 lBusNumber = 0;
1287
1288 if ( desc.strVboxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1289 || (!desc.strVboxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1290 )
1291 strResourceSubType = "lsilogic";
1292 else if (!desc.strVboxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1293 strResourceSubType = "buslogic";
1294 else if (!desc.strVboxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1295 strResourceSubType = "lsilogicsas";
1296 else
1297 throw setError(VBOX_E_NOT_SUPPORTED,
1298 tr("Invalid config string \"%s\" in SCSI/SAS controller"), desc.strVboxCurrent.c_str());
1299
1300 // remember this ID
1301 idSCSIController = ulInstanceID;
1302 lSCSIControllerIndex = lIndexThis;
1303 }
1304 break;
1305
1306 case VirtualSystemDescriptionType_HardDiskImage:
1307 /* <Item>
1308 <rasd:Caption>disk1</rasd:Caption>
1309 <rasd:InstanceId>8</rasd:InstanceId>
1310 <rasd:ResourceType>17</rasd:ResourceType>
1311 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1312 <rasd:Parent>4</rasd:Parent>
1313 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1314 </Item> */
1315 if (uLoop == 2)
1316 {
1317 uint32_t cDisks = stack.mapDisks.size();
1318 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1319
1320 strDescription = "Disk Image";
1321 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1322 type = ovf::ResourceType_HardDisk; // 17
1323
1324 // the following references the "<Disks>" XML block
1325 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1326
1327 // controller=<index>;channel=<c>
1328 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1329 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1330 int32_t lControllerIndex = -1;
1331 if (pos1 != Utf8Str::npos)
1332 {
1333 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1334 if (lControllerIndex == lIDEPrimaryControllerIndex)
1335 ulParent = idIDEPrimaryController;
1336 else if (lControllerIndex == lIDESecondaryControllerIndex)
1337 ulParent = idIDESecondaryController;
1338 else if (lControllerIndex == lSCSIControllerIndex)
1339 ulParent = idSCSIController;
1340 else if (lControllerIndex == lSATAControllerIndex)
1341 ulParent = idSATAController;
1342 }
1343 if (pos2 != Utf8Str::npos)
1344 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1345
1346 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1347 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1348
1349 if ( !ulParent
1350 || lAddressOnParent == -1
1351 )
1352 throw setError(VBOX_E_NOT_SUPPORTED,
1353 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfigCurrent.c_str());
1354
1355 stack.mapDisks[strDiskID] = &desc;
1356 }
1357 break;
1358
1359 case VirtualSystemDescriptionType_Floppy:
1360 if (uLoop == 1)
1361 {
1362 strDescription = "Floppy Drive";
1363 strCaption = "floppy0"; // this is what OVFTool writes
1364 type = ovf::ResourceType_FloppyDrive; // 14
1365 lAutomaticAllocation = 0;
1366 lAddressOnParent = 0; // this is what OVFTool writes
1367 }
1368 break;
1369
1370 case VirtualSystemDescriptionType_CDROM:
1371 if (uLoop == 2)
1372 {
1373 strDescription = "CD-ROM Drive";
1374 strCaption = Utf8StrFmt("cdrom%RI32", ++cDVDs); // OVFTool starts with 1
1375 type = ovf::ResourceType_CDDrive; // 15
1376 lAutomaticAllocation = 1;
1377
1378 // controller=<index>;channel=<c>
1379 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1380 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1381 int32_t lControllerIndex = -1;
1382 if (pos1 != Utf8Str::npos)
1383 {
1384 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1385 if (lControllerIndex == lIDEPrimaryControllerIndex)
1386 ulParent = idIDEPrimaryController;
1387 else if (lControllerIndex == lIDESecondaryControllerIndex)
1388 ulParent = idIDESecondaryController;
1389 else if (lControllerIndex == lSCSIControllerIndex)
1390 ulParent = idSCSIController;
1391 else if (lControllerIndex == lSATAControllerIndex)
1392 ulParent = idSATAController;
1393 }
1394 if (pos2 != Utf8Str::npos)
1395 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1396
1397 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1398 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1399
1400 if ( !ulParent
1401 || lAddressOnParent == -1
1402 )
1403 throw setError(VBOX_E_NOT_SUPPORTED,
1404 tr("Missing or bad extra config string in DVD drive medium: \"%s\""), desc.strExtraConfigCurrent.c_str());
1405
1406 // there is no DVD drive map to update because it is
1407 // handled completely with this entry.
1408 }
1409 break;
1410
1411 case VirtualSystemDescriptionType_NetworkAdapter:
1412 /* <Item>
1413 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1414 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1415 <rasd:Connection>VM Network</rasd:Connection>
1416 <rasd:ElementName>VM network</rasd:ElementName>
1417 <rasd:InstanceID>3</rasd:InstanceID>
1418 <rasd:ResourceType>10</rasd:ResourceType>
1419 </Item> */
1420 if (uLoop == 1)
1421 {
1422 lAutomaticAllocation = 1;
1423 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1424 type = ovf::ResourceType_EthernetAdapter; // 10
1425 /* Set the hardware type to something useful.
1426 * To be compatible with vmware & others we set
1427 * PCNet32 for our PCNet types & E1000 for the
1428 * E1000 cards. */
1429 switch (desc.strVboxCurrent.toInt32())
1430 {
1431 case NetworkAdapterType_Am79C970A:
1432 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1433#ifdef VBOX_WITH_E1000
1434 case NetworkAdapterType_I82540EM:
1435 case NetworkAdapterType_I82545EM:
1436 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1437#endif /* VBOX_WITH_E1000 */
1438 }
1439 strConnection = desc.strOvf;
1440
1441 stack.mapNetworks[desc.strOvf] = true;
1442 }
1443 break;
1444
1445 case VirtualSystemDescriptionType_USBController:
1446 /* <Item ovf:required="false">
1447 <rasd:Caption>usb</rasd:Caption>
1448 <rasd:Description>USB Controller</rasd:Description>
1449 <rasd:InstanceId>3</rasd:InstanceId>
1450 <rasd:ResourceType>23</rasd:ResourceType>
1451 <rasd:Address>0</rasd:Address>
1452 <rasd:BusNumber>0</rasd:BusNumber>
1453 </Item> */
1454 if (uLoop == 1)
1455 {
1456 strDescription = "USB Controller";
1457 strCaption = "usb";
1458 type = ovf::ResourceType_USBController; // 23
1459 lAddress = 0; // this is what OVFTool writes
1460 lBusNumber = 0; // this is what OVFTool writes
1461 }
1462 break;
1463
1464 case VirtualSystemDescriptionType_SoundCard:
1465 /* <Item ovf:required="false">
1466 <rasd:Caption>sound</rasd:Caption>
1467 <rasd:Description>Sound Card</rasd:Description>
1468 <rasd:InstanceId>10</rasd:InstanceId>
1469 <rasd:ResourceType>35</rasd:ResourceType>
1470 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1471 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1472 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1473 </Item> */
1474 if (uLoop == 1)
1475 {
1476 strDescription = "Sound Card";
1477 strCaption = "sound";
1478 type = ovf::ResourceType_SoundCard; // 35
1479 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1480 lAutomaticAllocation = 0;
1481 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1482 }
1483 break;
1484 }
1485
1486 if (type)
1487 {
1488 xml::ElementNode *pItem;
1489
1490 pItem = pelmVirtualHardwareSection->createChild("Item");
1491
1492 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1493 // the elements from the rasd: namespace must be sorted by letter, and VMware
1494 // actually requires this as well (see public bug #6612)
1495
1496 if (lAddress != -1)
1497 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1498
1499 if (lAddressOnParent != -1)
1500 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1501
1502 if (!strAllocationUnits.isEmpty())
1503 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1504
1505 if (lAutomaticAllocation != -1)
1506 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1507
1508 if (lBusNumber != -1)
1509 if (enFormat == OVF_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool compatibility
1510 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1511
1512 if (!strCaption.isEmpty())
1513 pItem->createChild("rasd:Caption")->addContent(strCaption);
1514
1515 if (!strConnection.isEmpty())
1516 pItem->createChild("rasd:Connection")->addContent(strConnection);
1517
1518 if (!strDescription.isEmpty())
1519 pItem->createChild("rasd:Description")->addContent(strDescription);
1520
1521 if (!strCaption.isEmpty())
1522 if (enFormat == OVF_1_0)
1523 pItem->createChild("rasd:ElementName")->addContent(strCaption);
1524
1525 if (!strHostResource.isEmpty())
1526 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1527
1528 // <rasd:InstanceID>1</rasd:InstanceID>
1529 xml::ElementNode *pelmInstanceID;
1530 if (enFormat == OVF_0_9)
1531 pelmInstanceID = pItem->createChild("rasd:InstanceId");
1532 else
1533 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1534 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
1535
1536 if (ulParent)
1537 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1538
1539 if (!strResourceSubType.isEmpty())
1540 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1541
1542 // <rasd:ResourceType>3</rasd:ResourceType>
1543 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1544
1545 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1546 if (lVirtualQuantity != -1)
1547 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1548 }
1549 }
1550 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1551
1552 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1553 // under the vbox: namespace
1554 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1555 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1556 pelmVBoxMachine->setAttribute("ovf:required", "false");
1557 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1558 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1559
1560 // create an empty machine config
1561 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(NULL);
1562
1563 writeLock.release();
1564 try
1565 {
1566 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1567 // fill the machine config
1568 vsdescThis->m->pMachine->copyMachineDataToSettings(*pConfig);
1569 // write the machine config to the vbox:Machine element
1570 pConfig->buildMachineXML(*pelmVBoxMachine,
1571 settings::MachineConfigFile::BuildMachineXML_WriteVboxVersionAttribute
1572 | settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia
1573 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
1574 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1575 pllElementsWithUuidAttributes);
1576 delete pConfig;
1577 }
1578 catch (...)
1579 {
1580 writeLock.acquire();
1581 delete pConfig;
1582 throw;
1583 }
1584 writeLock.acquire();
1585}
1586
1587/**
1588 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1589 * and therefore runs on the OVF/OVA write worker thread. This runs in two contexts:
1590 *
1591 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::writeImpl();
1592 *
1593 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
1594 * called Appliance::writeS3(), which called Appliance::writeImpl(), which then called this. In other
1595 * words, to write to the cloud, the first worker thread first starts a second worker thread to create
1596 * temporary files and then uploads them to the S3 cloud server.
1597 *
1598 * @param pTask
1599 * @return
1600 */
1601HRESULT Appliance::writeFS(TaskOVF *pTask)
1602{
1603 LogFlowFuncEnter();
1604 LogFlowFunc(("ENTER appliance %p\n", this));
1605
1606 AutoCaller autoCaller(this);
1607 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1608
1609 HRESULT rc = S_OK;
1610
1611 // Lock the media tree early to make sure nobody else tries to make changes
1612 // to the tree. Also lock the IAppliance object for writing.
1613 AutoMultiWriteLock2 multiLock(&mVirtualBox->getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1614 // Additional protect the IAppliance object, cause we leave the lock
1615 // when starting the disk export and we don't won't block other
1616 // callers on this lengthy operations.
1617 m->state = Data::ApplianceExporting;
1618
1619 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1620 rc = writeFSOVF(pTask, multiLock);
1621 else
1622 rc = writeFSOVA(pTask, multiLock);
1623
1624 // reset the state so others can call methods again
1625 m->state = Data::ApplianceIdle;
1626
1627 LogFlowFunc(("rc=%Rhrc\n", rc));
1628 LogFlowFuncLeave();
1629 return rc;
1630}
1631
1632HRESULT Appliance::writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1633{
1634 LogFlowFuncEnter();
1635
1636 HRESULT rc = S_OK;
1637
1638 PVDINTERFACEIO pShaIo = 0;
1639 PVDINTERFACEIO pFileIo = 0;
1640 do
1641 {
1642 pShaIo = ShaCreateInterface();
1643 if (!pShaIo)
1644 {
1645 rc = E_OUTOFMEMORY;
1646 break;
1647 }
1648 pFileIo = FileCreateInterface();
1649 if (!pFileIo)
1650 {
1651 rc = E_OUTOFMEMORY;
1652 break;
1653 }
1654
1655 SHASTORAGE storage;
1656 RT_ZERO(storage);
1657 storage.fCreateDigest = m->fManifest;
1658 storage.fSha256 = m->fSha256;
1659 int vrc = VDInterfaceAdd(&pFileIo->Core, "Appliance::IOFile",
1660 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1661 &storage.pVDImageIfaces);
1662 if (RT_FAILURE(vrc))
1663 {
1664 rc = E_FAIL;
1665 break;
1666 }
1667 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1668 }while(0);
1669
1670 /* Cleanup */
1671 if (pShaIo)
1672 RTMemFree(pShaIo);
1673 if (pFileIo)
1674 RTMemFree(pFileIo);
1675
1676 LogFlowFuncLeave();
1677 return rc;
1678}
1679
1680HRESULT Appliance::writeFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1681{
1682 LogFlowFuncEnter();
1683
1684 RTTAR tar;
1685 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL, false);
1686 if (RT_FAILURE(vrc))
1687 return setError(VBOX_E_FILE_ERROR,
1688 tr("Could not create OVA file '%s' (%Rrc)"),
1689 pTask->locInfo.strPath.c_str(), vrc);
1690
1691 HRESULT rc = S_OK;
1692
1693 PVDINTERFACEIO pShaIo = 0;
1694 PVDINTERFACEIO pTarIo = 0;
1695 do
1696 {
1697 pShaIo = ShaCreateInterface();
1698 if (!pShaIo)
1699 {
1700 rc = E_OUTOFMEMORY;
1701 break;
1702 }
1703 pTarIo = TarCreateInterface();
1704 if (!pTarIo)
1705 {
1706 rc = E_OUTOFMEMORY;
1707 break;
1708 }
1709 SHASTORAGE storage;
1710 RT_ZERO(storage);
1711 storage.fCreateDigest = m->fManifest;
1712 storage.fSha256 = m->fSha256;
1713 vrc = VDInterfaceAdd(&pTarIo->Core, "Appliance::IOTar",
1714 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
1715 &storage.pVDImageIfaces);
1716 if (RT_FAILURE(vrc))
1717 {
1718 rc = E_FAIL;
1719 break;
1720 }
1721 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1722 }while(0);
1723
1724 RTTarClose(tar);
1725
1726 /* Cleanup */
1727 if (pShaIo)
1728 RTMemFree(pShaIo);
1729 if (pTarIo)
1730 RTMemFree(pTarIo);
1731
1732 /* Delete ova file on error */
1733 if(FAILED(rc))
1734 RTFileDelete(pTask->locInfo.strPath.c_str());
1735
1736 LogFlowFuncLeave();
1737 return rc;
1738}
1739
1740HRESULT Appliance::writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
1741{
1742 LogFlowFuncEnter();
1743
1744 HRESULT rc = S_OK;
1745
1746 list<STRPAIR> fileList;
1747 try
1748 {
1749 int vrc;
1750 // the XML stack contains two maps for disks and networks, which allows us to
1751 // a) have a list of unique disk names (to make sure the same disk name is only added once)
1752 // and b) keep a list of all networks
1753 XMLStack stack;
1754 // Scope this to free the memory as soon as this is finished
1755 {
1756 // Create a xml document
1757 xml::Document doc;
1758 // Now fully build a valid ovf document in memory
1759 buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
1760 /* Extract the path */
1761 Utf8Str strOvfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".ovf");
1762 // Create a memory buffer containing the XML. */
1763 void *pvBuf = 0;
1764 size_t cbSize;
1765 xml::XmlMemWriter writer;
1766 writer.write(doc, &pvBuf, &cbSize);
1767 if (RT_UNLIKELY(!pvBuf))
1768 throw setError(VBOX_E_FILE_ERROR,
1769 tr("Could not create OVF file '%s'"),
1770 strOvfFile.c_str());
1771 /* Write the ovf file to disk. */
1772 vrc = ShaWriteBuf(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
1773 if (RT_FAILURE(vrc))
1774 throw setError(VBOX_E_FILE_ERROR,
1775 tr("Could not create OVF file '%s' (%Rrc)"),
1776 strOvfFile.c_str(), vrc);
1777 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
1778 }
1779
1780 // We need a proper format description
1781 ComObjPtr<MediumFormat> format;
1782 // Scope for the AutoReadLock
1783 {
1784 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
1785 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
1786 // We are always exporting to VMDK stream optimized for now
1787 format = pSysProps->mediumFormat("VMDK");
1788 if (format.isNull())
1789 throw setError(VBOX_E_NOT_SUPPORTED,
1790 tr("Invalid medium storage format"));
1791 }
1792
1793 // Finally, write out the disks!
1794 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
1795 for (itS = stack.mapDisks.begin();
1796 itS != stack.mapDisks.end();
1797 ++itS)
1798 {
1799 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
1800
1801 // source path: where the VBox image is
1802 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
1803
1804 // Do NOT check here whether the file exists. findHardDisk will
1805 // figure that out, and filesystem-based tests are simply wrong
1806 // in the general case (think of iSCSI).
1807
1808 // clone the disk:
1809 ComObjPtr<Medium> pSourceDisk;
1810
1811 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
1812 rc = mVirtualBox->findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
1813 if (FAILED(rc)) throw rc;
1814
1815 Bstr uuidSource;
1816 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1817 if (FAILED(rc)) throw rc;
1818 Guid guidSource(uuidSource);
1819
1820 // output filename
1821 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1822 // target path needs to be composed from where the output OVF is
1823 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
1824 strTargetFilePath.stripFilename()
1825 .append("/")
1826 .append(strTargetFileNameOnly);
1827
1828 // The exporting requests a lock on the media tree. So leave our lock temporary.
1829 writeLock.release();
1830 try
1831 {
1832 ComObjPtr<Progress> pProgress2;
1833 pProgress2.createObject();
1834 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetFilePath.c_str()).raw(), TRUE);
1835 if (FAILED(rc)) throw rc;
1836
1837 // advance to the next operation
1838 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"), RTPathFilename(strTargetFilePath.c_str())).raw(),
1839 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally
1840
1841 // create a flat copy of the source disk image
1842 rc = pSourceDisk->exportFile(strTargetFilePath.c_str(), format, MediumVariant_VmdkStreamOptimized, pIfIo, pStorage, pProgress2);
1843 if (FAILED(rc)) throw rc;
1844
1845 ComPtr<IProgress> pProgress3(pProgress2);
1846 // now wait for the background disk operation to complete; this throws HRESULTs on error
1847 waitForAsyncProgress(pTask->pProgress, pProgress3);
1848 }
1849 catch (HRESULT rc3)
1850 {
1851 writeLock.acquire();
1852 // Todo: file deletion on error? If not, we can remove that whole try/catch block.
1853 throw rc3;
1854 }
1855 // Finished, lock again (so nobody mess around with the medium tree
1856 // in the meantime)
1857 writeLock.acquire();
1858 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
1859 }
1860
1861 if (m->fManifest)
1862 {
1863 // Create & write the manifest file
1864 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1865 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
1866 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
1867 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally);
1868 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
1869 size_t i = 0;
1870 list<STRPAIR>::const_iterator it1;
1871 for (it1 = fileList.begin();
1872 it1 != fileList.end();
1873 ++it1, ++i)
1874 {
1875 paManifestFiles[i].pszTestFile = (*it1).first.c_str();
1876 paManifestFiles[i].pszTestDigest = (*it1).second.c_str();
1877 }
1878 void *pvBuf;
1879 size_t cbSize;
1880 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
1881 paManifestFiles, fileList.size());
1882 RTMemFree(paManifestFiles);
1883 if (RT_FAILURE(vrc))
1884 throw setError(VBOX_E_FILE_ERROR,
1885 tr("Could not create manifest file '%s' (%Rrc)"),
1886 strMfFileName.c_str(), vrc);
1887 /* Disable digest creation for the manifest file. */
1888 pStorage->fCreateDigest = false;
1889 /* Write the manifest file to disk. */
1890 vrc = ShaWriteBuf(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
1891 RTMemFree(pvBuf);
1892 if (RT_FAILURE(vrc))
1893 throw setError(VBOX_E_FILE_ERROR,
1894 tr("Could not create manifest file '%s' (%Rrc)"),
1895 strMfFilePath.c_str(), vrc);
1896 }
1897 }
1898 catch (RTCError &x) // includes all XML exceptions
1899 {
1900 rc = setError(VBOX_E_FILE_ERROR,
1901 x.what());
1902 }
1903 catch (HRESULT aRC)
1904 {
1905 rc = aRC;
1906 }
1907
1908 /* Cleanup on error */
1909 if (FAILED(rc))
1910 {
1911 list<STRPAIR>::const_iterator it1;
1912 for (it1 = fileList.begin();
1913 it1 != fileList.end();
1914 ++it1)
1915 pIfIo->pfnDelete(pStorage, (*it1).first.c_str());
1916 }
1917
1918 LogFlowFunc(("rc=%Rhrc\n", rc));
1919 LogFlowFuncLeave();
1920
1921 return rc;
1922}
1923
1924#ifdef VBOX_WITH_S3
1925/**
1926 * Worker code for writing out OVF to the cloud. This is called from Appliance::taskThreadWriteOVF()
1927 * in S3 mode and therefore runs on the OVF write worker thread. This then starts a second worker
1928 * thread to create temporary files (see Appliance::writeFS()).
1929 *
1930 * @param pTask
1931 * @return
1932 */
1933HRESULT Appliance::writeS3(TaskOVF *pTask)
1934{
1935 LogFlowFuncEnter();
1936 LogFlowFunc(("Appliance %p\n", this));
1937
1938 AutoCaller autoCaller(this);
1939 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1940
1941 HRESULT rc = S_OK;
1942
1943 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1944
1945 int vrc = VINF_SUCCESS;
1946 RTS3 hS3 = NIL_RTS3;
1947 char szOSTmpDir[RTPATH_MAX];
1948 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1949 /* The template for the temporary directory created below */
1950 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1951 list< pair<Utf8Str, ULONG> > filesList;
1952
1953 // todo:
1954 // - usable error codes
1955 // - seems snapshot filenames are problematic {uuid}.vdi
1956 try
1957 {
1958 /* Extract the bucket */
1959 Utf8Str tmpPath = pTask->locInfo.strPath;
1960 Utf8Str bucket;
1961 parseBucket(tmpPath, bucket);
1962
1963 /* We need a temporary directory which we can put the OVF file & all
1964 * disk images in */
1965 vrc = RTDirCreateTemp(pszTmpDir);
1966 if (RT_FAILURE(vrc))
1967 throw setError(VBOX_E_FILE_ERROR,
1968 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1969
1970 /* The temporary name of the target OVF file */
1971 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1972
1973 /* Prepare the temporary writing of the OVF */
1974 ComObjPtr<Progress> progress;
1975 /* Create a temporary file based location info for the sub task */
1976 LocationInfo li;
1977 li.strPath = strTmpOvf;
1978 rc = writeImpl(pTask->enFormat, li, progress);
1979 if (FAILED(rc)) throw rc;
1980
1981 /* Unlock the appliance for the writing thread */
1982 appLock.release();
1983 /* Wait until the writing is done, but report the progress back to the
1984 caller */
1985 ComPtr<IProgress> progressInt(progress);
1986 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1987
1988 /* Again lock the appliance for the next steps */
1989 appLock.acquire();
1990
1991 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
1992 if (RT_FAILURE(vrc))
1993 throw setError(VBOX_E_FILE_ERROR,
1994 tr("Cannot find source file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
1995 /* Add the OVF file */
1996 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightForXmlOperation)); /* Use 1% of the total for the OVF file upload */
1997 /* Add the manifest file */
1998 if (m->fManifest)
1999 {
2000 Utf8Str strMfFile = Utf8Str(strTmpOvf).stripExt().append(".mf");
2001 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightForXmlOperation)); /* Use 1% of the total for the manifest file upload */
2002 }
2003
2004 /* Now add every disks of every virtual system */
2005 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2006 for (it = m->virtualSystemDescriptions.begin();
2007 it != m->virtualSystemDescriptions.end();
2008 ++it)
2009 {
2010 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2011 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2012 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2013 for (itH = avsdeHDs.begin();
2014 itH != avsdeHDs.end();
2015 ++itH)
2016 {
2017 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
2018 /* Target path needs to be composed from where the output OVF is */
2019 Utf8Str strTargetFilePath(strTmpOvf);
2020 strTargetFilePath.stripFilename();
2021 strTargetFilePath.append("/");
2022 strTargetFilePath.append(strTargetFileNameOnly);
2023 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
2024 if (RT_FAILURE(vrc))
2025 throw setError(VBOX_E_FILE_ERROR,
2026 tr("Cannot find source file '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2027 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
2028 }
2029 }
2030 /* Next we have to upload the OVF & all disk images */
2031 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2032 if (RT_FAILURE(vrc))
2033 throw setError(VBOX_E_IPRT_ERROR,
2034 tr("Cannot create S3 service handler"));
2035 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2036
2037 /* Upload all files */
2038 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2039 {
2040 const pair<Utf8Str, ULONG> &s = (*it1);
2041 char *pszFilename = RTPathFilename(s.first.c_str());
2042 /* Advance to the next operation */
2043 pTask->pProgress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename).raw(), s.second);
2044 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
2045 if (RT_FAILURE(vrc))
2046 {
2047 if (vrc == VERR_S3_CANCELED)
2048 break;
2049 else if (vrc == VERR_S3_ACCESS_DENIED)
2050 throw setError(E_ACCESSDENIED,
2051 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);
2052 else if (vrc == VERR_S3_NOT_FOUND)
2053 throw setError(VBOX_E_FILE_ERROR,
2054 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
2055 else
2056 throw setError(VBOX_E_IPRT_ERROR,
2057 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
2058 }
2059 }
2060 }
2061 catch(HRESULT aRC)
2062 {
2063 rc = aRC;
2064 }
2065 /* Cleanup */
2066 RTS3Destroy(hS3);
2067 /* Delete all files which where temporary created */
2068 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2069 {
2070 const char *pszFilePath = (*it1).first.c_str();
2071 if (RTPathExists(pszFilePath))
2072 {
2073 vrc = RTFileDelete(pszFilePath);
2074 if (RT_FAILURE(vrc))
2075 rc = setError(VBOX_E_FILE_ERROR,
2076 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2077 }
2078 }
2079 /* Delete the temporary directory */
2080 if (RTPathExists(pszTmpDir))
2081 {
2082 vrc = RTDirRemove(pszTmpDir);
2083 if (RT_FAILURE(vrc))
2084 rc = setError(VBOX_E_FILE_ERROR,
2085 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2086 }
2087 if (pszTmpDir)
2088 RTStrFree(pszTmpDir);
2089
2090 LogFlowFunc(("rc=%Rhrc\n", rc));
2091 LogFlowFuncLeave();
2092
2093 return rc;
2094}
2095#endif /* VBOX_WITH_S3 */
Note: See TracBrowser for help on using the repository browser.

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