VirtualBox

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

Last change on this file since 48311 was 47401, checked in by vboxsync, 11 years ago

Main,Frontends: Second step of USB controller rework. There is one controller instance for every USB controller now. Adapt frontends and testsuite to work with the changed API

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