VirtualBox

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

Last change on this file since 46169 was 46169, checked in by vboxsync, 12 years ago

Changes in parsing, extracting and processing an OVF version in/from a XML file in the OVF package.

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