VirtualBox

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

Last change on this file since 35013 was 34505, checked in by vboxsync, 14 years ago

Main/OVF: write vbox ostype into ovf:/OperatingSystemSection/vbox:OSType element on export as well

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