VirtualBox

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

最後變更 在這個檔案從48339是 48339,由 vboxsync 提交於 12 年 前

1st approach, to skip a real disk mounted to the CD-ROM on the host.

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

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