VirtualBox

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

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

Automated rebranding to Oracle copyright/license strings via filemuncher

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

© 2023 Oracle
ContactPrivacy policyTerms of Use