VirtualBox

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

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

Main: missing initialization

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