VirtualBox

source: vbox/trunk/src/VBox/Main/ApplianceImplExport.cpp@ 33696

Last change on this file since 33696 was 33661, checked in by vboxsync, 14 years ago

Main/OVF: never write the Machine/@stateFile attribute in machine XML when exporting OVF vbox:Machine, since we have no state

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