VirtualBox

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

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

Main/OVF: added a sanity check for the size of OVF filenames to prevent creating invalid appliances if the VM name is too long

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

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