VirtualBox

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

Last change on this file since 48600 was 48425, checked in by vboxsync, 11 years ago

Main: ApplianceImplExport: do not crash if VM has no CD/DVD medium.

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