VirtualBox

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

Last change on this file since 32461 was 32448, checked in by vboxsync, 15 years ago

Main-OVF: make manifest file creation optional

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

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