VirtualBox

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

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

Export/import OVA/OVF package supports ISO images. The problem with the wrong search files in the archive has been resolved. (see #5429). 2 new elements SASD and EPASD were added in the OVF XML file structure (see #6022).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 104.3 KB
Line 
1/* $Id: ApplianceImplExport.cpp 46518 2013-06-13 10:07:09Z 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 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.215389.xyz/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 ovf::VirtualHardwareItem vhi;
1233 ovf::StorageItem si;
1234 ovf::EthernetPortItem epi;
1235
1236 switch (desc.type)
1237 {
1238 case VirtualSystemDescriptionType_CPU:
1239 /* <Item>
1240 <rasd:Caption>1 virtual CPU</rasd:Caption>
1241 <rasd:Description>Number of virtual CPUs</rasd:Description>
1242 <rasd:ElementName>virtual CPU</rasd:ElementName>
1243 <rasd:InstanceID>1</rasd:InstanceID>
1244 <rasd:ResourceType>3</rasd:ResourceType>
1245 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1246 </Item> */
1247 if (uLoop == 1)
1248 {
1249 strDescription = "Number of virtual CPUs";
1250 type = ovf::ResourceType_Processor; // 3
1251 desc.strVboxCurrent.toInt(uTemp);
1252 lVirtualQuantity = (int32_t)uTemp;
1253 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
1254 }
1255 break;
1256
1257 case VirtualSystemDescriptionType_Memory:
1258 /* <Item>
1259 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1260 <rasd:Caption>256 MB of memory</rasd:Caption>
1261 <rasd:Description>Memory Size</rasd:Description>
1262 <rasd:ElementName>Memory</rasd:ElementName>
1263 <rasd:InstanceID>2</rasd:InstanceID>
1264 <rasd:ResourceType>4</rasd:ResourceType>
1265 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1266 </Item> */
1267 if (uLoop == 1)
1268 {
1269 strDescription = "Memory Size";
1270 type = ovf::ResourceType_Memory; // 4
1271 desc.strVboxCurrent.toInt(uTemp);
1272 lVirtualQuantity = (int32_t)(uTemp / _1M);
1273 strAllocationUnits = "MegaBytes";
1274 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
1275 }
1276 break;
1277
1278 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1279 /* <Item>
1280 <rasd:Caption>ideController1</rasd:Caption>
1281 <rasd:Description>IDE Controller</rasd:Description>
1282 <rasd:InstanceId>5</rasd:InstanceId>
1283 <rasd:ResourceType>5</rasd:ResourceType>
1284 <rasd:Address>1</rasd:Address>
1285 <rasd:BusNumber>1</rasd:BusNumber>
1286 </Item> */
1287 if (uLoop == 1)
1288 {
1289 strDescription = "IDE Controller";
1290 type = ovf::ResourceType_IDEController; // 5
1291 strResourceSubType = desc.strVboxCurrent;
1292
1293 if (!lIDEPrimaryControllerIndex)
1294 {
1295 // first IDE controller:
1296 strCaption = "ideController0";
1297 lAddress = 0;
1298 lBusNumber = 0;
1299 // remember this ID
1300 idIDEPrimaryController = ulInstanceID;
1301 lIDEPrimaryControllerIndex = lIndexThis;
1302 }
1303 else
1304 {
1305 // second IDE controller:
1306 strCaption = "ideController1";
1307 lAddress = 1;
1308 lBusNumber = 1;
1309 // remember this ID
1310 idIDESecondaryController = ulInstanceID;
1311 lIDESecondaryControllerIndex = lIndexThis;
1312 }
1313 }
1314 break;
1315
1316 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1317 /* <Item>
1318 <rasd:Caption>sataController0</rasd:Caption>
1319 <rasd:Description>SATA Controller</rasd:Description>
1320 <rasd:InstanceId>4</rasd:InstanceId>
1321 <rasd:ResourceType>20</rasd:ResourceType>
1322 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1323 <rasd:Address>0</rasd:Address>
1324 <rasd:BusNumber>0</rasd:BusNumber>
1325 </Item>
1326 */
1327 if (uLoop == 1)
1328 {
1329 strDescription = "SATA Controller";
1330 strCaption = "sataController0";
1331 type = ovf::ResourceType_OtherStorageDevice; // 20
1332 // it seems that OVFTool always writes these two, and since we can only
1333 // have one SATA controller, we'll use this as well
1334 lAddress = 0;
1335 lBusNumber = 0;
1336
1337 if ( desc.strVboxCurrent.isEmpty() // AHCI is the default in VirtualBox
1338 || (!desc.strVboxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1339 )
1340 strResourceSubType = "AHCI";
1341 else
1342 throw setError(VBOX_E_NOT_SUPPORTED,
1343 tr("Invalid config string \"%s\" in SATA controller"), desc.strVboxCurrent.c_str());
1344
1345 // remember this ID
1346 idSATAController = ulInstanceID;
1347 lSATAControllerIndex = lIndexThis;
1348 }
1349 break;
1350
1351 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1352 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1353 /* <Item>
1354 <rasd:Caption>scsiController0</rasd:Caption>
1355 <rasd:Description>SCSI Controller</rasd:Description>
1356 <rasd:InstanceId>4</rasd:InstanceId>
1357 <rasd:ResourceType>6</rasd:ResourceType>
1358 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1359 <rasd:Address>0</rasd:Address>
1360 <rasd:BusNumber>0</rasd:BusNumber>
1361 </Item>
1362 */
1363 if (uLoop == 1)
1364 {
1365 strDescription = "SCSI Controller";
1366 strCaption = "scsiController0";
1367 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1368 // it seems that OVFTool always writes these two, and since we can only
1369 // have one SATA controller, we'll use this as well
1370 lAddress = 0;
1371 lBusNumber = 0;
1372
1373 if ( desc.strVboxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1374 || (!desc.strVboxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1375 )
1376 strResourceSubType = "lsilogic";
1377 else if (!desc.strVboxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1378 strResourceSubType = "buslogic";
1379 else if (!desc.strVboxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1380 strResourceSubType = "lsilogicsas";
1381 else
1382 throw setError(VBOX_E_NOT_SUPPORTED,
1383 tr("Invalid config string \"%s\" in SCSI/SAS controller"), desc.strVboxCurrent.c_str());
1384
1385 // remember this ID
1386 idSCSIController = ulInstanceID;
1387 lSCSIControllerIndex = lIndexThis;
1388 }
1389 break;
1390
1391 case VirtualSystemDescriptionType_HardDiskImage:
1392 /* <Item>
1393 <rasd:Caption>disk1</rasd:Caption>
1394 <rasd:InstanceId>8</rasd:InstanceId>
1395 <rasd:ResourceType>17</rasd:ResourceType>
1396 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1397 <rasd:Parent>4</rasd:Parent>
1398 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1399 </Item> */
1400 if (uLoop == 2)
1401 {
1402 uint32_t cDisks = stack.mapDisks.size();
1403 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1404
1405 strDescription = "Disk Image";
1406 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1407 type = ovf::ResourceType_HardDisk; // 17
1408
1409 // the following references the "<Disks>" XML block
1410 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1411
1412 // controller=<index>;channel=<c>
1413 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1414 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1415 int32_t lControllerIndex = -1;
1416 if (pos1 != Utf8Str::npos)
1417 {
1418 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1419 if (lControllerIndex == lIDEPrimaryControllerIndex)
1420 ulParent = idIDEPrimaryController;
1421 else if (lControllerIndex == lIDESecondaryControllerIndex)
1422 ulParent = idIDESecondaryController;
1423 else if (lControllerIndex == lSCSIControllerIndex)
1424 ulParent = idSCSIController;
1425 else if (lControllerIndex == lSATAControllerIndex)
1426 ulParent = idSATAController;
1427 }
1428 if (pos2 != Utf8Str::npos)
1429 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1430
1431 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1432 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1433
1434 if ( !ulParent
1435 || lAddressOnParent == -1
1436 )
1437 throw setError(VBOX_E_NOT_SUPPORTED,
1438 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfigCurrent.c_str());
1439
1440 stack.mapDisks[strDiskID] = &desc;
1441 }
1442 break;
1443
1444 case VirtualSystemDescriptionType_Floppy:
1445 if (uLoop == 1)
1446 {
1447 strDescription = "Floppy Drive";
1448 strCaption = "floppy0"; // this is what OVFTool writes
1449 type = ovf::ResourceType_FloppyDrive; // 14
1450 lAutomaticAllocation = 0;
1451 lAddressOnParent = 0; // this is what OVFTool writes
1452 }
1453 break;
1454
1455 case VirtualSystemDescriptionType_CDROM:
1456 /* <Item>
1457 <rasd:Caption>cdrom1</rasd:Caption>
1458 <rasd:InstanceId>8</rasd:InstanceId>
1459 <rasd:ResourceType>15</rasd:ResourceType>
1460 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1461 <rasd:Parent>4</rasd:Parent>
1462 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1463 </Item> */
1464 if (uLoop == 2)
1465 {
1466 //uint32_t cDisks = stack.mapDisks.size();
1467 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDVDs);
1468
1469 strDescription = "CD-ROM Drive";
1470 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1471 type = ovf::ResourceType_CDDrive; // 15
1472 lAutomaticAllocation = 1;
1473
1474 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1475 if (desc.strVboxCurrent.isNotEmpty())
1476 {
1477 // the following references the "<Disks>" XML block
1478 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1479 }
1480
1481 // controller=<index>;channel=<c>
1482 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1483 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1484 int32_t lControllerIndex = -1;
1485 if (pos1 != Utf8Str::npos)
1486 {
1487 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1488 if (lControllerIndex == lIDEPrimaryControllerIndex)
1489 ulParent = idIDEPrimaryController;
1490 else if (lControllerIndex == lIDESecondaryControllerIndex)
1491 ulParent = idIDESecondaryController;
1492 else if (lControllerIndex == lSCSIControllerIndex)
1493 ulParent = idSCSIController;
1494 else if (lControllerIndex == lSATAControllerIndex)
1495 ulParent = idSATAController;
1496 }
1497 if (pos2 != Utf8Str::npos)
1498 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1499
1500 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1501 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1502
1503 if ( !ulParent
1504 || lAddressOnParent == -1
1505 )
1506 throw setError(VBOX_E_NOT_SUPPORTED,
1507 tr("Missing or bad extra config string in DVD drive medium: \"%s\""), desc.strExtraConfigCurrent.c_str());
1508
1509 stack.mapDisks[strDiskID] = &desc;
1510 // there is no DVD drive map to update because it is
1511 // handled completely with this entry.
1512 }
1513 break;
1514
1515 case VirtualSystemDescriptionType_NetworkAdapter:
1516 /* <Item>
1517 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1518 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1519 <rasd:Connection>VM Network</rasd:Connection>
1520 <rasd:ElementName>VM network</rasd:ElementName>
1521 <rasd:InstanceID>3</rasd:InstanceID>
1522 <rasd:ResourceType>10</rasd:ResourceType>
1523 </Item> */
1524 if (uLoop == 2)
1525 {
1526 lAutomaticAllocation = 1;
1527 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1528 type = ovf::ResourceType_EthernetAdapter; // 10
1529 /* Set the hardware type to something useful.
1530 * To be compatible with vmware & others we set
1531 * PCNet32 for our PCNet types & E1000 for the
1532 * E1000 cards. */
1533 switch (desc.strVboxCurrent.toInt32())
1534 {
1535 case NetworkAdapterType_Am79C970A:
1536 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1537#ifdef VBOX_WITH_E1000
1538 case NetworkAdapterType_I82540EM:
1539 case NetworkAdapterType_I82545EM:
1540 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1541#endif /* VBOX_WITH_E1000 */
1542 }
1543 strConnection = desc.strOvf;
1544
1545 stack.mapNetworks[desc.strOvf] = true;
1546 }
1547 break;
1548
1549 case VirtualSystemDescriptionType_USBController:
1550 /* <Item ovf:required="false">
1551 <rasd:Caption>usb</rasd:Caption>
1552 <rasd:Description>USB Controller</rasd:Description>
1553 <rasd:InstanceId>3</rasd:InstanceId>
1554 <rasd:ResourceType>23</rasd:ResourceType>
1555 <rasd:Address>0</rasd:Address>
1556 <rasd:BusNumber>0</rasd:BusNumber>
1557 </Item> */
1558 if (uLoop == 1)
1559 {
1560 strDescription = "USB Controller";
1561 strCaption = "usb";
1562 type = ovf::ResourceType_USBController; // 23
1563 lAddress = 0; // this is what OVFTool writes
1564 lBusNumber = 0; // this is what OVFTool writes
1565 }
1566 break;
1567
1568 case VirtualSystemDescriptionType_SoundCard:
1569 /* <Item ovf:required="false">
1570 <rasd:Caption>sound</rasd:Caption>
1571 <rasd:Description>Sound Card</rasd:Description>
1572 <rasd:InstanceId>10</rasd:InstanceId>
1573 <rasd:ResourceType>35</rasd:ResourceType>
1574 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1575 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1576 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1577 </Item> */
1578 if (uLoop == 1)
1579 {
1580 strDescription = "Sound Card";
1581 strCaption = "sound";
1582 type = ovf::ResourceType_SoundCard; // 35
1583 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1584 lAutomaticAllocation = 0;
1585 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1586 }
1587 break;
1588 }
1589
1590 if (type)
1591 {
1592 xml::ElementNode *pItem;
1593 xml::ElementNode *pItemHelper;
1594 RTCString itemElement;
1595 RTCString itemElementHelper;
1596
1597 if (enFormat == ovf::OVFVersion_2_0)
1598 {
1599 if(uLoop == 2)
1600 {
1601 if (desc.type == VirtualSystemDescriptionType_NetworkAdapter)
1602 {
1603 itemElement = "epasd:";
1604 pItem = pelmVirtualHardwareSection->createChild("EthernetPortItem");
1605 }
1606 else if (desc.type == VirtualSystemDescriptionType_CDROM ||
1607 desc.type == VirtualSystemDescriptionType_HardDiskImage)
1608 {
1609 itemElement = "sasd:";
1610 pItem = pelmVirtualHardwareSection->createChild("StorageItem");
1611 }
1612 }
1613 else
1614 {
1615 itemElement = "rasd:";
1616 pItem = pelmVirtualHardwareSection->createChild("Item");
1617 }
1618 }
1619 else
1620 {
1621 itemElement = "rasd:";
1622 pItem = pelmVirtualHardwareSection->createChild("Item");
1623 }
1624
1625 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1626 // the elements from the rasd: namespace must be sorted by letter, and VMware
1627 // actually requires this as well (see public bug #6612)
1628
1629 if (lAddress != -1)
1630 {
1631 //pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1632 itemElementHelper = itemElement;
1633 pItemHelper = pItem->createChild(itemElementHelper.append("Address").c_str());
1634 pItemHelper->addContent(Utf8StrFmt("%d", lAddress));
1635 }
1636
1637 if (lAddressOnParent != -1)
1638 {
1639 //pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1640 itemElementHelper = itemElement;
1641 pItemHelper = pItem->createChild(itemElementHelper.append("AddressOnParent").c_str());
1642 pItemHelper->addContent(Utf8StrFmt("%d", lAddressOnParent));
1643 }
1644
1645 if (!strAllocationUnits.isEmpty())
1646 {
1647 //pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1648 itemElementHelper = itemElement;
1649 pItemHelper = pItem->createChild(itemElementHelper.append("AllocationUnits").c_str());
1650 pItemHelper->addContent(strAllocationUnits);
1651 }
1652
1653 if (lAutomaticAllocation != -1)
1654 {
1655 //pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1656 itemElementHelper = itemElement;
1657 pItemHelper = pItem->createChild(itemElementHelper.append("AutomaticAllocation").c_str());
1658 pItemHelper->addContent((lAutomaticAllocation) ? "true" : "false" );
1659 }
1660
1661 if (lBusNumber != -1)
1662 {
1663 if (enFormat == ovf::OVFVersion_0_9)
1664 {
1665 // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool
1666 //pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1667 itemElementHelper = itemElement;
1668 pItemHelper = pItem->createChild(itemElementHelper.append("BusNumber").c_str());
1669 pItemHelper->addContent(Utf8StrFmt("%d", lBusNumber));
1670 }
1671 }
1672
1673 if (!strCaption.isEmpty())
1674 {
1675 //pItem->createChild("rasd:Caption")->addContent(strCaption);
1676 itemElementHelper = itemElement;
1677 pItemHelper = pItem->createChild(itemElementHelper.append("Caption").c_str());
1678 pItemHelper->addContent(strCaption);
1679 }
1680
1681 if (!strConnection.isEmpty())
1682 {
1683 //pItem->createChild("rasd:Connection")->addContent(strConnection);
1684 itemElementHelper = itemElement;
1685 pItemHelper = pItem->createChild(itemElementHelper.append("Connection").c_str());
1686 pItemHelper->addContent(strConnection);
1687 }
1688
1689 if (!strDescription.isEmpty())
1690 {
1691 //pItem->createChild("rasd:Description")->addContent(strDescription);
1692 itemElementHelper = itemElement;
1693 pItemHelper = pItem->createChild(itemElementHelper.append("Description").c_str());
1694 pItemHelper->addContent(strDescription);
1695 }
1696
1697 if (!strCaption.isEmpty())
1698 {
1699 if (enFormat == ovf::OVFVersion_1_0)
1700 {
1701 //pItem->createChild("rasd:ElementName")->addContent(strCaption);
1702 itemElementHelper = itemElement;
1703 pItemHelper = pItem->createChild(itemElementHelper.append("ElementName").c_str());
1704 pItemHelper->addContent(strCaption);
1705 }
1706 }
1707
1708 if (!strHostResource.isEmpty())
1709 {
1710 //pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1711 itemElementHelper = itemElement;
1712 pItemHelper = pItem->createChild(itemElementHelper.append("HostResource").c_str());
1713 pItemHelper->addContent(strHostResource);
1714 }
1715
1716 {
1717 // <rasd:InstanceID>1</rasd:InstanceID>
1718 itemElementHelper = itemElement;
1719 if (enFormat == ovf::OVFVersion_0_9)
1720 //pelmInstanceID = pItem->createChild("rasd:InstanceId");
1721 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceId").c_str());
1722 else
1723 //pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1724 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceID").c_str());
1725
1726 pItemHelper->addContent(Utf8StrFmt("%d", ulInstanceID++));
1727 }
1728
1729 if (ulParent)
1730 {
1731 //pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1732 itemElementHelper = itemElement;
1733 pItemHelper = pItem->createChild(itemElementHelper.append("Parent").c_str());
1734 pItemHelper->addContent(Utf8StrFmt("%d", ulParent));
1735 }
1736
1737 if (!strResourceSubType.isEmpty())
1738 {
1739 //pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1740 itemElementHelper = itemElement;
1741 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceSubType").c_str());
1742 pItemHelper->addContent(strResourceSubType);
1743 }
1744
1745 {
1746 // <rasd:ResourceType>3</rasd:ResourceType>
1747 //pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1748 itemElementHelper = itemElement;
1749 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceType").c_str());
1750 pItemHelper->addContent(Utf8StrFmt("%d", type));
1751 }
1752
1753 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1754 if (lVirtualQuantity != -1)
1755 {
1756 //pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1757 itemElementHelper = itemElement;
1758 pItemHelper = pItem->createChild(itemElementHelper.append("VirtualQuantity").c_str());
1759 pItemHelper->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1760 }
1761 }
1762 }
1763 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1764
1765 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1766 // under the vbox: namespace
1767 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1768 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1769 pelmVBoxMachine->setAttribute("ovf:required", "false");
1770 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1771 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1772
1773 // create an empty machine config
1774 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(NULL);
1775
1776 writeLock.release();
1777 try
1778 {
1779 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1780 // fill the machine config
1781 vsdescThis->m->pMachine->copyMachineDataToSettings(*pConfig);
1782 // write the machine config to the vbox:Machine element
1783 pConfig->buildMachineXML(*pelmVBoxMachine,
1784 settings::MachineConfigFile::BuildMachineXML_WriteVboxVersionAttribute
1785 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
1786 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
1787 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1788 pllElementsWithUuidAttributes);
1789 delete pConfig;
1790 }
1791 catch (...)
1792 {
1793 writeLock.acquire();
1794 delete pConfig;
1795 throw;
1796 }
1797 writeLock.acquire();
1798}
1799
1800/**
1801 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1802 * and therefore runs on the OVF/OVA write worker thread. This runs in two contexts:
1803 *
1804 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::writeImpl();
1805 *
1806 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
1807 * called Appliance::writeS3(), which called Appliance::writeImpl(), which then called this. In other
1808 * words, to write to the cloud, the first worker thread first starts a second worker thread to create
1809 * temporary files and then uploads them to the S3 cloud server.
1810 *
1811 * @param pTask
1812 * @return
1813 */
1814HRESULT Appliance::writeFS(TaskOVF *pTask)
1815{
1816 LogFlowFuncEnter();
1817 LogFlowFunc(("ENTER appliance %p\n", this));
1818
1819 AutoCaller autoCaller(this);
1820 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1821
1822 HRESULT rc = S_OK;
1823
1824 // Lock the media tree early to make sure nobody else tries to make changes
1825 // to the tree. Also lock the IAppliance object for writing.
1826 AutoMultiWriteLock2 multiLock(&mVirtualBox->getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1827 // Additional protect the IAppliance object, cause we leave the lock
1828 // when starting the disk export and we don't won't block other
1829 // callers on this lengthy operations.
1830 m->state = Data::ApplianceExporting;
1831
1832 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1833 rc = writeFSOVF(pTask, multiLock);
1834 else
1835 rc = writeFSOVA(pTask, multiLock);
1836
1837 // reset the state so others can call methods again
1838 m->state = Data::ApplianceIdle;
1839
1840 LogFlowFunc(("rc=%Rhrc\n", rc));
1841 LogFlowFuncLeave();
1842 return rc;
1843}
1844
1845HRESULT Appliance::writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1846{
1847 LogFlowFuncEnter();
1848
1849 HRESULT rc = S_OK;
1850
1851 PVDINTERFACEIO pShaIo = 0;
1852 PVDINTERFACEIO pFileIo = 0;
1853 do
1854 {
1855 pShaIo = ShaCreateInterface();
1856 if (!pShaIo)
1857 {
1858 rc = E_OUTOFMEMORY;
1859 break;
1860 }
1861 pFileIo = FileCreateInterface();
1862 if (!pFileIo)
1863 {
1864 rc = E_OUTOFMEMORY;
1865 break;
1866 }
1867
1868 SHASTORAGE storage;
1869 RT_ZERO(storage);
1870 storage.fCreateDigest = m->fManifest;
1871 storage.fSha256 = m->fSha256;
1872
1873
1874 Utf8Str name = applianceIOName(applianceIOFile);
1875
1876 int vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
1877 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1878 &storage.pVDImageIfaces);
1879 if (RT_FAILURE(vrc))
1880 {
1881 rc = E_FAIL;
1882 break;
1883 }
1884 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1885 } while (0);
1886
1887 /* Cleanup */
1888 if (pShaIo)
1889 RTMemFree(pShaIo);
1890 if (pFileIo)
1891 RTMemFree(pFileIo);
1892
1893 LogFlowFuncLeave();
1894 return rc;
1895}
1896
1897HRESULT Appliance::writeFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1898{
1899 LogFlowFuncEnter();
1900
1901 RTTAR tar;
1902 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL, false);
1903 if (RT_FAILURE(vrc))
1904 return setError(VBOX_E_FILE_ERROR,
1905 tr("Could not create OVA file '%s' (%Rrc)"),
1906 pTask->locInfo.strPath.c_str(), vrc);
1907
1908 HRESULT rc = S_OK;
1909
1910 PVDINTERFACEIO pShaIo = 0;
1911 PVDINTERFACEIO pTarIo = 0;
1912 do
1913 {
1914 pShaIo = ShaCreateInterface();
1915 if (!pShaIo)
1916 {
1917 rc = E_OUTOFMEMORY;
1918 break;
1919 }
1920 pTarIo = TarCreateInterface();
1921 if (!pTarIo)
1922 {
1923 rc = E_OUTOFMEMORY;
1924 break;
1925 }
1926 SHASTORAGE storage;
1927 RT_ZERO(storage);
1928 storage.fCreateDigest = m->fManifest;
1929 storage.fSha256 = m->fSha256;
1930
1931 Utf8Str name = applianceIOName(applianceIOTar);
1932
1933 vrc = VDInterfaceAdd(&pTarIo->Core, name.c_str(),
1934 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
1935 &storage.pVDImageIfaces);
1936
1937 if (RT_FAILURE(vrc))
1938 {
1939 rc = E_FAIL;
1940 break;
1941 }
1942 rc = writeFSImpl(pTask, writeLock, pShaIo, &storage);
1943 } while (0);
1944
1945 RTTarClose(tar);
1946
1947 /* Cleanup */
1948 if (pShaIo)
1949 RTMemFree(pShaIo);
1950 if (pTarIo)
1951 RTMemFree(pTarIo);
1952
1953 /* Delete ova file on error */
1954 if (FAILED(rc))
1955 RTFileDelete(pTask->locInfo.strPath.c_str());
1956
1957 LogFlowFuncLeave();
1958 return rc;
1959}
1960
1961HRESULT Appliance::writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
1962{
1963 LogFlowFuncEnter();
1964
1965 HRESULT rc = S_OK;
1966
1967 list<STRPAIR> fileList;
1968 try
1969 {
1970 int vrc;
1971 // the XML stack contains two maps for disks and networks, which allows us to
1972 // a) have a list of unique disk names (to make sure the same disk name is only added once)
1973 // and b) keep a list of all networks
1974 XMLStack stack;
1975 // Scope this to free the memory as soon as this is finished
1976 {
1977 // Create a xml document
1978 xml::Document doc;
1979 // Now fully build a valid ovf document in memory
1980 buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
1981 /* Extract the OVA file name */
1982 Utf8Str strOvaFile = pTask->locInfo.strPath;
1983 /* Extract the path */
1984 Utf8Str strOvfFile = strOvaFile.stripExt().append(".ovf");
1985 // Create a memory buffer containing the XML. */
1986 void *pvBuf = 0;
1987 size_t cbSize;
1988 xml::XmlMemWriter writer;
1989 writer.write(doc, &pvBuf, &cbSize);
1990 if (RT_UNLIKELY(!pvBuf))
1991 throw setError(VBOX_E_FILE_ERROR,
1992 tr("Could not create OVF file '%s'"),
1993 strOvfFile.c_str());
1994 /* Write the ovf file to disk. */
1995 vrc = ShaWriteBuf(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
1996 if (RT_FAILURE(vrc))
1997 throw setError(VBOX_E_FILE_ERROR,
1998 tr("Could not create OVF file '%s' (%Rrc)"),
1999 strOvfFile.c_str(), vrc);
2000 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
2001 }
2002
2003 // We need a proper format description
2004 ComObjPtr<MediumFormat> formatTemp;
2005
2006 ComObjPtr<MediumFormat> format;
2007 // Scope for the AutoReadLock
2008 {
2009 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
2010 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2011 // We are always exporting to VMDK stream optimized for now
2012 formatTemp = pSysProps->mediumFormatFromExtension("iso");
2013
2014 format = pSysProps->mediumFormat("VMDK");
2015 if (format.isNull())
2016 throw setError(VBOX_E_NOT_SUPPORTED,
2017 tr("Invalid medium storage format"));
2018 }
2019
2020 // Finally, write out the disks!
2021 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
2022 for (itS = stack.mapDisks.begin();
2023 itS != stack.mapDisks.end();
2024 ++itS)
2025 {
2026 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
2027
2028 // source path: where the VBox image is
2029 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
2030
2031 //skip empty Medium. In common, It's may be empty CD/DVD
2032 if (strSrcFilePath.isEmpty())
2033 continue;
2034
2035 // Do NOT check here whether the file exists. findHardDisk will
2036 // figure that out, and filesystem-based tests are simply wrong
2037 // in the general case (think of iSCSI).
2038
2039 // clone the disk:
2040 ComObjPtr<Medium> pSourceDisk;
2041
2042 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2043
2044 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2045 {
2046 rc = mVirtualBox->findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2047 if (FAILED(rc)) throw rc;
2048 }
2049 else//may be CD or DVD
2050 {
2051 rc = mVirtualBox->findDVDOrFloppyImage(DeviceType_DVD,
2052 NULL,
2053 strSrcFilePath,
2054 true,
2055 &pSourceDisk);
2056 if (FAILED(rc)) throw rc;
2057 }
2058
2059 Bstr uuidSource;
2060 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2061 if (FAILED(rc)) throw rc;
2062 Guid guidSource(uuidSource);
2063
2064 // output filename
2065 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2066 // target path needs to be composed from where the output OVF is
2067 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2068 strTargetFilePath.stripFilename()
2069 .append("/")
2070 .append(strTargetFileNameOnly);
2071
2072 // The exporting requests a lock on the media tree. So leave our lock temporary.
2073 writeLock.release();
2074 try
2075 {
2076 // advance to the next operation
2077 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"), RTPathFilename(strTargetFilePath.c_str())).raw(),
2078 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally
2079
2080 // create a flat copy of the source disk image
2081 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2082 {
2083 ComObjPtr<Progress> pProgress2;
2084 pProgress2.createObject();
2085 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetFilePath.c_str()).raw(), TRUE);
2086 if (FAILED(rc)) throw rc;
2087
2088 rc = pSourceDisk->exportFile(strTargetFilePath.c_str(),
2089 format,
2090 MediumVariant_VmdkStreamOptimized,
2091 pIfIo,
2092 pStorage,
2093 pProgress2);
2094 if (FAILED(rc)) throw rc;
2095
2096 ComPtr<IProgress> pProgress3(pProgress2);
2097 // now wait for the background disk operation to complete; this throws HRESULTs on error
2098 waitForAsyncProgress(pTask->pProgress, pProgress3);
2099 }
2100 else
2101 {
2102 //copy/clone CD/DVD image
2103 /* Read the ISO file into a memory buffer */
2104 {
2105 void *pvTmpBuf = 0;
2106 size_t cbSize = 0;
2107
2108 if (RTFileExists(strSrcFilePath.c_str()))
2109 {
2110 // open ISO file and read one into memory buffer
2111 RTFILE pFile = NULL;
2112 vrc = RTFileOpen(&pFile, strSrcFilePath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
2113 if (RT_SUCCESS(vrc) && pFile != NULL)
2114 {
2115 uint64_t cbFile = 0;
2116
2117 vrc = RTFileGetSize(pFile, &cbFile);
2118
2119 if (RT_SUCCESS(vrc))
2120 pvTmpBuf = RTMemAllocZ(cbFile);
2121 else
2122 throw setError(VBOX_E_FILE_ERROR,
2123 tr("Could not get size of the ISO file '%s' "),
2124 RTPathFilename(strSrcFilePath.c_str()));
2125
2126 vrc = RTFileRead(pFile, pvTmpBuf, cbFile, &cbSize);
2127
2128 if (RT_FAILURE(vrc))
2129 {
2130 if (pvTmpBuf)
2131 RTMemFree(pvTmpBuf);
2132 throw setError(VBOX_E_FILE_ERROR,
2133 tr("Could not read the ISO file '%s' (%Rrc)"),
2134 RTPathFilename(strSrcFilePath.c_str()), vrc);
2135 }
2136 }
2137
2138 RTFileClose(pFile);
2139 }
2140
2141 /* Write the ISO file to disk. */
2142 vrc = ShaWriteBuf(strTargetFilePath.c_str(), pvTmpBuf, cbSize, pIfIo, pStorage);
2143 RTMemFree(pvTmpBuf);
2144 if (RT_FAILURE(vrc))
2145 throw setError(VBOX_E_FILE_ERROR,
2146 tr("Could not create ISO file '%s' (%Rrc)"),
2147 strTargetFilePath.c_str(), vrc);
2148 }
2149 }
2150 }
2151 catch (HRESULT rc3)
2152 {
2153 writeLock.acquire();
2154 // Todo: file deletion on error? If not, we can remove that whole try/catch block.
2155 throw rc3;
2156 }
2157 // Finished, lock again (so nobody mess around with the medium tree
2158 // in the meantime)
2159 writeLock.acquire();
2160 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
2161 }
2162
2163 if (m->fManifest)
2164 {
2165 // Create & write the manifest file
2166 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
2167 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2168 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2169 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally);
2170 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
2171 size_t i = 0;
2172 list<STRPAIR>::const_iterator it1;
2173 for (it1 = fileList.begin();
2174 it1 != fileList.end();
2175 ++it1, ++i)
2176 {
2177 paManifestFiles[i].pszTestFile = (*it1).first.c_str();
2178 paManifestFiles[i].pszTestDigest = (*it1).second.c_str();
2179 }
2180 void *pvBuf;
2181 size_t cbSize;
2182 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
2183 paManifestFiles, fileList.size());
2184 RTMemFree(paManifestFiles);
2185 if (RT_FAILURE(vrc))
2186 throw setError(VBOX_E_FILE_ERROR,
2187 tr("Could not create manifest file '%s' (%Rrc)"),
2188 strMfFileName.c_str(), vrc);
2189 /* Disable digest creation for the manifest file. */
2190 pStorage->fCreateDigest = false;
2191 /* Write the manifest file to disk. */
2192 vrc = ShaWriteBuf(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2193 RTMemFree(pvBuf);
2194 if (RT_FAILURE(vrc))
2195 throw setError(VBOX_E_FILE_ERROR,
2196 tr("Could not create manifest file '%s' (%Rrc)"),
2197 strMfFilePath.c_str(), vrc);
2198 }
2199 }
2200 catch (RTCError &x) // includes all XML exceptions
2201 {
2202 rc = setError(VBOX_E_FILE_ERROR,
2203 x.what());
2204 }
2205 catch (HRESULT aRC)
2206 {
2207 rc = aRC;
2208 }
2209
2210 /* Cleanup on error */
2211 if (FAILED(rc))
2212 {
2213 list<STRPAIR>::const_iterator it1;
2214 for (it1 = fileList.begin();
2215 it1 != fileList.end();
2216 ++it1)
2217 pIfIo->pfnDelete(pStorage, (*it1).first.c_str());
2218 }
2219
2220 LogFlowFunc(("rc=%Rhrc\n", rc));
2221 LogFlowFuncLeave();
2222
2223 return rc;
2224}
2225
2226#ifdef VBOX_WITH_S3
2227/**
2228 * Worker code for writing out OVF to the cloud. This is called from Appliance::taskThreadWriteOVF()
2229 * in S3 mode and therefore runs on the OVF write worker thread. This then starts a second worker
2230 * thread to create temporary files (see Appliance::writeFS()).
2231 *
2232 * @param pTask
2233 * @return
2234 */
2235HRESULT Appliance::writeS3(TaskOVF *pTask)
2236{
2237 LogFlowFuncEnter();
2238 LogFlowFunc(("Appliance %p\n", this));
2239
2240 AutoCaller autoCaller(this);
2241 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2242
2243 HRESULT rc = S_OK;
2244
2245 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
2246
2247 int vrc = VINF_SUCCESS;
2248 RTS3 hS3 = NIL_RTS3;
2249 char szOSTmpDir[RTPATH_MAX];
2250 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
2251 /* The template for the temporary directory created below */
2252 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
2253 list< pair<Utf8Str, ULONG> > filesList;
2254
2255 // todo:
2256 // - usable error codes
2257 // - seems snapshot filenames are problematic {uuid}.vdi
2258 try
2259 {
2260 /* Extract the bucket */
2261 Utf8Str tmpPath = pTask->locInfo.strPath;
2262 Utf8Str bucket;
2263 parseBucket(tmpPath, bucket);
2264
2265 /* We need a temporary directory which we can put the OVF file & all
2266 * disk images in */
2267 vrc = RTDirCreateTemp(pszTmpDir, 0700);
2268 if (RT_FAILURE(vrc))
2269 throw setError(VBOX_E_FILE_ERROR,
2270 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2271
2272 /* The temporary name of the target OVF file */
2273 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2274
2275 /* Prepare the temporary writing of the OVF */
2276 ComObjPtr<Progress> progress;
2277 /* Create a temporary file based location info for the sub task */
2278 LocationInfo li;
2279 li.strPath = strTmpOvf;
2280 rc = writeImpl(pTask->enFormat, li, progress);
2281 if (FAILED(rc)) throw rc;
2282
2283 /* Unlock the appliance for the writing thread */
2284 appLock.release();
2285 /* Wait until the writing is done, but report the progress back to the
2286 caller */
2287 ComPtr<IProgress> progressInt(progress);
2288 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2289
2290 /* Again lock the appliance for the next steps */
2291 appLock.acquire();
2292
2293 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
2294 if (RT_FAILURE(vrc))
2295 throw setError(VBOX_E_FILE_ERROR,
2296 tr("Cannot find source file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
2297 /* Add the OVF file */
2298 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightForXmlOperation)); /* Use 1% of the total for the OVF file upload */
2299 /* Add the manifest file */
2300 if (m->fManifest)
2301 {
2302 Utf8Str strMfFile = Utf8Str(strTmpOvf).stripExt().append(".mf");
2303 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightForXmlOperation)); /* Use 1% of the total for the manifest file upload */
2304 }
2305
2306 /* Now add every disks of every virtual system */
2307 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2308 for (it = m->virtualSystemDescriptions.begin();
2309 it != m->virtualSystemDescriptions.end();
2310 ++it)
2311 {
2312 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2313 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2314 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2315 for (itH = avsdeHDs.begin();
2316 itH != avsdeHDs.end();
2317 ++itH)
2318 {
2319 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
2320 /* Target path needs to be composed from where the output OVF is */
2321 Utf8Str strTargetFilePath(strTmpOvf);
2322 strTargetFilePath.stripFilename();
2323 strTargetFilePath.append("/");
2324 strTargetFilePath.append(strTargetFileNameOnly);
2325 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
2326 if (RT_FAILURE(vrc))
2327 throw setError(VBOX_E_FILE_ERROR,
2328 tr("Cannot find source file '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2329 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
2330 }
2331 }
2332 /* Next we have to upload the OVF & all disk images */
2333 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2334 if (RT_FAILURE(vrc))
2335 throw setError(VBOX_E_IPRT_ERROR,
2336 tr("Cannot create S3 service handler"));
2337 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2338
2339 /* Upload all files */
2340 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2341 {
2342 const pair<Utf8Str, ULONG> &s = (*it1);
2343 char *pszFilename = RTPathFilename(s.first.c_str());
2344 /* Advance to the next operation */
2345 pTask->pProgress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename).raw(), s.second);
2346 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
2347 if (RT_FAILURE(vrc))
2348 {
2349 if (vrc == VERR_S3_CANCELED)
2350 break;
2351 else if (vrc == VERR_S3_ACCESS_DENIED)
2352 throw setError(E_ACCESSDENIED,
2353 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);
2354 else if (vrc == VERR_S3_NOT_FOUND)
2355 throw setError(VBOX_E_FILE_ERROR,
2356 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
2357 else
2358 throw setError(VBOX_E_IPRT_ERROR,
2359 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
2360 }
2361 }
2362 }
2363 catch(HRESULT aRC)
2364 {
2365 rc = aRC;
2366 }
2367 /* Cleanup */
2368 RTS3Destroy(hS3);
2369 /* Delete all files which where temporary created */
2370 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2371 {
2372 const char *pszFilePath = (*it1).first.c_str();
2373 if (RTPathExists(pszFilePath))
2374 {
2375 vrc = RTFileDelete(pszFilePath);
2376 if (RT_FAILURE(vrc))
2377 rc = setError(VBOX_E_FILE_ERROR,
2378 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2379 }
2380 }
2381 /* Delete the temporary directory */
2382 if (RTPathExists(pszTmpDir))
2383 {
2384 vrc = RTDirRemove(pszTmpDir);
2385 if (RT_FAILURE(vrc))
2386 rc = setError(VBOX_E_FILE_ERROR,
2387 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2388 }
2389 if (pszTmpDir)
2390 RTStrFree(pszTmpDir);
2391
2392 LogFlowFunc(("rc=%Rhrc\n", rc));
2393 LogFlowFuncLeave();
2394
2395 return rc;
2396}
2397#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