VirtualBox

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

Last change on this file since 49058 was 49047, checked in by vboxsync, 11 years ago

pr6927. the state of CD/DVD image is checked, only ISO image is granted to export, host CD/DVD isn't exported now.

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