VirtualBox

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

Last change on this file since 49875 was 49795, checked in by vboxsync, 11 years ago

6813 - stage 3 rev 1

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