VirtualBox

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

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

Main/ApplianceImplExport.cpp: rearrange handling of appliance description lists, always allow the user to override (especially important for the description of a VM, as it defaults to the VM description which some people might not want to export)
Frontends/VBoxManage: finally implement changing the VM description from command line, and also add a way to provide a VM description on export

  • 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 46290 2013-05-27 15:26:15Z 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.215389.xyz. 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.215389.xyz/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())
998 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing VM name"));
999 Utf8Str &strVMName = llName.back()->strVboxCurrent;
1000 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
1001
1002 // product info
1003 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
1004 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
1005 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
1006 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
1007 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
1008 bool fProduct = llProduct.size() && !llProduct.back()->strVboxCurrent.isEmpty();
1009 bool fProductUrl = llProductUrl.size() && !llProductUrl.back()->strVboxCurrent.isEmpty();
1010 bool fVendor = llVendor.size() && !llVendor.back()->strVboxCurrent.isEmpty();
1011 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.back()->strVboxCurrent.isEmpty();
1012 bool fVersion = llVersion.size() && !llVersion.back()->strVboxCurrent.isEmpty();
1013 if (fProduct ||
1014 fProductUrl ||
1015 fVersion ||
1016 fVendorUrl ||
1017 fVersion)
1018 {
1019 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1020 <Info>Meta-information about the installed software</Info>
1021 <Product>VAtest</Product>
1022 <Vendor>SUN Microsystems</Vendor>
1023 <Version>10.0</Version>
1024 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
1025 <VendorUrl>http://www.sun.com</VendorUrl>
1026 </Section> */
1027 xml::ElementNode *pelmAnnotationSection;
1028 if (enFormat == ovf::OVFVersion_0_9)
1029 {
1030 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1031 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1032 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
1033 }
1034 else
1035 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
1036
1037 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
1038 if (fProduct)
1039 pelmAnnotationSection->createChild("Product")->addContent(llProduct.back()->strVboxCurrent);
1040 if (fVendor)
1041 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.back()->strVboxCurrent);
1042 if (fVersion)
1043 pelmAnnotationSection->createChild("Version")->addContent(llVersion.back()->strVboxCurrent);
1044 if (fProductUrl)
1045 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.back()->strVboxCurrent);
1046 if (fVendorUrl)
1047 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.back()->strVboxCurrent);
1048 }
1049
1050 // description
1051 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1052 if (llDescription.size() &&
1053 !llDescription.back()->strVboxCurrent.isEmpty())
1054 {
1055 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1056 <Info>A human-readable annotation</Info>
1057 <Annotation>Plan 9</Annotation>
1058 </Section> */
1059 xml::ElementNode *pelmAnnotationSection;
1060 if (enFormat == ovf::OVFVersion_0_9)
1061 {
1062 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1063 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1064 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
1065 }
1066 else
1067 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
1068
1069 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1070 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.back()->strVboxCurrent);
1071 }
1072
1073 // license
1074 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
1075 if (llLicense.size() &&
1076 !llLicense.back()->strVboxCurrent.isEmpty())
1077 {
1078 /* <EulaSection>
1079 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1080 <License ovf:msgid="1">License terms can go in here.</License>
1081 </EulaSection> */
1082 xml::ElementNode *pelmEulaSection;
1083 if (enFormat == ovf::OVFVersion_0_9)
1084 {
1085 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1086 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1087 }
1088 else
1089 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1090
1091 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1092 pelmEulaSection->createChild("License")->addContent(llLicense.back()->strVboxCurrent);
1093 }
1094
1095 // operating system
1096 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1097 if (!llOS.size())
1098 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing OS type"));
1099 /* <OperatingSystemSection ovf:id="82">
1100 <Info>Guest Operating System</Info>
1101 <Description>Linux 2.6.x</Description>
1102 </OperatingSystemSection> */
1103 VirtualSystemDescriptionEntry *pvsdeOS = llOS.back();
1104 xml::ElementNode *pelmOperatingSystemSection;
1105 if (enFormat == ovf::OVFVersion_0_9)
1106 {
1107 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1108 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1109 }
1110 else
1111 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1112
1113 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1114 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1115 Utf8Str strOSDesc;
1116 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1117 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1118 // add the VirtualBox ostype in a custom tag in a different namespace
1119 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1120 pelmVBoxOSType->setAttribute("ovf:required", "false");
1121 pelmVBoxOSType->addContent(pvsdeOS->strVboxCurrent);
1122
1123 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1124 xml::ElementNode *pelmVirtualHardwareSection;
1125 if (enFormat == ovf::OVFVersion_0_9)
1126 {
1127 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1128 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1129 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1130 }
1131 else
1132 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1133
1134 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1135
1136 /* <System>
1137 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1138 <vssd:ElementName>vmware</vssd:ElementName>
1139 <vssd:InstanceID>1</vssd:InstanceID>
1140 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1141 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1142 </System> */
1143 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1144
1145 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1146
1147 // <vssd:InstanceId>0</vssd:InstanceId>
1148 if (enFormat == ovf::OVFVersion_0_9)
1149 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1150 else // capitalization changed...
1151 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1152
1153 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1154 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1155 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1156 const char *pcszHardware = "virtualbox-2.2";
1157 if (enFormat == ovf::OVFVersion_0_9)
1158 // pretend to be vmware compatible then
1159 pcszHardware = "vmx-6";
1160 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1161
1162 // loop thru all description entries twice; once to write out all
1163 // devices _except_ disk images, and a second time to assign the
1164 // disk images; this is because disk images need to reference
1165 // IDE controllers, and we can't know their instance IDs without
1166 // assigning them first
1167
1168 uint32_t idIDEPrimaryController = 0;
1169 int32_t lIDEPrimaryControllerIndex = 0;
1170 uint32_t idIDESecondaryController = 0;
1171 int32_t lIDESecondaryControllerIndex = 0;
1172 uint32_t idSATAController = 0;
1173 int32_t lSATAControllerIndex = 0;
1174 uint32_t idSCSIController = 0;
1175 int32_t lSCSIControllerIndex = 0;
1176
1177 uint32_t ulInstanceID = 1;
1178
1179 uint32_t cDVDs = 0;
1180
1181 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1182 {
1183 int32_t lIndexThis = 0;
1184 list<VirtualSystemDescriptionEntry>::const_iterator itD;
1185 for (itD = vsdescThis->m->llDescriptions.begin();
1186 itD != vsdescThis->m->llDescriptions.end();
1187 ++itD, ++lIndexThis)
1188 {
1189 const VirtualSystemDescriptionEntry &desc = *itD;
1190
1191 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVbox=%s, strExtraConfig=%s\n",
1192 uLoop,
1193 desc.ulIndex,
1194 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1195 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1196 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1197 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1198 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1199 : Utf8StrFmt("%d", desc.type).c_str()),
1200 desc.strRef.c_str(),
1201 desc.strOvf.c_str(),
1202 desc.strVboxCurrent.c_str(),
1203 desc.strExtraConfigCurrent.c_str()));
1204
1205 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1206 Utf8Str strResourceSubType;
1207
1208 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1209 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1210
1211 uint32_t ulParent = 0;
1212
1213 int32_t lVirtualQuantity = -1;
1214 Utf8Str strAllocationUnits;
1215
1216 int32_t lAddress = -1;
1217 int32_t lBusNumber = -1;
1218 int32_t lAddressOnParent = -1;
1219
1220 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1221 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1222 Utf8Str strHostResource;
1223
1224 uint64_t uTemp;
1225
1226 switch (desc.type)
1227 {
1228 case VirtualSystemDescriptionType_CPU:
1229 /* <Item>
1230 <rasd:Caption>1 virtual CPU</rasd:Caption>
1231 <rasd:Description>Number of virtual CPUs</rasd:Description>
1232 <rasd:ElementName>virtual CPU</rasd:ElementName>
1233 <rasd:InstanceID>1</rasd:InstanceID>
1234 <rasd:ResourceType>3</rasd:ResourceType>
1235 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1236 </Item> */
1237 if (uLoop == 1)
1238 {
1239 strDescription = "Number of virtual CPUs";
1240 type = ovf::ResourceType_Processor; // 3
1241 desc.strVboxCurrent.toInt(uTemp);
1242 lVirtualQuantity = (int32_t)uTemp;
1243 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
1244 }
1245 break;
1246
1247 case VirtualSystemDescriptionType_Memory:
1248 /* <Item>
1249 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1250 <rasd:Caption>256 MB of memory</rasd:Caption>
1251 <rasd:Description>Memory Size</rasd:Description>
1252 <rasd:ElementName>Memory</rasd:ElementName>
1253 <rasd:InstanceID>2</rasd:InstanceID>
1254 <rasd:ResourceType>4</rasd:ResourceType>
1255 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1256 </Item> */
1257 if (uLoop == 1)
1258 {
1259 strDescription = "Memory Size";
1260 type = ovf::ResourceType_Memory; // 4
1261 desc.strVboxCurrent.toInt(uTemp);
1262 lVirtualQuantity = (int32_t)(uTemp / _1M);
1263 strAllocationUnits = "MegaBytes";
1264 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
1265 }
1266 break;
1267
1268 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1269 /* <Item>
1270 <rasd:Caption>ideController1</rasd:Caption>
1271 <rasd:Description>IDE Controller</rasd:Description>
1272 <rasd:InstanceId>5</rasd:InstanceId>
1273 <rasd:ResourceType>5</rasd:ResourceType>
1274 <rasd:Address>1</rasd:Address>
1275 <rasd:BusNumber>1</rasd:BusNumber>
1276 </Item> */
1277 if (uLoop == 1)
1278 {
1279 strDescription = "IDE Controller";
1280 type = ovf::ResourceType_IDEController; // 5
1281 strResourceSubType = desc.strVboxCurrent;
1282
1283 if (!lIDEPrimaryControllerIndex)
1284 {
1285 // first IDE controller:
1286 strCaption = "ideController0";
1287 lAddress = 0;
1288 lBusNumber = 0;
1289 // remember this ID
1290 idIDEPrimaryController = ulInstanceID;
1291 lIDEPrimaryControllerIndex = lIndexThis;
1292 }
1293 else
1294 {
1295 // second IDE controller:
1296 strCaption = "ideController1";
1297 lAddress = 1;
1298 lBusNumber = 1;
1299 // remember this ID
1300 idIDESecondaryController = ulInstanceID;
1301 lIDESecondaryControllerIndex = lIndexThis;
1302 }
1303 }
1304 break;
1305
1306 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1307 /* <Item>
1308 <rasd:Caption>sataController0</rasd:Caption>
1309 <rasd:Description>SATA Controller</rasd:Description>
1310 <rasd:InstanceId>4</rasd:InstanceId>
1311 <rasd:ResourceType>20</rasd:ResourceType>
1312 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1313 <rasd:Address>0</rasd:Address>
1314 <rasd:BusNumber>0</rasd:BusNumber>
1315 </Item>
1316 */
1317 if (uLoop == 1)
1318 {
1319 strDescription = "SATA Controller";
1320 strCaption = "sataController0";
1321 type = ovf::ResourceType_OtherStorageDevice; // 20
1322 // it seems that OVFTool always writes these two, and since we can only
1323 // have one SATA controller, we'll use this as well
1324 lAddress = 0;
1325 lBusNumber = 0;
1326
1327 if ( desc.strVboxCurrent.isEmpty() // AHCI is the default in VirtualBox
1328 || (!desc.strVboxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1329 )
1330 strResourceSubType = "AHCI";
1331 else
1332 throw setError(VBOX_E_NOT_SUPPORTED,
1333 tr("Invalid config string \"%s\" in SATA controller"), desc.strVboxCurrent.c_str());
1334
1335 // remember this ID
1336 idSATAController = ulInstanceID;
1337 lSATAControllerIndex = lIndexThis;
1338 }
1339 break;
1340
1341 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1342 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1343 /* <Item>
1344 <rasd:Caption>scsiController0</rasd:Caption>
1345 <rasd:Description>SCSI Controller</rasd:Description>
1346 <rasd:InstanceId>4</rasd:InstanceId>
1347 <rasd:ResourceType>6</rasd:ResourceType>
1348 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1349 <rasd:Address>0</rasd:Address>
1350 <rasd:BusNumber>0</rasd:BusNumber>
1351 </Item>
1352 */
1353 if (uLoop == 1)
1354 {
1355 strDescription = "SCSI Controller";
1356 strCaption = "scsiController0";
1357 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1358 // it seems that OVFTool always writes these two, and since we can only
1359 // have one SATA controller, we'll use this as well
1360 lAddress = 0;
1361 lBusNumber = 0;
1362
1363 if ( desc.strVboxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1364 || (!desc.strVboxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1365 )
1366 strResourceSubType = "lsilogic";
1367 else if (!desc.strVboxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1368 strResourceSubType = "buslogic";
1369 else if (!desc.strVboxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1370 strResourceSubType = "lsilogicsas";
1371 else
1372 throw setError(VBOX_E_NOT_SUPPORTED,
1373 tr("Invalid config string \"%s\" in SCSI/SAS controller"), desc.strVboxCurrent.c_str());
1374
1375 // remember this ID
1376 idSCSIController = ulInstanceID;
1377 lSCSIControllerIndex = lIndexThis;
1378 }
1379 break;
1380
1381 case VirtualSystemDescriptionType_HardDiskImage:
1382 /* <Item>
1383 <rasd:Caption>disk1</rasd:Caption>
1384 <rasd:InstanceId>8</rasd:InstanceId>
1385 <rasd:ResourceType>17</rasd:ResourceType>
1386 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1387 <rasd:Parent>4</rasd:Parent>
1388 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1389 </Item> */
1390 if (uLoop == 2)
1391 {
1392 uint32_t cDisks = stack.mapDisks.size();
1393 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1394
1395 strDescription = "Disk Image";
1396 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1397 type = ovf::ResourceType_HardDisk; // 17
1398
1399 // the following references the "<Disks>" XML block
1400 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1401
1402 // controller=<index>;channel=<c>
1403 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1404 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1405 int32_t lControllerIndex = -1;
1406 if (pos1 != Utf8Str::npos)
1407 {
1408 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1409 if (lControllerIndex == lIDEPrimaryControllerIndex)
1410 ulParent = idIDEPrimaryController;
1411 else if (lControllerIndex == lIDESecondaryControllerIndex)
1412 ulParent = idIDESecondaryController;
1413 else if (lControllerIndex == lSCSIControllerIndex)
1414 ulParent = idSCSIController;
1415 else if (lControllerIndex == lSATAControllerIndex)
1416 ulParent = idSATAController;
1417 }
1418 if (pos2 != Utf8Str::npos)
1419 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1420
1421 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1422 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1423
1424 if ( !ulParent
1425 || lAddressOnParent == -1
1426 )
1427 throw setError(VBOX_E_NOT_SUPPORTED,
1428 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfigCurrent.c_str());
1429
1430 stack.mapDisks[strDiskID] = &desc;
1431 }
1432 break;
1433
1434 case VirtualSystemDescriptionType_Floppy:
1435 if (uLoop == 1)
1436 {
1437 strDescription = "Floppy Drive";
1438 strCaption = "floppy0"; // this is what OVFTool writes
1439 type = ovf::ResourceType_FloppyDrive; // 14
1440 lAutomaticAllocation = 0;
1441 lAddressOnParent = 0; // this is what OVFTool writes
1442 }
1443 break;
1444
1445 case VirtualSystemDescriptionType_CDROM:
1446 /* <Item>
1447 <rasd:Caption>cdrom1</rasd:Caption>
1448 <rasd:InstanceId>8</rasd:InstanceId>
1449 <rasd:ResourceType>15</rasd:ResourceType>
1450 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1451 <rasd:Parent>4</rasd:Parent>
1452 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1453 </Item> */
1454 if (uLoop == 2)
1455 {
1456 //uint32_t cDisks = stack.mapDisks.size();
1457 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDVDs);
1458
1459 strDescription = "CD-ROM Drive";
1460 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1461 type = ovf::ResourceType_CDDrive; // 15
1462 lAutomaticAllocation = 1;
1463
1464 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1465 if (desc.strVboxCurrent.isNotEmpty())
1466 {
1467 // the following references the "<Disks>" XML block
1468 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1469 }
1470
1471 // controller=<index>;channel=<c>
1472 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1473 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1474 int32_t lControllerIndex = -1;
1475 if (pos1 != Utf8Str::npos)
1476 {
1477 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1478 if (lControllerIndex == lIDEPrimaryControllerIndex)
1479 ulParent = idIDEPrimaryController;
1480 else if (lControllerIndex == lIDESecondaryControllerIndex)
1481 ulParent = idIDESecondaryController;
1482 else if (lControllerIndex == lSCSIControllerIndex)
1483 ulParent = idSCSIController;
1484 else if (lControllerIndex == lSATAControllerIndex)
1485 ulParent = idSATAController;
1486 }
1487 if (pos2 != Utf8Str::npos)
1488 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1489
1490 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1491 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1492
1493 if ( !ulParent
1494 || lAddressOnParent == -1
1495 )
1496 throw setError(VBOX_E_NOT_SUPPORTED,
1497 tr("Missing or bad extra config string in DVD drive medium: \"%s\""), desc.strExtraConfigCurrent.c_str());
1498
1499 stack.mapDisks[strDiskID] = &desc;
1500 // there is no DVD drive map to update because it is
1501 // handled completely with this entry.
1502 }
1503 break;
1504
1505 case VirtualSystemDescriptionType_NetworkAdapter:
1506 /* <Item>
1507 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1508 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1509 <rasd:Connection>VM Network</rasd:Connection>
1510 <rasd:ElementName>VM network</rasd:ElementName>
1511 <rasd:InstanceID>3</rasd:InstanceID>
1512 <rasd:ResourceType>10</rasd:ResourceType>
1513 </Item> */
1514 if (uLoop == 1)
1515 {
1516 lAutomaticAllocation = 1;
1517 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1518 type = ovf::ResourceType_EthernetAdapter; // 10
1519 /* Set the hardware type to something useful.
1520 * To be compatible with vmware & others we set
1521 * PCNet32 for our PCNet types & E1000 for the
1522 * E1000 cards. */
1523 switch (desc.strVboxCurrent.toInt32())
1524 {
1525 case NetworkAdapterType_Am79C970A:
1526 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1527#ifdef VBOX_WITH_E1000
1528 case NetworkAdapterType_I82540EM:
1529 case NetworkAdapterType_I82545EM:
1530 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1531#endif /* VBOX_WITH_E1000 */
1532 }
1533 strConnection = desc.strOvf;
1534
1535 stack.mapNetworks[desc.strOvf] = true;
1536 }
1537 break;
1538
1539 case VirtualSystemDescriptionType_USBController:
1540 /* <Item ovf:required="false">
1541 <rasd:Caption>usb</rasd:Caption>
1542 <rasd:Description>USB Controller</rasd:Description>
1543 <rasd:InstanceId>3</rasd:InstanceId>
1544 <rasd:ResourceType>23</rasd:ResourceType>
1545 <rasd:Address>0</rasd:Address>
1546 <rasd:BusNumber>0</rasd:BusNumber>
1547 </Item> */
1548 if (uLoop == 1)
1549 {
1550 strDescription = "USB Controller";
1551 strCaption = "usb";
1552 type = ovf::ResourceType_USBController; // 23
1553 lAddress = 0; // this is what OVFTool writes
1554 lBusNumber = 0; // this is what OVFTool writes
1555 }
1556 break;
1557
1558 case VirtualSystemDescriptionType_SoundCard:
1559 /* <Item ovf:required="false">
1560 <rasd:Caption>sound</rasd:Caption>
1561 <rasd:Description>Sound Card</rasd:Description>
1562 <rasd:InstanceId>10</rasd:InstanceId>
1563 <rasd:ResourceType>35</rasd:ResourceType>
1564 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1565 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1566 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1567 </Item> */
1568 if (uLoop == 1)
1569 {
1570 strDescription = "Sound Card";
1571 strCaption = "sound";
1572 type = ovf::ResourceType_SoundCard; // 35
1573 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1574 lAutomaticAllocation = 0;
1575 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1576 }
1577 break;
1578 }
1579
1580 if (type)
1581 {
1582 xml::ElementNode *pItem;
1583
1584 pItem = pelmVirtualHardwareSection->createChild("Item");
1585
1586 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1587 // the elements from the rasd: namespace must be sorted by letter, and VMware
1588 // actually requires this as well (see public bug #6612)
1589
1590 if (lAddress != -1)
1591 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1592
1593 if (lAddressOnParent != -1)
1594 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1595
1596 if (!strAllocationUnits.isEmpty())
1597 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1598
1599 if (lAutomaticAllocation != -1)
1600 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1601
1602 if (lBusNumber != -1)
1603 if (enFormat == ovf::OVFVersion_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool y
1604 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1605
1606 if (!strCaption.isEmpty())
1607 pItem->createChild("rasd:Caption")->addContent(strCaption);
1608
1609 if (!strConnection.isEmpty())
1610 pItem->createChild("rasd:Connection")->addContent(strConnection);
1611
1612 if (!strDescription.isEmpty())
1613 pItem->createChild("rasd:Description")->addContent(strDescription);
1614
1615 if (!strCaption.isEmpty())
1616 if (enFormat == ovf::OVFVersion_1_0)
1617 pItem->createChild("rasd:ElementName")->addContent(strCaption);
1618
1619 if (!strHostResource.isEmpty())
1620 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1621
1622 // <rasd:InstanceID>1</rasd:InstanceID>
1623 xml::ElementNode *pelmInstanceID;
1624 if (enFormat == ovf::OVFVersion_0_9)
1625 pelmInstanceID = pItem->createChild("rasd:InstanceId");
1626 else
1627 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1628 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
1629
1630 if (ulParent)
1631 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1632
1633 if (!strResourceSubType.isEmpty())
1634 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1635
1636 // <rasd:ResourceType>3</rasd:ResourceType>
1637 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1638
1639 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1640 if (lVirtualQuantity != -1)
1641 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1642 }
1643 }
1644 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1645
1646 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1647 // under the vbox: namespace
1648 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1649 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1650 pelmVBoxMachine->setAttribute("ovf:required", "false");
1651 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1652 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1653
1654 // create an empty machine config
1655 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(NULL);
1656
1657 writeLock.release();
1658 try
1659 {
1660 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1661 // fill the machine config
1662 vsdescThis->m->pMachine->copyMachineDataToSettings(*pConfig);
1663 // write the machine config to the vbox:Machine element
1664 pConfig->buildMachineXML(*pelmVBoxMachine,
1665 settings::MachineConfigFile::BuildMachineXML_WriteVboxVersionAttribute
1666 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
1667 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
1668 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1669 pllElementsWithUuidAttributes);
1670 delete pConfig;
1671 }
1672 catch (...)
1673 {
1674 writeLock.acquire();
1675 delete pConfig;
1676 throw;
1677 }
1678 writeLock.acquire();
1679}
1680
1681/**
1682 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1683 * and therefore runs on the OVF/OVA write worker thread. This runs in two contexts:
1684 *
1685 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::writeImpl();
1686 *
1687 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
1688 * called Appliance::writeS3(), which called Appliance::writeImpl(), which then called this. In other
1689 * words, to write to the cloud, the first worker thread first starts a second worker thread to create
1690 * temporary files and then uploads them to the S3 cloud server.
1691 *
1692 * @param pTask
1693 * @return
1694 */
1695HRESULT Appliance::writeFS(TaskOVF *pTask)
1696{
1697 LogFlowFuncEnter();
1698 LogFlowFunc(("ENTER appliance %p\n", this));
1699
1700 AutoCaller autoCaller(this);
1701 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1702
1703 HRESULT rc = S_OK;
1704
1705 // Lock the media tree early to make sure nobody else tries to make changes
1706 // to the tree. Also lock the IAppliance object for writing.
1707 AutoMultiWriteLock2 multiLock(&mVirtualBox->getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1708 // Additional protect the IAppliance object, cause we leave the lock
1709 // when starting the disk export and we don't won't block other
1710 // callers on this lengthy operations.
1711 m->state = Data::ApplianceExporting;
1712
1713 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1714 rc = writeFSOVF(pTask, multiLock);
1715 else
1716 rc = writeFSOVA(pTask, multiLock);
1717
1718 // reset the state so others can call methods again
1719 m->state = Data::ApplianceIdle;
1720
1721 LogFlowFunc(("rc=%Rhrc\n", rc));
1722 LogFlowFuncLeave();
1723 return rc;
1724}
1725
1726HRESULT Appliance::writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1727{
1728 LogFlowFuncEnter();
1729
1730 HRESULT rc = S_OK;
1731
1732 PVDINTERFACEIO pShaIo = 0;
1733 PVDINTERFACEIO pFileIo = 0;
1734 do
1735 {
1736 pShaIo = ShaCreateInterface();
1737 if (!pShaIo)
1738 {
1739 rc = E_OUTOFMEMORY;
1740 break;
1741 }
1742 pFileIo = FileCreateInterface();
1743 if (!pFileIo)
1744 {
1745 rc = E_OUTOFMEMORY;
1746 break;
1747 }
1748
1749 SHASTORAGE storage;
1750 RT_ZERO(storage);
1751 storage.fCreateDigest = m->fManifest;
1752 storage.fSha256 = m->fSha256;
1753 int vrc = VDInterfaceAdd(&pFileIo->Core, "Appliance::IOFile",
1754 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1755 &storage.pVDImageIfaces);
1756 if (RT_FAILURE(vrc))
1757 {
1758 rc = E_FAIL;
1759 break;
1760 }
1761 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1762 } while (0);
1763
1764 /* Cleanup */
1765 if (pShaIo)
1766 RTMemFree(pShaIo);
1767 if (pFileIo)
1768 RTMemFree(pFileIo);
1769
1770 LogFlowFuncLeave();
1771 return rc;
1772}
1773
1774HRESULT Appliance::writeFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1775{
1776 LogFlowFuncEnter();
1777
1778 RTTAR tar;
1779 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL, false);
1780 if (RT_FAILURE(vrc))
1781 return setError(VBOX_E_FILE_ERROR,
1782 tr("Could not create OVA file '%s' (%Rrc)"),
1783 pTask->locInfo.strPath.c_str(), vrc);
1784
1785 HRESULT rc = S_OK;
1786
1787 PVDINTERFACEIO pShaIo = 0;
1788 PVDINTERFACEIO pTarIo = 0;
1789 do
1790 {
1791 pShaIo = ShaCreateInterface();
1792 if (!pShaIo)
1793 {
1794 rc = E_OUTOFMEMORY;
1795 break;
1796 }
1797 pTarIo = TarCreateInterface();
1798 if (!pTarIo)
1799 {
1800 rc = E_OUTOFMEMORY;
1801 break;
1802 }
1803 SHASTORAGE storage;
1804 RT_ZERO(storage);
1805 storage.fCreateDigest = m->fManifest;
1806 storage.fSha256 = m->fSha256;
1807 vrc = VDInterfaceAdd(&pTarIo->Core, "Appliance::IOTar",
1808 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
1809 &storage.pVDImageIfaces);
1810 if (RT_FAILURE(vrc))
1811 {
1812 rc = E_FAIL;
1813 break;
1814 }
1815 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1816 } while (0);
1817
1818 RTTarClose(tar);
1819
1820 /* Cleanup */
1821 if (pShaIo)
1822 RTMemFree(pShaIo);
1823 if (pTarIo)
1824 RTMemFree(pTarIo);
1825
1826 /* Delete ova file on error */
1827 if (FAILED(rc))
1828 RTFileDelete(pTask->locInfo.strPath.c_str());
1829
1830 LogFlowFuncLeave();
1831 return rc;
1832}
1833
1834HRESULT Appliance::writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
1835{
1836 LogFlowFuncEnter();
1837
1838 HRESULT rc = S_OK;
1839
1840 list<STRPAIR> fileList;
1841 try
1842 {
1843 int vrc;
1844 // the XML stack contains two maps for disks and networks, which allows us to
1845 // a) have a list of unique disk names (to make sure the same disk name is only added once)
1846 // and b) keep a list of all networks
1847 XMLStack stack;
1848 // Scope this to free the memory as soon as this is finished
1849 {
1850 // Create a xml document
1851 xml::Document doc;
1852 // Now fully build a valid ovf document in memory
1853 buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
1854 /* Extract the path */
1855 Utf8Str strOvfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".ovf");
1856 // Create a memory buffer containing the XML. */
1857 void *pvBuf = 0;
1858 size_t cbSize;
1859 xml::XmlMemWriter writer;
1860 writer.write(doc, &pvBuf, &cbSize);
1861 if (RT_UNLIKELY(!pvBuf))
1862 throw setError(VBOX_E_FILE_ERROR,
1863 tr("Could not create OVF file '%s'"),
1864 strOvfFile.c_str());
1865 /* Write the ovf file to disk. */
1866 vrc = ShaWriteBuf(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
1867 if (RT_FAILURE(vrc))
1868 throw setError(VBOX_E_FILE_ERROR,
1869 tr("Could not create OVF file '%s' (%Rrc)"),
1870 strOvfFile.c_str(), vrc);
1871 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
1872 }
1873
1874 // We need a proper format description
1875 ComObjPtr<MediumFormat> formatTemp;
1876
1877 ComObjPtr<MediumFormat> format;
1878 // Scope for the AutoReadLock
1879 {
1880 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
1881 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
1882 // We are always exporting to VMDK stream optimized for now
1883 formatTemp = pSysProps->mediumFormatFromExtension("iso");
1884
1885 format = pSysProps->mediumFormat("VMDK");
1886 if (format.isNull())
1887 throw setError(VBOX_E_NOT_SUPPORTED,
1888 tr("Invalid medium storage format"));
1889 }
1890
1891 // Finally, write out the disks!
1892 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
1893 for (itS = stack.mapDisks.begin();
1894 itS != stack.mapDisks.end();
1895 ++itS)
1896 {
1897 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
1898
1899 // source path: where the VBox image is
1900 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
1901
1902 //skip empty Medium. In common, It's may be empty CD/DVD
1903 if (strSrcFilePath.isEmpty())
1904 continue;
1905
1906 // Do NOT check here whether the file exists. findHardDisk will
1907 // figure that out, and filesystem-based tests are simply wrong
1908 // in the general case (think of iSCSI).
1909
1910 // clone the disk:
1911 ComObjPtr<Medium> pSourceDisk;
1912
1913 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
1914
1915 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
1916 {
1917 rc = mVirtualBox->findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
1918 if (FAILED(rc)) throw rc;
1919 }
1920 else//may be CD or DVD
1921 {
1922 rc = mVirtualBox->findDVDOrFloppyImage(DeviceType_DVD,
1923 NULL,
1924 strSrcFilePath,
1925 true,
1926 &pSourceDisk);
1927 if (FAILED(rc)) throw rc;
1928 }
1929
1930 Bstr uuidSource;
1931 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1932 if (FAILED(rc)) throw rc;
1933 Guid guidSource(uuidSource);
1934
1935 // output filename
1936 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1937 // target path needs to be composed from where the output OVF is
1938 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
1939 strTargetFilePath.stripFilename()
1940 .append("/")
1941 .append(strTargetFileNameOnly);
1942
1943 // The exporting requests a lock on the media tree. So leave our lock temporary.
1944 writeLock.release();
1945 try
1946 {
1947 ComObjPtr<Progress> pProgress2;
1948 pProgress2.createObject();
1949 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetFilePath.c_str()).raw(), TRUE);
1950 if (FAILED(rc)) throw rc;
1951
1952 // advance to the next operation
1953 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"), RTPathFilename(strTargetFilePath.c_str())).raw(),
1954 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally
1955
1956 // create a flat copy of the source disk image
1957 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
1958 {
1959 rc = pSourceDisk->exportFile(strTargetFilePath.c_str(),
1960 format,
1961 MediumVariant_VmdkStreamOptimized,
1962 pIfIo,
1963 pStorage,
1964 pProgress2);
1965 if (FAILED(rc)) throw rc;
1966 }
1967 else
1968 {
1969 //copy/clone CD/DVD image
1970 rc = pSourceDisk->exportFile(strTargetFilePath.c_str(),
1971 formatTemp,
1972 MediumVariant_Standard,
1973 pIfIo,
1974 pStorage,
1975 pProgress2);
1976 if (FAILED(rc)) throw rc;
1977 }
1978
1979 ComPtr<IProgress> pProgress3(pProgress2);
1980 // now wait for the background disk operation to complete; this throws HRESULTs on error
1981 waitForAsyncProgress(pTask->pProgress, pProgress3);
1982 }
1983 catch (HRESULT rc3)
1984 {
1985 writeLock.acquire();
1986 // Todo: file deletion on error? If not, we can remove that whole try/catch block.
1987 throw rc3;
1988 }
1989 // Finished, lock again (so nobody mess around with the medium tree
1990 // in the meantime)
1991 writeLock.acquire();
1992 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
1993 }
1994
1995 if (m->fManifest)
1996 {
1997 // Create & write the manifest file
1998 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1999 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2000 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2001 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally);
2002 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
2003 size_t i = 0;
2004 list<STRPAIR>::const_iterator it1;
2005 for (it1 = fileList.begin();
2006 it1 != fileList.end();
2007 ++it1, ++i)
2008 {
2009 paManifestFiles[i].pszTestFile = (*it1).first.c_str();
2010 paManifestFiles[i].pszTestDigest = (*it1).second.c_str();
2011 }
2012 void *pvBuf;
2013 size_t cbSize;
2014 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
2015 paManifestFiles, fileList.size());
2016 RTMemFree(paManifestFiles);
2017 if (RT_FAILURE(vrc))
2018 throw setError(VBOX_E_FILE_ERROR,
2019 tr("Could not create manifest file '%s' (%Rrc)"),
2020 strMfFileName.c_str(), vrc);
2021 /* Disable digest creation for the manifest file. */
2022 pStorage->fCreateDigest = false;
2023 /* Write the manifest file to disk. */
2024 vrc = ShaWriteBuf(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2025 RTMemFree(pvBuf);
2026 if (RT_FAILURE(vrc))
2027 throw setError(VBOX_E_FILE_ERROR,
2028 tr("Could not create manifest file '%s' (%Rrc)"),
2029 strMfFilePath.c_str(), vrc);
2030 }
2031 }
2032 catch (RTCError &x) // includes all XML exceptions
2033 {
2034 rc = setError(VBOX_E_FILE_ERROR,
2035 x.what());
2036 }
2037 catch (HRESULT aRC)
2038 {
2039 rc = aRC;
2040 }
2041
2042 /* Cleanup on error */
2043 if (FAILED(rc))
2044 {
2045 list<STRPAIR>::const_iterator it1;
2046 for (it1 = fileList.begin();
2047 it1 != fileList.end();
2048 ++it1)
2049 pIfIo->pfnDelete(pStorage, (*it1).first.c_str());
2050 }
2051
2052 LogFlowFunc(("rc=%Rhrc\n", rc));
2053 LogFlowFuncLeave();
2054
2055 return rc;
2056}
2057
2058#ifdef VBOX_WITH_S3
2059/**
2060 * Worker code for writing out OVF to the cloud. This is called from Appliance::taskThreadWriteOVF()
2061 * in S3 mode and therefore runs on the OVF write worker thread. This then starts a second worker
2062 * thread to create temporary files (see Appliance::writeFS()).
2063 *
2064 * @param pTask
2065 * @return
2066 */
2067HRESULT Appliance::writeS3(TaskOVF *pTask)
2068{
2069 LogFlowFuncEnter();
2070 LogFlowFunc(("Appliance %p\n", this));
2071
2072 AutoCaller autoCaller(this);
2073 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2074
2075 HRESULT rc = S_OK;
2076
2077 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
2078
2079 int vrc = VINF_SUCCESS;
2080 RTS3 hS3 = NIL_RTS3;
2081 char szOSTmpDir[RTPATH_MAX];
2082 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
2083 /* The template for the temporary directory created below */
2084 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
2085 list< pair<Utf8Str, ULONG> > filesList;
2086
2087 // todo:
2088 // - usable error codes
2089 // - seems snapshot filenames are problematic {uuid}.vdi
2090 try
2091 {
2092 /* Extract the bucket */
2093 Utf8Str tmpPath = pTask->locInfo.strPath;
2094 Utf8Str bucket;
2095 parseBucket(tmpPath, bucket);
2096
2097 /* We need a temporary directory which we can put the OVF file & all
2098 * disk images in */
2099 vrc = RTDirCreateTemp(pszTmpDir, 0700);
2100 if (RT_FAILURE(vrc))
2101 throw setError(VBOX_E_FILE_ERROR,
2102 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2103
2104 /* The temporary name of the target OVF file */
2105 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2106
2107 /* Prepare the temporary writing of the OVF */
2108 ComObjPtr<Progress> progress;
2109 /* Create a temporary file based location info for the sub task */
2110 LocationInfo li;
2111 li.strPath = strTmpOvf;
2112 rc = writeImpl(pTask->enFormat, li, progress);
2113 if (FAILED(rc)) throw rc;
2114
2115 /* Unlock the appliance for the writing thread */
2116 appLock.release();
2117 /* Wait until the writing is done, but report the progress back to the
2118 caller */
2119 ComPtr<IProgress> progressInt(progress);
2120 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2121
2122 /* Again lock the appliance for the next steps */
2123 appLock.acquire();
2124
2125 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
2126 if (RT_FAILURE(vrc))
2127 throw setError(VBOX_E_FILE_ERROR,
2128 tr("Cannot find source file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
2129 /* Add the OVF file */
2130 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightForXmlOperation)); /* Use 1% of the total for the OVF file upload */
2131 /* Add the manifest file */
2132 if (m->fManifest)
2133 {
2134 Utf8Str strMfFile = Utf8Str(strTmpOvf).stripExt().append(".mf");
2135 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightForXmlOperation)); /* Use 1% of the total for the manifest file upload */
2136 }
2137
2138 /* Now add every disks of every virtual system */
2139 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2140 for (it = m->virtualSystemDescriptions.begin();
2141 it != m->virtualSystemDescriptions.end();
2142 ++it)
2143 {
2144 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2145 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2146 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2147 for (itH = avsdeHDs.begin();
2148 itH != avsdeHDs.end();
2149 ++itH)
2150 {
2151 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
2152 /* Target path needs to be composed from where the output OVF is */
2153 Utf8Str strTargetFilePath(strTmpOvf);
2154 strTargetFilePath.stripFilename();
2155 strTargetFilePath.append("/");
2156 strTargetFilePath.append(strTargetFileNameOnly);
2157 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
2158 if (RT_FAILURE(vrc))
2159 throw setError(VBOX_E_FILE_ERROR,
2160 tr("Cannot find source file '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2161 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
2162 }
2163 }
2164 /* Next we have to upload the OVF & all disk images */
2165 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2166 if (RT_FAILURE(vrc))
2167 throw setError(VBOX_E_IPRT_ERROR,
2168 tr("Cannot create S3 service handler"));
2169 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2170
2171 /* Upload all files */
2172 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2173 {
2174 const pair<Utf8Str, ULONG> &s = (*it1);
2175 char *pszFilename = RTPathFilename(s.first.c_str());
2176 /* Advance to the next operation */
2177 pTask->pProgress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename).raw(), s.second);
2178 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
2179 if (RT_FAILURE(vrc))
2180 {
2181 if (vrc == VERR_S3_CANCELED)
2182 break;
2183 else if (vrc == VERR_S3_ACCESS_DENIED)
2184 throw setError(E_ACCESSDENIED,
2185 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);
2186 else if (vrc == VERR_S3_NOT_FOUND)
2187 throw setError(VBOX_E_FILE_ERROR,
2188 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
2189 else
2190 throw setError(VBOX_E_IPRT_ERROR,
2191 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
2192 }
2193 }
2194 }
2195 catch(HRESULT aRC)
2196 {
2197 rc = aRC;
2198 }
2199 /* Cleanup */
2200 RTS3Destroy(hS3);
2201 /* Delete all files which where temporary created */
2202 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2203 {
2204 const char *pszFilePath = (*it1).first.c_str();
2205 if (RTPathExists(pszFilePath))
2206 {
2207 vrc = RTFileDelete(pszFilePath);
2208 if (RT_FAILURE(vrc))
2209 rc = setError(VBOX_E_FILE_ERROR,
2210 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2211 }
2212 }
2213 /* Delete the temporary directory */
2214 if (RTPathExists(pszTmpDir))
2215 {
2216 vrc = RTDirRemove(pszTmpDir);
2217 if (RT_FAILURE(vrc))
2218 rc = setError(VBOX_E_FILE_ERROR,
2219 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2220 }
2221 if (pszTmpDir)
2222 RTStrFree(pszTmpDir);
2223
2224 LogFlowFunc(("rc=%Rhrc\n", rc));
2225 LogFlowFuncLeave();
2226
2227 return rc;
2228}
2229#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