VirtualBox

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

Last change on this file since 97698 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 125.4 KB
Line 
1/* $Id: ApplianceImplExport.cpp 96407 2022-08-22 17:43:14Z vboxsync $ */
2/** @file
3 * IAppliance and IVirtualSystem COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2008-2022 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28#define LOG_GROUP LOG_GROUP_MAIN_APPLIANCE
29#include <iprt/buildconfig.h>
30#include <iprt/path.h>
31#include <iprt/dir.h>
32#include <iprt/param.h>
33#include <iprt/s3.h>
34#include <iprt/manifest.h>
35#include <iprt/stream.h>
36#include <iprt/zip.h>
37
38#include <VBox/version.h>
39
40#include "ApplianceImpl.h"
41#include "VirtualBoxImpl.h"
42#include "ProgressImpl.h"
43#include "MachineImpl.h"
44#include "MediumImpl.h"
45#include "LoggingNew.h"
46#include "Global.h"
47#include "MediumFormatImpl.h"
48#include "SystemPropertiesImpl.h"
49
50#include "AutoCaller.h"
51
52#include "ApplianceImplPrivate.h"
53
54using namespace std;
55
56////////////////////////////////////////////////////////////////////////////////
57//
58// IMachine public methods
59//
60////////////////////////////////////////////////////////////////////////////////
61
62// This code is here so we won't have to include the appliance headers in the
63// IMachine implementation, and we also need to access private appliance data.
64
65/**
66* Public method implementation.
67* @param aAppliance Appliance object.
68* @param aLocation Where to store the appliance.
69* @param aDescription Appliance description.
70* @return
71*/
72HRESULT Machine::exportTo(const ComPtr<IAppliance> &aAppliance, const com::Utf8Str &aLocation,
73 ComPtr<IVirtualSystemDescription> &aDescription)
74{
75 HRESULT rc = S_OK;
76
77 if (!aAppliance)
78 return E_POINTER;
79
80 ComObjPtr<VirtualSystemDescription> pNewDesc;
81
82 try
83 {
84 IAppliance *iAppliance = aAppliance;
85 Appliance *pAppliance = static_cast<Appliance*>(iAppliance);
86
87 LocationInfo locInfo;
88 i_parseURI(aLocation, locInfo);
89
90 Utf8Str strBasename(locInfo.strPath);
91 strBasename.stripPath().stripSuffix();
92 if (locInfo.strPath.endsWith(".tar.gz", Utf8Str::CaseSensitive))
93 strBasename.stripSuffix();
94
95 // create a new virtual system to store in the appliance
96 rc = pNewDesc.createObject();
97 if (FAILED(rc)) throw rc;
98 rc = pNewDesc->init();
99 if (FAILED(rc)) throw rc;
100
101 // store the machine object so we can dump the XML in Appliance::Write()
102 pNewDesc->m->pMachine = this;
103
104#ifdef VBOX_WITH_USB
105 // first, call the COM methods, as they request locks
106 BOOL fUSBEnabled = FALSE;
107 com::SafeIfaceArray<IUSBController> usbControllers;
108 rc = COMGETTER(USBControllers)(ComSafeArrayAsOutParam(usbControllers));
109 if (SUCCEEDED(rc))
110 {
111 for (unsigned i = 0; i < usbControllers.size(); ++i)
112 {
113 USBControllerType_T enmType;
114
115 rc = usbControllers[i]->COMGETTER(Type)(&enmType);
116 if (FAILED(rc)) throw rc;
117
118 if (enmType == USBControllerType_OHCI)
119 fUSBEnabled = TRUE;
120 }
121 }
122#endif /* VBOX_WITH_USB */
123
124 // request the machine lock while accessing internal members
125 AutoReadLock alock1(this COMMA_LOCKVAL_SRC_POS);
126
127 ComPtr<IAudioAdapter> pAudioAdapter;
128 rc = mAudioSettings->COMGETTER(Adapter)(pAudioAdapter.asOutParam());
129 if (FAILED(rc)) throw rc;
130 BOOL fAudioEnabled;
131 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
132 if (FAILED(rc)) throw rc;
133 AudioControllerType_T audioController;
134 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
135 if (FAILED(rc)) throw rc;
136
137 // get name
138 Utf8Str strVMName = mUserData->s.strName;
139 // get description
140 Utf8Str strDescription = mUserData->s.strDescription;
141 // get guest OS
142 Utf8Str strOsTypeVBox = mUserData->s.strOsType;
143 // CPU count
144 uint32_t cCPUs = mHWData->mCPUCount;
145 // memory size in MB
146 uint32_t ulMemSizeMB = mHWData->mMemorySize;
147 // VRAM size?
148 // BIOS settings?
149 // 3D acceleration enabled?
150 // hardware virtualization enabled?
151 // nested paging enabled?
152 // HWVirtExVPIDEnabled?
153 // PAEEnabled?
154 // Long mode enabled?
155 BOOL fLongMode;
156 rc = GetCPUProperty(CPUPropertyType_LongMode, &fLongMode);
157 if (FAILED(rc)) throw rc;
158
159 // snapshotFolder?
160 // VRDPServer?
161
162 /* Guest OS type */
163 ovf::CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str(), fLongMode);
164 pNewDesc->i_addEntry(VirtualSystemDescriptionType_OS,
165 "",
166 Utf8StrFmt("%RI32", cim),
167 strOsTypeVBox);
168
169 /* VM name */
170 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Name,
171 "",
172 strVMName,
173 strVMName);
174
175 // description
176 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Description,
177 "",
178 strDescription,
179 strDescription);
180
181 /* CPU count*/
182 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
183 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CPU,
184 "",
185 strCpuCount,
186 strCpuCount);
187
188 /* Memory */
189 Utf8Str strMemory = Utf8StrFmt("%RI64", (uint64_t)ulMemSizeMB * _1M);
190 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Memory,
191 "",
192 strMemory,
193 strMemory);
194
195 // the one VirtualBox IDE controller has two channels with two ports each, which is
196 // considered two IDE controllers with two ports each by OVF, so export it as two
197 int32_t lIDEControllerPrimaryIndex = 0;
198 int32_t lIDEControllerSecondaryIndex = 0;
199 int32_t lSATAControllerIndex = 0;
200 int32_t lSCSIControllerIndex = 0;
201 int32_t lVirtioSCSIControllerIndex = 0;
202
203 /* Fetch all available storage controllers */
204 com::SafeIfaceArray<IStorageController> nwControllers;
205 rc = COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(nwControllers));
206 if (FAILED(rc)) throw rc;
207
208 ComPtr<IStorageController> pIDEController;
209 ComPtr<IStorageController> pSATAController;
210 ComPtr<IStorageController> pSCSIController;
211 ComPtr<IStorageController> pVirtioSCSIController;
212 ComPtr<IStorageController> pSASController;
213 for (size_t j = 0; j < nwControllers.size(); ++j)
214 {
215 StorageBus_T eType;
216 rc = nwControllers[j]->COMGETTER(Bus)(&eType);
217 if (FAILED(rc)) throw rc;
218 if ( eType == StorageBus_IDE
219 && pIDEController.isNull())
220 pIDEController = nwControllers[j];
221 else if ( eType == StorageBus_SATA
222 && pSATAController.isNull())
223 pSATAController = nwControllers[j];
224 else if ( eType == StorageBus_SCSI
225 && pSCSIController.isNull())
226 pSCSIController = nwControllers[j];
227 else if ( eType == StorageBus_SAS
228 && pSASController.isNull())
229 pSASController = nwControllers[j];
230 else if ( eType == StorageBus_VirtioSCSI
231 && pVirtioSCSIController.isNull())
232 pVirtioSCSIController = nwControllers[j];
233 }
234
235// <const name="HardDiskControllerIDE" value="6" />
236 if (!pIDEController.isNull())
237 {
238 StorageControllerType_T ctlr;
239 rc = pIDEController->COMGETTER(ControllerType)(&ctlr);
240 if (FAILED(rc)) throw rc;
241
242 Utf8Str strVBox;
243 switch (ctlr)
244 {
245 case StorageControllerType_PIIX3: strVBox = "PIIX3"; break;
246 case StorageControllerType_PIIX4: strVBox = "PIIX4"; break;
247 case StorageControllerType_ICH6: strVBox = "ICH6"; break;
248 default: break; /* Shut up MSC. */
249 }
250
251 if (strVBox.length())
252 {
253 lIDEControllerPrimaryIndex = (int32_t)pNewDesc->m->maDescriptions.size();
254 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
255 Utf8StrFmt("%d", lIDEControllerPrimaryIndex), // strRef
256 strVBox, // aOvfValue
257 strVBox); // aVBoxValue
258 lIDEControllerSecondaryIndex = lIDEControllerPrimaryIndex + 1;
259 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
260 Utf8StrFmt("%d", lIDEControllerSecondaryIndex),
261 strVBox,
262 strVBox);
263 }
264 }
265
266// <const name="HardDiskControllerSATA" value="7" />
267 if (!pSATAController.isNull())
268 {
269 Utf8Str strVBox = "AHCI";
270 lSATAControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
271 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
272 Utf8StrFmt("%d", lSATAControllerIndex),
273 strVBox,
274 strVBox);
275 }
276
277// <const name="HardDiskControllerSCSI" value="8" />
278 if (!pSCSIController.isNull())
279 {
280 StorageControllerType_T ctlr;
281 rc = pSCSIController->COMGETTER(ControllerType)(&ctlr);
282 if (SUCCEEDED(rc))
283 {
284 Utf8Str strVBox = "LsiLogic"; // the default in VBox
285 switch (ctlr)
286 {
287 case StorageControllerType_LsiLogic: strVBox = "LsiLogic"; break;
288 case StorageControllerType_BusLogic: strVBox = "BusLogic"; break;
289 default: break; /* Shut up MSC. */
290 }
291 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
292 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
293 Utf8StrFmt("%d", lSCSIControllerIndex),
294 strVBox,
295 strVBox);
296 }
297 else
298 throw rc;
299 }
300
301 if (!pSASController.isNull())
302 {
303 // VirtualBox considers the SAS controller a class of its own but in OVF
304 // it should be a SCSI controller
305 Utf8Str strVBox = "LsiLogicSas";
306 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
307 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSAS,
308 Utf8StrFmt("%d", lSCSIControllerIndex),
309 strVBox,
310 strVBox);
311 }
312
313 if (!pVirtioSCSIController.isNull())
314 {
315 StorageControllerType_T ctlr;
316 rc = pVirtioSCSIController->COMGETTER(ControllerType)(&ctlr);
317 if (SUCCEEDED(rc))
318 {
319 Utf8Str strVBox = "VirtioSCSI"; // the default in VBox
320 switch (ctlr)
321 {
322 case StorageControllerType_VirtioSCSI: strVBox = "VirtioSCSI"; break;
323 default: break; /* Shut up MSC. */
324 }
325 lVirtioSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
326 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerVirtioSCSI,
327 Utf8StrFmt("%d", lVirtioSCSIControllerIndex),
328 strVBox,
329 strVBox);
330 }
331 else
332 throw rc;
333 }
334
335// <const name="HardDiskImage" value="9" />
336// <const name="Floppy" value="18" />
337// <const name="CDROM" value="19" />
338
339 for (MediumAttachmentList::const_iterator
340 it = mMediumAttachments->begin();
341 it != mMediumAttachments->end();
342 ++it)
343 {
344 ComObjPtr<MediumAttachment> pHDA = *it;
345
346 // the attachment's data
347 ComPtr<IMedium> pMedium;
348 ComPtr<IStorageController> ctl;
349 Bstr controllerName;
350
351 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
352 if (FAILED(rc)) throw rc;
353
354 rc = GetStorageControllerByName(controllerName.raw(), ctl.asOutParam());
355 if (FAILED(rc)) throw rc;
356
357 StorageBus_T storageBus;
358 DeviceType_T deviceType;
359 LONG lChannel;
360 LONG lDevice;
361
362 rc = ctl->COMGETTER(Bus)(&storageBus);
363 if (FAILED(rc)) throw rc;
364
365 rc = pHDA->COMGETTER(Type)(&deviceType);
366 if (FAILED(rc)) throw rc;
367
368 rc = pHDA->COMGETTER(Port)(&lChannel);
369 if (FAILED(rc)) throw rc;
370
371 rc = pHDA->COMGETTER(Device)(&lDevice);
372 if (FAILED(rc)) throw rc;
373
374 rc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
375 if (FAILED(rc)) throw rc;
376 if (pMedium.isNull())
377 {
378 Utf8Str strStBus;
379 if ( storageBus == StorageBus_IDE)
380 strStBus = "IDE";
381 else if ( storageBus == StorageBus_SATA)
382 strStBus = "SATA";
383 else if ( storageBus == StorageBus_SCSI)
384 strStBus = "SCSI";
385 else if ( storageBus == StorageBus_SAS)
386 strStBus = "SAS";
387 else if ( storageBus == StorageBus_VirtioSCSI)
388 strStBus = "VirtioSCSI";
389
390 LogRel(("Warning: skip the medium (bus: %s, slot: %d, port: %d). No storage device attached.\n",
391 strStBus.c_str(), lDevice, lChannel));
392 continue;
393 }
394
395 Utf8Str strTargetImageName;
396 Utf8Str strLocation;
397 LONG64 llSize = 0;
398
399 if ( deviceType == DeviceType_HardDisk
400 && pMedium)
401 {
402 Bstr bstrLocation;
403
404 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
405 if (FAILED(rc)) throw rc;
406 strLocation = bstrLocation;
407
408 // find the source's base medium for two things:
409 // 1) we'll use its name to determine the name of the target disk, which is readable,
410 // as opposed to the UUID filename of a differencing image, if pMedium is one
411 // 2) we need the size of the base image so we can give it to addEntry(), and later
412 // on export, the progress will be based on that (and not the diff image)
413 ComPtr<IMedium> pBaseMedium;
414 rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
415 // returns pMedium if there are no diff images
416 if (FAILED(rc)) throw rc;
417
418 strTargetImageName = Utf8StrFmt("%s-disk%.3d.vmdk", strBasename.c_str(), ++pAppliance->m->cDisks);
419 if (strTargetImageName.length() > RTTAR_NAME_MAX)
420 throw setError(VBOX_E_NOT_SUPPORTED,
421 tr("Cannot attach disk '%s' -- file name too long"), strTargetImageName.c_str());
422
423 // force reading state, or else size will be returned as 0
424 MediumState_T ms;
425 rc = pBaseMedium->RefreshState(&ms);
426 if (FAILED(rc)) throw rc;
427
428 rc = pBaseMedium->COMGETTER(Size)(&llSize);
429 if (FAILED(rc)) throw rc;
430
431 /* If the medium is encrypted add the key identifier to the list. */
432 IMedium *iBaseMedium = pBaseMedium;
433 Medium *pBase = static_cast<Medium*>(iBaseMedium);
434 const com::Utf8Str strKeyId = pBase->i_getKeyId();
435 if (!strKeyId.isEmpty())
436 {
437 IMedium *iMedium = pMedium;
438 Medium *pMed = static_cast<Medium*>(iMedium);
439 com::Guid mediumUuid = pMed->i_getId();
440 bool fKnown = false;
441
442 /* Check whether the ID is already in our sequence, add it otherwise. */
443 for (unsigned i = 0; i < pAppliance->m->m_vecPasswordIdentifiers.size(); i++)
444 {
445 if (strKeyId.equals(pAppliance->m->m_vecPasswordIdentifiers[i]))
446 {
447 fKnown = true;
448 break;
449 }
450 }
451
452 if (!fKnown)
453 {
454 GUIDVEC vecMediumIds;
455
456 vecMediumIds.push_back(mediumUuid);
457 pAppliance->m->m_vecPasswordIdentifiers.push_back(strKeyId);
458 pAppliance->m->m_mapPwIdToMediumIds.insert(std::pair<com::Utf8Str, GUIDVEC>(strKeyId, vecMediumIds));
459 }
460 else
461 {
462 std::map<com::Utf8Str, GUIDVEC>::iterator itMap = pAppliance->m->m_mapPwIdToMediumIds.find(strKeyId);
463 if (itMap == pAppliance->m->m_mapPwIdToMediumIds.end())
464 throw setError(E_FAIL, tr("Internal error adding a medium UUID to the map"));
465 itMap->second.push_back(mediumUuid);
466 }
467 }
468 }
469 else if ( deviceType == DeviceType_DVD
470 && pMedium)
471 {
472 /*
473 * check the minimal rules to grant access to export an image
474 * 1. no host drive CD/DVD image
475 * 2. the image must be accessible and readable
476 * 3. only ISO image is exported
477 */
478
479 //1. no host drive CD/DVD image
480 BOOL fHostDrive = false;
481 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
482 if (FAILED(rc)) throw rc;
483
484 if(fHostDrive)
485 continue;
486
487 //2. the image must be accessible and readable
488 MediumState_T ms;
489 rc = pMedium->RefreshState(&ms);
490 if (FAILED(rc)) throw rc;
491
492 if (ms != MediumState_Created)
493 continue;
494
495 //3. only ISO image is exported
496 Bstr bstrLocation;
497 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
498 if (FAILED(rc)) throw rc;
499
500 strLocation = bstrLocation;
501
502 Utf8Str ext = strLocation;
503 ext.assignEx(RTPathSuffix(strLocation.c_str()));//returns extension with dot (".iso")
504
505 int eq = ext.compare(".iso", Utf8Str::CaseInsensitive);
506 if (eq != 0)
507 continue;
508
509 strTargetImageName = Utf8StrFmt("%s-disk%.3d.iso", strBasename.c_str(), ++pAppliance->m->cDisks);
510 if (strTargetImageName.length() > RTTAR_NAME_MAX)
511 throw setError(VBOX_E_NOT_SUPPORTED,
512 tr("Cannot attach image '%s' -- file name too long"), strTargetImageName.c_str());
513
514 rc = pMedium->COMGETTER(Size)(&llSize);
515 if (FAILED(rc)) throw rc;
516 }
517 // and how this translates to the virtual system
518 int32_t lControllerVsys = 0;
519 LONG lChannelVsys;
520
521 switch (storageBus)
522 {
523 case StorageBus_IDE:
524 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
525 // and it must be updated when that is changed!
526 // Before 3.2 we exported one IDE controller with channel 0-3, but we now maintain
527 // compatibility with what VMware does and export two IDE controllers with two channels each
528
529 if (lChannel == 0 && lDevice == 0) // primary master
530 {
531 lControllerVsys = lIDEControllerPrimaryIndex;
532 lChannelVsys = 0;
533 }
534 else if (lChannel == 0 && lDevice == 1) // primary slave
535 {
536 lControllerVsys = lIDEControllerPrimaryIndex;
537 lChannelVsys = 1;
538 }
539 else if (lChannel == 1 && lDevice == 0) // secondary master; by default this is the CD-ROM but
540 // as of VirtualBox 3.1 that can change
541 {
542 lControllerVsys = lIDEControllerSecondaryIndex;
543 lChannelVsys = 0;
544 }
545 else if (lChannel == 1 && lDevice == 1) // secondary slave
546 {
547 lControllerVsys = lIDEControllerSecondaryIndex;
548 lChannelVsys = 1;
549 }
550 else
551 throw setError(VBOX_E_NOT_SUPPORTED,
552 tr("Cannot handle medium attachment: channel is %d, device is %d"), lChannel, lDevice);
553 break;
554
555 case StorageBus_SATA:
556 lChannelVsys = lChannel; // should be between 0 and 29
557 lControllerVsys = lSATAControllerIndex;
558 break;
559
560 case StorageBus_VirtioSCSI:
561 lChannelVsys = lChannel; // should be between 0 and 255
562 lControllerVsys = lVirtioSCSIControllerIndex;
563 break;
564
565 case StorageBus_SCSI:
566 case StorageBus_SAS:
567 lChannelVsys = lChannel; // should be between 0 and 15
568 lControllerVsys = lSCSIControllerIndex;
569 break;
570
571 case StorageBus_Floppy:
572 lChannelVsys = 0;
573 lControllerVsys = 0;
574 break;
575
576 default:
577 throw setError(VBOX_E_NOT_SUPPORTED,
578 tr("Cannot handle medium attachment: storageBus is %d, channel is %d, device is %d"),
579 storageBus, lChannel, lDevice);
580 }
581
582 Utf8StrFmt strExtra("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys);
583 Utf8Str strEmpty;
584
585 switch (deviceType)
586 {
587 case DeviceType_HardDisk:
588 Log(("Adding VirtualSystemDescriptionType_HardDiskImage, disk size: %RI64\n", llSize));
589 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskImage,
590 strTargetImageName, // disk ID: let's use the name
591 strTargetImageName, // OVF value:
592 strLocation, // vbox value: media path
593 (uint32_t)(llSize / _1M),
594 strExtra);
595 break;
596
597 case DeviceType_DVD:
598 Log(("Adding VirtualSystemDescriptionType_CDROM, disk size: %RI64\n", llSize));
599 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CDROM,
600 strTargetImageName, // disk ID
601 strTargetImageName, // OVF value
602 strLocation, // vbox value
603 (uint32_t)(llSize / _1M),// ulSize
604 strExtra);
605 break;
606
607 case DeviceType_Floppy:
608 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Floppy,
609 strEmpty, // disk ID
610 strEmpty, // OVF value
611 strEmpty, // vbox value
612 1, // ulSize
613 strExtra);
614 break;
615
616 default: break; /* Shut up MSC. */
617 }
618 }
619
620// <const name="NetworkAdapter" />
621 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(i_getChipsetType());
622 size_t a;
623 for (a = 0; a < maxNetworkAdapters; ++a)
624 {
625 ComPtr<INetworkAdapter> pNetworkAdapter;
626 BOOL fEnabled;
627 NetworkAdapterType_T adapterType;
628 NetworkAttachmentType_T attachmentType;
629
630 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
631 if (FAILED(rc)) throw rc;
632 /* Enable the network card & set the adapter type */
633 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
634 if (FAILED(rc)) throw rc;
635
636 if (fEnabled)
637 {
638 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
639 if (FAILED(rc)) throw rc;
640
641 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
642 if (FAILED(rc)) throw rc;
643
644 Utf8Str strAttachmentType = convertNetworkAttachmentTypeToString(attachmentType);
645 pNewDesc->i_addEntry(VirtualSystemDescriptionType_NetworkAdapter,
646 "", // ref
647 strAttachmentType, // orig
648 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
649 0,
650 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
651 }
652 }
653
654// <const name="USBController" />
655#ifdef VBOX_WITH_USB
656 if (fUSBEnabled)
657 pNewDesc->i_addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
658#endif /* VBOX_WITH_USB */
659
660// <const name="SoundCard" />
661 if (fAudioEnabled)
662 pNewDesc->i_addEntry(VirtualSystemDescriptionType_SoundCard,
663 "",
664 "ensoniq1371", // this is what OVFTool writes and VMware supports
665 Utf8StrFmt("%RI32", audioController));
666
667 /* We return the new description to the caller */
668 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
669 copy.queryInterfaceTo(aDescription.asOutParam());
670
671 AutoWriteLock alock(pAppliance COMMA_LOCKVAL_SRC_POS);
672 // finally, add the virtual system to the appliance
673 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
674 }
675 catch(HRESULT arc)
676 {
677 rc = arc;
678 }
679
680 return rc;
681}
682
683////////////////////////////////////////////////////////////////////////////////
684//
685// IAppliance public methods
686//
687////////////////////////////////////////////////////////////////////////////////
688
689/**
690 * Public method implementation.
691 * @param aFormat Appliance format.
692 * @param aOptions Export options.
693 * @param aPath Path to write the appliance to.
694 * @param aProgress Progress object.
695 * @return
696 */
697HRESULT Appliance::write(const com::Utf8Str &aFormat,
698 const std::vector<ExportOptions_T> &aOptions,
699 const com::Utf8Str &aPath,
700 ComPtr<IProgress> &aProgress)
701{
702 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
703
704 m->optListExport.clear();
705 if (aOptions.size())
706 {
707 for (size_t i = 0; i < aOptions.size(); ++i)
708 {
709 m->optListExport.insert(i, aOptions[i]);
710 }
711 }
712
713 HRESULT rc = S_OK;
714// AssertReturn(!(m->optListExport.contains(ExportOptions_CreateManifest)
715// && m->optListExport.contains(ExportOptions_ExportDVDImages)), E_INVALIDARG);
716
717 /* Parse all necessary info out of the URI */
718 i_parseURI(aPath, m->locInfo);
719
720 if (m->locInfo.storageType == VFSType_Cloud)
721 {
722 rc = S_OK;
723 ComObjPtr<Progress> progress;
724 try
725 {
726 rc = i_writeCloudImpl(m->locInfo, progress);
727 }
728 catch (HRESULT aRC)
729 {
730 rc = aRC;
731 }
732
733 if (SUCCEEDED(rc))
734 /* Return progress to the caller */
735 progress.queryInterfaceTo(aProgress.asOutParam());
736 }
737 else
738 {
739 m->fExportISOImages = m->optListExport.contains(ExportOptions_ExportDVDImages);
740
741 if (!m->fExportISOImages)/* remove all ISO images from VirtualSystemDescription */
742 {
743 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
744 it = m->virtualSystemDescriptions.begin();
745 it != m->virtualSystemDescriptions.end();
746 ++it)
747 {
748 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
749 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
750 std::list<VirtualSystemDescriptionEntry*>::const_iterator itSkipped = skipped.begin();
751 while (itSkipped != skipped.end())
752 {
753 (*itSkipped)->skipIt = true;
754 ++itSkipped;
755 }
756 }
757 }
758
759 // do not allow entering this method if the appliance is busy reading or writing
760 if (!i_isApplianceIdle())
761 return E_ACCESSDENIED;
762
763 // figure the export format. We exploit the unknown version value for oracle public cloud.
764 ovf::OVFVersion_T ovfF;
765 if (aFormat == "ovf-0.9")
766 ovfF = ovf::OVFVersion_0_9;
767 else if (aFormat == "ovf-1.0")
768 ovfF = ovf::OVFVersion_1_0;
769 else if (aFormat == "ovf-2.0")
770 ovfF = ovf::OVFVersion_2_0;
771 else if (aFormat == "opc-1.0")
772 ovfF = ovf::OVFVersion_unknown;
773 else
774 return setError(VBOX_E_FILE_ERROR,
775 tr("Invalid format \"%s\" specified"), aFormat.c_str());
776
777 // Check the extension.
778 if (ovfF == ovf::OVFVersion_unknown)
779 {
780 if (!aPath.endsWith(".tar.gz", Utf8Str::CaseInsensitive))
781 return setError(VBOX_E_FILE_ERROR,
782 tr("OPC appliance file must have .tar.gz extension"));
783 }
784 else if ( !aPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
785 && !aPath.endsWith(".ova", Utf8Str::CaseInsensitive))
786 return setError(VBOX_E_FILE_ERROR, tr("Appliance file must have .ovf or .ova extension"));
787
788
789 /* As of OVF 2.0 we have to use SHA-256 in the manifest. */
790 m->fManifest = m->optListExport.contains(ExportOptions_CreateManifest);
791 if (m->fManifest)
792 m->fDigestTypes = ovfF >= ovf::OVFVersion_2_0 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1;
793 Assert(m->hOurManifest == NIL_RTMANIFEST);
794
795 /* Check whether all passwords are supplied or error out. */
796 if (m->m_cPwProvided < m->m_vecPasswordIdentifiers.size())
797 return setError(VBOX_E_INVALID_OBJECT_STATE,
798 tr("Appliance export failed because not all passwords were provided for all encrypted media"));
799
800 ComObjPtr<Progress> progress;
801 rc = S_OK;
802 try
803 {
804 /* Parse all necessary info out of the URI */
805 i_parseURI(aPath, m->locInfo);
806
807 switch (ovfF)
808 {
809 case ovf::OVFVersion_unknown:
810 rc = i_writeOPCImpl(ovfF, m->locInfo, progress);
811 break;
812 default:
813 rc = i_writeImpl(ovfF, m->locInfo, progress);
814 break;
815 }
816
817 }
818 catch (HRESULT aRC)
819 {
820 rc = aRC;
821 }
822
823 if (SUCCEEDED(rc))
824 /* Return progress to the caller */
825 progress.queryInterfaceTo(aProgress.asOutParam());
826 }
827
828 return rc;
829}
830
831////////////////////////////////////////////////////////////////////////////////
832//
833// Appliance private methods
834//
835////////////////////////////////////////////////////////////////////////////////
836
837/*******************************************************************************
838 * Export stuff
839 ******************************************************************************/
840
841/**
842 * Implementation for writing out the OVF to disk. This starts a new thread which will call
843 * Appliance::taskThreadWriteOVF().
844 *
845 * This is in a separate private method because it is used from two locations:
846 *
847 * 1) from the public Appliance::Write().
848 *
849 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl(), which
850 * called Appliance::i_writeFSOVA(), which called Appliance::i_writeImpl(), which then called this again.
851 *
852 * @param aFormat
853 * @param aLocInfo
854 * @param aProgress
855 * @return
856 */
857HRESULT Appliance::i_writeImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
858{
859 /* Prepare progress object: */
860 HRESULT hrc;
861 try
862 {
863 hrc = i_setUpProgress(aProgress,
864 Utf8StrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
865 aLocInfo.storageType == VFSType_File ? WriteFile : WriteS3);
866 }
867 catch (std::bad_alloc &) /* only Utf8StrFmt */
868 {
869 hrc = E_OUTOFMEMORY;
870 }
871 if (SUCCEEDED(hrc))
872 {
873 /* Create our worker task: */
874 TaskOVF *pTask = NULL;
875 try
876 {
877 pTask = new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress);
878 }
879 catch (std::bad_alloc &)
880 {
881 return E_OUTOFMEMORY;
882 }
883
884 /* The OVF version to produce: */
885 pTask->enFormat = aFormat;
886
887 /* Start the thread: */
888 hrc = pTask->createThread();
889 pTask = NULL;
890 }
891 return hrc;
892}
893
894
895HRESULT Appliance::i_writeCloudImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
896{
897 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
898 it = m->virtualSystemDescriptions.begin();
899 it != m->virtualSystemDescriptions.end();
900 ++it)
901 {
902 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
903 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
904 std::list<VirtualSystemDescriptionEntry*>::const_iterator itSkipped = skipped.begin();
905 while (itSkipped != skipped.end())
906 {
907 (*itSkipped)->skipIt = true;
908 ++itSkipped;
909 }
910
911 //remove all disks from the VirtualSystemDescription exept one
912 skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
913 itSkipped = skipped.begin();
914
915 Utf8Str strBootLocation;
916 while (itSkipped != skipped.end())
917 {
918 if (strBootLocation.isEmpty())
919 strBootLocation = (*itSkipped)->strVBoxCurrent;
920 else
921 (*itSkipped)->skipIt = true;
922 ++itSkipped;
923 }
924
925 //just in case
926 if (vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage).empty())
927 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("There are no images to export to Cloud after preparation steps"));
928
929 /*
930 * Fills out the OCI settings
931 */
932 std::list<VirtualSystemDescriptionEntry*> profileName
933 = vsdescThis->i_findByType(VirtualSystemDescriptionType_CloudProfileName);
934 if (profileName.size() > 1)
935 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("Cloud: More than one profile name was found."));
936 if (profileName.empty())
937 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("Cloud: Profile name wasn't specified."));
938
939 if (profileName.front()->strVBoxCurrent.isEmpty())
940 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("Cloud: Cloud user profile name is empty"));
941
942 LogRel(("profile name: %s\n", profileName.front()->strVBoxCurrent.c_str()));
943 }
944
945 // Create a progress object here otherwise Task won't be created successfully
946 HRESULT hrc = aProgress.createObject();
947 if (SUCCEEDED(hrc))
948 {
949 if (aLocInfo.strProvider.equals("OCI"))
950 hrc = aProgress->init(mVirtualBox, static_cast<IAppliance *>(this),
951 Utf8Str(tr("Exporting VM to Cloud...")),
952 TRUE /* aCancelable */,
953 5, // ULONG cOperations,
954 1000, // ULONG ulTotalOperationsWeight,
955 Utf8Str(tr("Exporting VM to Cloud...")), // aFirstOperationDescription
956 10); // ULONG ulFirstOperationWeight
957 else
958 hrc = setError(VBOX_E_NOT_SUPPORTED,
959 tr("Only \"OCI\" cloud provider is supported for now. \"%s\" isn't supported."),
960 aLocInfo.strProvider.c_str());
961 if (SUCCEEDED(hrc))
962 {
963 /* Initialize the worker task: */
964 TaskCloud *pTask = NULL;
965 try
966 {
967 pTask = new Appliance::TaskCloud(this, TaskCloud::Export, aLocInfo, aProgress);
968 }
969 catch (std::bad_alloc &)
970 {
971 pTask = NULL;
972 hrc = E_OUTOFMEMORY;
973 }
974 if (SUCCEEDED(hrc))
975 {
976 /* Kick off the worker task: */
977 hrc = pTask->createThread();
978 pTask = NULL;
979 }
980 }
981 }
982 return hrc;
983}
984
985HRESULT Appliance::i_writeOPCImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
986{
987 RT_NOREF(aFormat);
988
989 /* Prepare progress object: */
990 HRESULT hrc;
991 try
992 {
993 hrc = i_setUpProgress(aProgress,
994 Utf8StrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
995 aLocInfo.storageType == VFSType_File ? WriteFile : WriteS3);
996 }
997 catch (std::bad_alloc &) /* only Utf8StrFmt */
998 {
999 hrc = E_OUTOFMEMORY;
1000 }
1001 if (SUCCEEDED(hrc))
1002 {
1003 /* Create our worker task: */
1004 TaskOPC *pTask = NULL;
1005 try
1006 {
1007 pTask = new Appliance::TaskOPC(this, TaskOPC::Export, aLocInfo, aProgress);
1008 }
1009 catch (std::bad_alloc &)
1010 {
1011 return E_OUTOFMEMORY;
1012 }
1013
1014 /* Kick it off: */
1015 hrc = pTask->createThread();
1016 pTask = NULL;
1017 }
1018 return hrc;
1019}
1020
1021
1022/**
1023 * Called from Appliance::i_writeFS() for creating a XML document for this
1024 * Appliance.
1025 *
1026 * @param writeLock The current write lock.
1027 * @param doc The xml document to fill.
1028 * @param stack Structure for temporary private
1029 * data shared with caller.
1030 * @param strPath Path to the target OVF.
1031 * instance for which to write XML.
1032 * @param enFormat OVF format (0.9 or 1.0).
1033 */
1034void Appliance::i_buildXML(AutoWriteLockBase& writeLock,
1035 xml::Document &doc,
1036 XMLStack &stack,
1037 const Utf8Str &strPath,
1038 ovf::OVFVersion_T enFormat)
1039{
1040 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
1041
1042 pelmRoot->setAttribute("ovf:version", enFormat == ovf::OVFVersion_2_0 ? "2.0"
1043 : enFormat == ovf::OVFVersion_1_0 ? "1.0"
1044 : "0.9");
1045 pelmRoot->setAttribute("xml:lang", "en-US");
1046
1047 Utf8Str strNamespace;
1048
1049 if (enFormat == ovf::OVFVersion_0_9)
1050 {
1051 strNamespace = ovf::OVF09_URI_string;
1052 }
1053 else if (enFormat == ovf::OVFVersion_1_0)
1054 {
1055 strNamespace = ovf::OVF10_URI_string;
1056 }
1057 else
1058 {
1059 strNamespace = ovf::OVF20_URI_string;
1060 }
1061
1062 pelmRoot->setAttribute("xmlns", strNamespace);
1063 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
1064
1065 // pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
1066 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
1067 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
1068 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
1069 pelmRoot->setAttribute("xmlns:vbox", "http://www.virtualbox.org/ovf/machine");
1070 // pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
1071
1072 if (enFormat == ovf::OVFVersion_2_0)
1073 {
1074 pelmRoot->setAttribute("xmlns:epasd",
1075 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_EthernetPortAllocationSettingData.xsd");
1076 pelmRoot->setAttribute("xmlns:sasd",
1077 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_StorageAllocationSettingData.xsd");
1078 }
1079
1080 // <Envelope>/<References>
1081 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
1082
1083 /* <Envelope>/<DiskSection>:
1084 <DiskSection>
1085 <Info>List of the virtual disks used in the package</Info>
1086 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
1087 </DiskSection> */
1088 xml::ElementNode *pelmDiskSection;
1089 if (enFormat == ovf::OVFVersion_0_9)
1090 {
1091 // <Section xsi:type="ovf:DiskSection_Type">
1092 pelmDiskSection = pelmRoot->createChild("Section");
1093 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
1094 }
1095 else
1096 pelmDiskSection = pelmRoot->createChild("DiskSection");
1097
1098 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
1099 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
1100
1101 /* <Envelope>/<NetworkSection>:
1102 <NetworkSection>
1103 <Info>Logical networks used in the package</Info>
1104 <Network ovf:name="VM Network">
1105 <Description>The network that the LAMP Service will be available on</Description>
1106 </Network>
1107 </NetworkSection> */
1108 xml::ElementNode *pelmNetworkSection;
1109 if (enFormat == ovf::OVFVersion_0_9)
1110 {
1111 // <Section xsi:type="ovf:NetworkSection_Type">
1112 pelmNetworkSection = pelmRoot->createChild("Section");
1113 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
1114 }
1115 else
1116 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
1117
1118 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
1119 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
1120
1121 // and here come the virtual systems:
1122
1123 // write a collection if we have more than one virtual system _and_ we're
1124 // writing OVF 1.0; otherwise fail since ovftool can't import more than
1125 // one machine, it seems
1126 xml::ElementNode *pelmToAddVirtualSystemsTo;
1127 if (m->virtualSystemDescriptions.size() > 1)
1128 {
1129 if (enFormat == ovf::OVFVersion_0_9)
1130 throw setError(VBOX_E_FILE_ERROR,
1131 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
1132
1133 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
1134 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
1135 }
1136 else
1137 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
1138
1139 // this list receives pointers to the XML elements in the machine XML which
1140 // might have UUIDs that need fixing after we know the UUIDs of the exported images
1141 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
1142 uint32_t ulFile = 1;
1143 /* Iterate through all virtual systems of that appliance */
1144 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
1145 itV = m->virtualSystemDescriptions.begin();
1146 itV != m->virtualSystemDescriptions.end();
1147 ++itV)
1148 {
1149 ComObjPtr<VirtualSystemDescription> vsdescThis = *itV;
1150 i_buildXMLForOneVirtualSystem(writeLock,
1151 *pelmToAddVirtualSystemsTo,
1152 &llElementsWithUuidAttributes,
1153 vsdescThis,
1154 enFormat,
1155 stack); // disks and networks stack
1156
1157 list<Utf8Str> diskList;
1158
1159 for (list<Utf8Str>::const_iterator
1160 itDisk = stack.mapDiskSequenceForOneVM.begin();
1161 itDisk != stack.mapDiskSequenceForOneVM.end();
1162 ++itDisk)
1163 {
1164 const Utf8Str &strDiskID = *itDisk;
1165 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
1166
1167 // source path: where the VBox image is
1168 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
1169 Bstr bstrSrcFilePath(strSrcFilePath);
1170
1171 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1172 if (strSrcFilePath.isEmpty() ||
1173 pDiskEntry->skipIt == true)
1174 continue;
1175
1176 // Do NOT check here whether the file exists. FindMedium will figure
1177 // that out, and filesystem-based tests are simply wrong in the
1178 // general case (think of iSCSI).
1179
1180 // We need some info from the source disks
1181 ComPtr<IMedium> pSourceDisk;
1182 //DeviceType_T deviceType = DeviceType_HardDisk;// by default
1183
1184 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
1185
1186 HRESULT rc;
1187
1188 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
1189 {
1190 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
1191 DeviceType_HardDisk,
1192 AccessMode_ReadWrite,
1193 FALSE /* fForceNewUuid */,
1194 pSourceDisk.asOutParam());
1195 if (FAILED(rc))
1196 throw rc;
1197 }
1198 else if (pDiskEntry->type == VirtualSystemDescriptionType_CDROM)//may be, this is CD/DVD
1199 {
1200 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
1201 DeviceType_DVD,
1202 AccessMode_ReadOnly,
1203 FALSE,
1204 pSourceDisk.asOutParam());
1205 if (FAILED(rc))
1206 throw rc;
1207 }
1208
1209 Bstr uuidSource;
1210 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1211 if (FAILED(rc)) throw rc;
1212 Guid guidSource(uuidSource);
1213
1214 // output filename
1215 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1216
1217 // target path needs to be composed from where the output OVF is
1218 Utf8Str strTargetFilePath(strPath);
1219 strTargetFilePath.stripFilename();
1220 strTargetFilePath.append("/");
1221 strTargetFilePath.append(strTargetFileNameOnly);
1222
1223 // We are always exporting to VMDK stream optimized for now
1224 //Bstr bstrSrcFormat = L"VMDK";//not used
1225
1226 diskList.push_back(strTargetFilePath);
1227
1228 LONG64 cbCapacity = 0; // size reported to guest
1229 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
1230 if (FAILED(rc)) throw rc;
1231 /// @todo r=poetzsch: wrong it is reported in bytes ...
1232 // capacity is reported in megabytes, so...
1233 //cbCapacity *= _1M;
1234
1235 Guid guidTarget; /* Creates a new uniq number for the target disk. */
1236 guidTarget.create();
1237
1238 // now handle the XML for the disk:
1239 Utf8StrFmt strFileRef("file%RI32", ulFile++);
1240 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
1241 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
1242 pelmFile->setAttribute("ovf:id", strFileRef);
1243 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
1244 /// @todo the actual size is not available at this point of time,
1245 // cause the disk will be compressed. The 1.0 standard says this is
1246 // optional! 1.1 isn't fully clear if the "gzip" format is used.
1247 // Need to be checked. */
1248 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
1249
1250 // add disk to XML Disks section
1251 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
1252 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
1253 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
1254 pelmDisk->setAttribute("ovf:diskId", strDiskID);
1255 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
1256
1257 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)//deviceType == DeviceType_HardDisk
1258 {
1259 pelmDisk->setAttribute("ovf:format",
1260 (enFormat == ovf::OVFVersion_0_9)
1261 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftoo
1262 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
1263 // correct string as communicated to us by VMware (public bug #6612)
1264 );
1265 }
1266 else //pDiskEntry->type == VirtualSystemDescriptionType_CDROM, deviceType == DeviceType_DVD
1267 {
1268 pelmDisk->setAttribute("ovf:format",
1269 "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
1270 );
1271 }
1272
1273 // add the UUID of the newly target image to the OVF disk element, but in the
1274 // vbox: namespace since it's not part of the standard
1275 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
1276
1277 // now, we might have other XML elements from vbox:Machine pointing to this image,
1278 // but those would refer to the UUID of the _source_ image (which we created the
1279 // export image from); those UUIDs need to be fixed to the export image
1280 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
1281 for (std::list<xml::ElementNode*>::const_iterator
1282 it = llElementsWithUuidAttributes.begin();
1283 it != llElementsWithUuidAttributes.end();
1284 ++it)
1285 {
1286 xml::ElementNode *pelmImage = *it;
1287 Utf8Str strUUID;
1288 pelmImage->getAttributeValue("uuid", strUUID);
1289 if (strUUID == strGuidSourceCurly)
1290 // overwrite existing uuid attribute
1291 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
1292 }
1293 }
1294 llElementsWithUuidAttributes.clear();
1295 stack.mapDiskSequenceForOneVM.clear();
1296 }
1297
1298 // now, fill in the network section we set up empty above according
1299 // to the networks we found with the hardware items
1300 for (map<Utf8Str, bool>::const_iterator
1301 it = stack.mapNetworks.begin();
1302 it != stack.mapNetworks.end();
1303 ++it)
1304 {
1305 const Utf8Str &strNetwork = it->first;
1306 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
1307 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
1308 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
1309 }
1310
1311}
1312
1313/**
1314 * Called from Appliance::i_buildXML() for each virtual system (machine) that
1315 * needs XML written out.
1316 *
1317 * @param writeLock The current write lock.
1318 * @param elmToAddVirtualSystemsTo XML element to append elements to.
1319 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
1320 * with UUID attributes for quick
1321 * fixing by caller later
1322 * @param vsdescThis The IVirtualSystemDescription
1323 * instance for which to write XML.
1324 * @param enFormat OVF format (0.9 or 1.0).
1325 * @param stack Structure for temporary private
1326 * data shared with caller.
1327 */
1328void Appliance::i_buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
1329 xml::ElementNode &elmToAddVirtualSystemsTo,
1330 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
1331 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1332 ovf::OVFVersion_T enFormat,
1333 XMLStack &stack)
1334{
1335 LogFlowFunc(("ENTER appliance %p\n", this));
1336
1337 xml::ElementNode *pelmVirtualSystem;
1338 if (enFormat == ovf::OVFVersion_0_9)
1339 {
1340 // <Section xsi:type="ovf:NetworkSection_Type">
1341 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
1342 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
1343 }
1344 else
1345 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
1346
1347 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
1348
1349 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
1350 if (llName.empty())
1351 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing VM name"));
1352 Utf8Str &strVMName = llName.back()->strVBoxCurrent;
1353 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
1354
1355 // product info
1356 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->i_findByType(VirtualSystemDescriptionType_Product);
1357 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_ProductUrl);
1358 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->i_findByType(VirtualSystemDescriptionType_Vendor);
1359 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_VendorUrl);
1360 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->i_findByType(VirtualSystemDescriptionType_Version);
1361 bool fProduct = llProduct.size() && !llProduct.back()->strVBoxCurrent.isEmpty();
1362 bool fProductUrl = llProductUrl.size() && !llProductUrl.back()->strVBoxCurrent.isEmpty();
1363 bool fVendor = llVendor.size() && !llVendor.back()->strVBoxCurrent.isEmpty();
1364 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.back()->strVBoxCurrent.isEmpty();
1365 bool fVersion = llVersion.size() && !llVersion.back()->strVBoxCurrent.isEmpty();
1366 if (fProduct || fProductUrl || fVendor || fVendorUrl || fVersion)
1367 {
1368 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1369 <Info>Meta-information about the installed software</Info>
1370 <Product>VAtest</Product>
1371 <Vendor>SUN Microsystems</Vendor>
1372 <Version>10.0</Version>
1373 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
1374 <VendorUrl>http://www.sun.com</VendorUrl>
1375 </Section> */
1376 xml::ElementNode *pelmAnnotationSection;
1377 if (enFormat == ovf::OVFVersion_0_9)
1378 {
1379 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1380 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1381 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
1382 }
1383 else
1384 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
1385
1386 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
1387 if (fProduct)
1388 pelmAnnotationSection->createChild("Product")->addContent(llProduct.back()->strVBoxCurrent);
1389 if (fVendor)
1390 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.back()->strVBoxCurrent);
1391 if (fVersion)
1392 pelmAnnotationSection->createChild("Version")->addContent(llVersion.back()->strVBoxCurrent);
1393 if (fProductUrl)
1394 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.back()->strVBoxCurrent);
1395 if (fVendorUrl)
1396 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.back()->strVBoxCurrent);
1397 }
1398
1399 // description
1400 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
1401 if (llDescription.size() &&
1402 !llDescription.back()->strVBoxCurrent.isEmpty())
1403 {
1404 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1405 <Info>A human-readable annotation</Info>
1406 <Annotation>Plan 9</Annotation>
1407 </Section> */
1408 xml::ElementNode *pelmAnnotationSection;
1409 if (enFormat == ovf::OVFVersion_0_9)
1410 {
1411 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1412 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1413 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
1414 }
1415 else
1416 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
1417
1418 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1419 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.back()->strVBoxCurrent);
1420 }
1421
1422 // license
1423 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->i_findByType(VirtualSystemDescriptionType_License);
1424 if (llLicense.size() &&
1425 !llLicense.back()->strVBoxCurrent.isEmpty())
1426 {
1427 /* <EulaSection>
1428 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1429 <License ovf:msgid="1">License terms can go in here.</License>
1430 </EulaSection> */
1431 xml::ElementNode *pelmEulaSection;
1432 if (enFormat == ovf::OVFVersion_0_9)
1433 {
1434 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1435 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1436 }
1437 else
1438 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1439
1440 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1441 pelmEulaSection->createChild("License")->addContent(llLicense.back()->strVBoxCurrent);
1442 }
1443
1444 // operating system
1445 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
1446 if (llOS.empty())
1447 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing OS type"));
1448 /* <OperatingSystemSection ovf:id="82">
1449 <Info>Guest Operating System</Info>
1450 <Description>Linux 2.6.x</Description>
1451 </OperatingSystemSection> */
1452 VirtualSystemDescriptionEntry *pvsdeOS = llOS.back();
1453 xml::ElementNode *pelmOperatingSystemSection;
1454 if (enFormat == ovf::OVFVersion_0_9)
1455 {
1456 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1457 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1458 }
1459 else
1460 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1461
1462 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1463 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1464 Utf8Str strOSDesc;
1465 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1466 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1467 // add the VirtualBox ostype in a custom tag in a different namespace
1468 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1469 pelmVBoxOSType->setAttribute("ovf:required", "false");
1470 pelmVBoxOSType->addContent(pvsdeOS->strVBoxCurrent);
1471
1472 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1473 xml::ElementNode *pelmVirtualHardwareSection;
1474 if (enFormat == ovf::OVFVersion_0_9)
1475 {
1476 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1477 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1478 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1479 }
1480 else
1481 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1482
1483 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1484
1485 /* <System>
1486 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1487 <vssd:ElementName>vmware</vssd:ElementName>
1488 <vssd:InstanceID>1</vssd:InstanceID>
1489 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1490 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1491 </System> */
1492 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1493
1494 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1495
1496 // <vssd:InstanceId>0</vssd:InstanceId>
1497 if (enFormat == ovf::OVFVersion_0_9)
1498 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1499 else // capitalization changed...
1500 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1501
1502 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1503 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1504 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1505 const char *pcszHardware = "virtualbox-2.2";
1506 if (enFormat == ovf::OVFVersion_0_9)
1507 // pretend to be vmware compatible then
1508 pcszHardware = "vmx-6";
1509 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1510
1511 // loop thru all description entries twice; once to write out all
1512 // devices _except_ disk images, and a second time to assign the
1513 // disk images; this is because disk images need to reference
1514 // IDE controllers, and we can't know their instance IDs without
1515 // assigning them first
1516
1517 uint32_t idIDEPrimaryController = 0;
1518 int32_t lIDEPrimaryControllerIndex = 0;
1519 uint32_t idIDESecondaryController = 0;
1520 int32_t lIDESecondaryControllerIndex = 0;
1521 uint32_t idSATAController = 0;
1522 int32_t lSATAControllerIndex = 0;
1523 uint32_t idSCSIController = 0;
1524 int32_t lSCSIControllerIndex = 0;
1525 uint32_t idVirtioSCSIController = 0;
1526 int32_t lVirtioSCSIControllerIndex = 0;
1527
1528 uint32_t ulInstanceID = 1;
1529
1530 uint32_t cDVDs = 0;
1531
1532 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1533 {
1534 int32_t lIndexThis = 0;
1535 for (vector<VirtualSystemDescriptionEntry>::const_iterator
1536 it = vsdescThis->m->maDescriptions.begin();
1537 it != vsdescThis->m->maDescriptions.end();
1538 ++it, ++lIndexThis)
1539 {
1540 const VirtualSystemDescriptionEntry &desc = *it;
1541
1542 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVBox=%s, strExtraConfig=%s\n",
1543 uLoop,
1544 desc.ulIndex,
1545 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1546 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1547 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1548 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1549 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1550 : Utf8StrFmt("%d", desc.type).c_str()),
1551 desc.strRef.c_str(),
1552 desc.strOvf.c_str(),
1553 desc.strVBoxCurrent.c_str(),
1554 desc.strExtraConfigCurrent.c_str()));
1555
1556 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1557 Utf8Str strResourceSubType;
1558
1559 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1560 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1561
1562 uint32_t ulParent = 0;
1563
1564 int32_t lVirtualQuantity = -1;
1565 Utf8Str strAllocationUnits;
1566
1567 int32_t lAddress = -1;
1568 int32_t lBusNumber = -1;
1569 int32_t lAddressOnParent = -1;
1570
1571 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1572 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1573 Utf8Str strHostResource;
1574
1575 uint64_t uTemp;
1576
1577 ovf::VirtualHardwareItem vhi;
1578 ovf::StorageItem si;
1579 ovf::EthernetPortItem epi;
1580
1581 switch (desc.type)
1582 {
1583 case VirtualSystemDescriptionType_CPU:
1584 /* <Item>
1585 <rasd:Caption>1 virtual CPU</rasd:Caption>
1586 <rasd:Description>Number of virtual CPUs</rasd:Description>
1587 <rasd:ElementName>virtual CPU</rasd:ElementName>
1588 <rasd:InstanceID>1</rasd:InstanceID>
1589 <rasd:ResourceType>3</rasd:ResourceType>
1590 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1591 </Item> */
1592 if (uLoop == 1)
1593 {
1594 strDescription = "Number of virtual CPUs";
1595 type = ovf::ResourceType_Processor; // 3
1596 desc.strVBoxCurrent.toInt(uTemp);
1597 lVirtualQuantity = (int32_t)uTemp;
1598 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool
1599 // won't eat the item
1600 }
1601 break;
1602
1603 case VirtualSystemDescriptionType_Memory:
1604 /* <Item>
1605 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1606 <rasd:Caption>256 MB of memory</rasd:Caption>
1607 <rasd:Description>Memory Size</rasd:Description>
1608 <rasd:ElementName>Memory</rasd:ElementName>
1609 <rasd:InstanceID>2</rasd:InstanceID>
1610 <rasd:ResourceType>4</rasd:ResourceType>
1611 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1612 </Item> */
1613 if (uLoop == 1)
1614 {
1615 strDescription = "Memory Size";
1616 type = ovf::ResourceType_Memory; // 4
1617 desc.strVBoxCurrent.toInt(uTemp);
1618 lVirtualQuantity = (int32_t)(uTemp / _1M);
1619 strAllocationUnits = "MegaBytes";
1620 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool
1621 // won't eat the item
1622 }
1623 break;
1624
1625 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1626 /* <Item>
1627 <rasd:Caption>ideController1</rasd:Caption>
1628 <rasd:Description>IDE Controller</rasd:Description>
1629 <rasd:InstanceId>5</rasd:InstanceId>
1630 <rasd:ResourceType>5</rasd:ResourceType>
1631 <rasd:Address>1</rasd:Address>
1632 <rasd:BusNumber>1</rasd:BusNumber>
1633 </Item> */
1634 if (uLoop == 1)
1635 {
1636 strDescription = "IDE Controller";
1637 type = ovf::ResourceType_IDEController; // 5
1638 strResourceSubType = desc.strVBoxCurrent;
1639
1640 if (!lIDEPrimaryControllerIndex)
1641 {
1642 // first IDE controller:
1643 strCaption = "ideController0";
1644 lAddress = 0;
1645 lBusNumber = 0;
1646 // remember this ID
1647 idIDEPrimaryController = ulInstanceID;
1648 lIDEPrimaryControllerIndex = lIndexThis;
1649 }
1650 else
1651 {
1652 // second IDE controller:
1653 strCaption = "ideController1";
1654 lAddress = 1;
1655 lBusNumber = 1;
1656 // remember this ID
1657 idIDESecondaryController = ulInstanceID;
1658 lIDESecondaryControllerIndex = lIndexThis;
1659 }
1660 }
1661 break;
1662
1663 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1664 /* <Item>
1665 <rasd:Caption>sataController0</rasd:Caption>
1666 <rasd:Description>SATA Controller</rasd:Description>
1667 <rasd:InstanceId>4</rasd:InstanceId>
1668 <rasd:ResourceType>20</rasd:ResourceType>
1669 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1670 <rasd:Address>0</rasd:Address>
1671 <rasd:BusNumber>0</rasd:BusNumber>
1672 </Item>
1673 */
1674 if (uLoop == 1)
1675 {
1676 strDescription = "SATA Controller";
1677 strCaption = "sataController0";
1678 type = ovf::ResourceType_OtherStorageDevice; // 20
1679 // it seems that OVFTool always writes these two, and since we can only
1680 // have one SATA controller, we'll use this as well
1681 lAddress = 0;
1682 lBusNumber = 0;
1683
1684 if ( desc.strVBoxCurrent.isEmpty() // AHCI is the default in VirtualBox
1685 || (!desc.strVBoxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1686 )
1687 strResourceSubType = "AHCI";
1688 else
1689 throw setError(VBOX_E_NOT_SUPPORTED,
1690 tr("Invalid config string \"%s\" in SATA controller"), desc.strVBoxCurrent.c_str());
1691
1692 // remember this ID
1693 idSATAController = ulInstanceID;
1694 lSATAControllerIndex = lIndexThis;
1695 }
1696 break;
1697
1698 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1699 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1700 /* <Item>
1701 <rasd:Caption>scsiController0</rasd:Caption>
1702 <rasd:Description>SCSI Controller</rasd:Description>
1703 <rasd:InstanceId>4</rasd:InstanceId>
1704 <rasd:ResourceType>6</rasd:ResourceType>
1705 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1706 <rasd:Address>0</rasd:Address>
1707 <rasd:BusNumber>0</rasd:BusNumber>
1708 </Item>
1709 */
1710 if (uLoop == 1)
1711 {
1712 strDescription = "SCSI Controller";
1713 strCaption = "scsiController0";
1714 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1715 // it seems that OVFTool always writes these two, and since we can only
1716 // have one SATA controller, we'll use this as well
1717 lAddress = 0;
1718 lBusNumber = 0;
1719
1720 if ( desc.strVBoxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1721 || (!desc.strVBoxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1722 )
1723 strResourceSubType = "lsilogic";
1724 else if (!desc.strVBoxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1725 strResourceSubType = "buslogic";
1726 else if (!desc.strVBoxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1727 strResourceSubType = "lsilogicsas";
1728 else
1729 throw setError(VBOX_E_NOT_SUPPORTED,
1730 tr("Invalid config string \"%s\" in SCSI/SAS controller"),
1731 desc.strVBoxCurrent.c_str());
1732
1733 // remember this ID
1734 idSCSIController = ulInstanceID;
1735 lSCSIControllerIndex = lIndexThis;
1736 }
1737 break;
1738
1739
1740 case VirtualSystemDescriptionType_HardDiskControllerVirtioSCSI:
1741 /* <Item>
1742 <rasd:Caption>VirtioSCSIController0</rasd:Caption>
1743 <rasd:Description>VirtioSCSI Controller</rasd:Description>
1744 <rasd:InstanceId>4</rasd:InstanceId>
1745 <rasd:ResourceType>20</rasd:ResourceType>
1746 <rasd:Address>0</rasd:Address>
1747 <rasd:BusNumber>0</rasd:BusNumber>
1748 </Item>
1749 */
1750 if (uLoop == 1)
1751 {
1752 strDescription = "VirtioSCSI Controller";
1753 strCaption = "virtioSCSIController0";
1754 type = ovf::ResourceType_OtherStorageDevice; // 20
1755 lAddress = 0;
1756 lBusNumber = 0;
1757 strResourceSubType = "VirtioSCSI";
1758 // remember this ID
1759 idVirtioSCSIController = ulInstanceID;
1760 lVirtioSCSIControllerIndex = lIndexThis;
1761 }
1762 break;
1763
1764 case VirtualSystemDescriptionType_HardDiskImage:
1765 /* <Item>
1766 <rasd:Caption>disk1</rasd:Caption>
1767 <rasd:InstanceId>8</rasd:InstanceId>
1768 <rasd:ResourceType>17</rasd:ResourceType>
1769 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1770 <rasd:Parent>4</rasd:Parent>
1771 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1772 </Item> */
1773 if (uLoop == 2)
1774 {
1775 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1776 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1777
1778 strDescription = "Disk Image";
1779 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1780 type = ovf::ResourceType_HardDisk; // 17
1781
1782 // the following references the "<Disks>" XML block
1783 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1784
1785 // controller=<index>;channel=<c>
1786 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1787 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1788 int32_t lControllerIndex = -1;
1789 if (pos1 != Utf8Str::npos)
1790 {
1791 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1792 if (lControllerIndex == lIDEPrimaryControllerIndex)
1793 ulParent = idIDEPrimaryController;
1794 else if (lControllerIndex == lIDESecondaryControllerIndex)
1795 ulParent = idIDESecondaryController;
1796 else if (lControllerIndex == lSCSIControllerIndex)
1797 ulParent = idSCSIController;
1798 else if (lControllerIndex == lSATAControllerIndex)
1799 ulParent = idSATAController;
1800 else if (lControllerIndex == lVirtioSCSIControllerIndex)
1801 ulParent = idVirtioSCSIController;
1802 }
1803 if (pos2 != Utf8Str::npos)
1804 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1805
1806 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1807 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex,
1808 ulParent, lAddressOnParent));
1809
1810 if ( !ulParent
1811 || lAddressOnParent == -1
1812 )
1813 throw setError(VBOX_E_NOT_SUPPORTED,
1814 tr("Missing or bad extra config string in hard disk image: \"%s\""),
1815 desc.strExtraConfigCurrent.c_str());
1816
1817 stack.mapDisks[strDiskID] = &desc;
1818
1819 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1820 //in the OVF description file.
1821 stack.mapDiskSequence.push_back(strDiskID);
1822 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1823 }
1824 break;
1825
1826 case VirtualSystemDescriptionType_Floppy:
1827 if (uLoop == 1)
1828 {
1829 strDescription = "Floppy Drive";
1830 strCaption = "floppy0"; // this is what OVFTool writes
1831 type = ovf::ResourceType_FloppyDrive; // 14
1832 lAutomaticAllocation = 0;
1833 lAddressOnParent = 0; // this is what OVFTool writes
1834 }
1835 break;
1836
1837 case VirtualSystemDescriptionType_CDROM:
1838 /* <Item>
1839 <rasd:Caption>cdrom1</rasd:Caption>
1840 <rasd:InstanceId>8</rasd:InstanceId>
1841 <rasd:ResourceType>15</rasd:ResourceType>
1842 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1843 <rasd:Parent>4</rasd:Parent>
1844 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1845 </Item> */
1846 if (uLoop == 2)
1847 {
1848 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1849 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDisks);
1850 ++cDVDs;
1851 strDescription = "CD-ROM Drive";
1852 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1853 type = ovf::ResourceType_CDDrive; // 15
1854 lAutomaticAllocation = 1;
1855
1856 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1857 if (desc.strVBoxCurrent.isNotEmpty() &&
1858 desc.skipIt == false)
1859 {
1860 // the following references the "<Disks>" XML block
1861 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1862 }
1863
1864 // controller=<index>;channel=<c>
1865 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1866 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1867 int32_t lControllerIndex = -1;
1868 if (pos1 != Utf8Str::npos)
1869 {
1870 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1871 if (lControllerIndex == lIDEPrimaryControllerIndex)
1872 ulParent = idIDEPrimaryController;
1873 else if (lControllerIndex == lIDESecondaryControllerIndex)
1874 ulParent = idIDESecondaryController;
1875 else if (lControllerIndex == lSCSIControllerIndex)
1876 ulParent = idSCSIController;
1877 else if (lControllerIndex == lSATAControllerIndex)
1878 ulParent = idSATAController;
1879 }
1880 if (pos2 != Utf8Str::npos)
1881 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1882
1883 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1884 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex,
1885 lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1886
1887 if ( !ulParent
1888 || lAddressOnParent == -1
1889 )
1890 throw setError(VBOX_E_NOT_SUPPORTED,
1891 tr("Missing or bad extra config string in DVD drive medium: \"%s\""),
1892 desc.strExtraConfigCurrent.c_str());
1893
1894 stack.mapDisks[strDiskID] = &desc;
1895
1896 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1897 //in the OVF description file.
1898 stack.mapDiskSequence.push_back(strDiskID);
1899 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1900 // there is no DVD drive map to update because it is
1901 // handled completely with this entry.
1902 }
1903 break;
1904
1905 case VirtualSystemDescriptionType_NetworkAdapter:
1906 /* <Item>
1907 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1908 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1909 <rasd:Connection>VM Network</rasd:Connection>
1910 <rasd:ElementName>VM network</rasd:ElementName>
1911 <rasd:InstanceID>3</rasd:InstanceID>
1912 <rasd:ResourceType>10</rasd:ResourceType>
1913 </Item> */
1914 if (uLoop == 2)
1915 {
1916 lAutomaticAllocation = 1;
1917 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1918 type = ovf::ResourceType_EthernetAdapter; // 10
1919 /* Set the hardware type to something useful.
1920 * To be compatible with vmware & others we set
1921 * PCNet32 for our PCNet types & E1000 for the
1922 * E1000 cards. */
1923 switch (desc.strVBoxCurrent.toInt32())
1924 {
1925 case NetworkAdapterType_Am79C970A:
1926 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1927#ifdef VBOX_WITH_E1000
1928 case NetworkAdapterType_I82540EM:
1929 case NetworkAdapterType_I82545EM:
1930 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1931#endif /* VBOX_WITH_E1000 */
1932 }
1933 strConnection = desc.strOvf;
1934
1935 stack.mapNetworks[desc.strOvf] = true;
1936 }
1937 break;
1938
1939 case VirtualSystemDescriptionType_USBController:
1940 /* <Item ovf:required="false">
1941 <rasd:Caption>usb</rasd:Caption>
1942 <rasd:Description>USB Controller</rasd:Description>
1943 <rasd:InstanceId>3</rasd:InstanceId>
1944 <rasd:ResourceType>23</rasd:ResourceType>
1945 <rasd:Address>0</rasd:Address>
1946 <rasd:BusNumber>0</rasd:BusNumber>
1947 </Item> */
1948 if (uLoop == 1)
1949 {
1950 strDescription = "USB Controller";
1951 strCaption = "usb";
1952 type = ovf::ResourceType_USBController; // 23
1953 lAddress = 0; // this is what OVFTool writes
1954 lBusNumber = 0; // this is what OVFTool writes
1955 }
1956 break;
1957
1958 case VirtualSystemDescriptionType_SoundCard:
1959 /* <Item ovf:required="false">
1960 <rasd:Caption>sound</rasd:Caption>
1961 <rasd:Description>Sound Card</rasd:Description>
1962 <rasd:InstanceId>10</rasd:InstanceId>
1963 <rasd:ResourceType>35</rasd:ResourceType>
1964 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1965 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1966 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1967 </Item> */
1968 if (uLoop == 1)
1969 {
1970 strDescription = "Sound Card";
1971 strCaption = "sound";
1972 type = ovf::ResourceType_SoundCard; // 35
1973 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1974 lAutomaticAllocation = 0;
1975 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1976 }
1977 break;
1978
1979 default: break; /* Shut up MSC. */
1980 }
1981
1982 if (type)
1983 {
1984 xml::ElementNode *pItem;
1985 xml::ElementNode *pItemHelper;
1986 RTCString itemElement;
1987 RTCString itemElementHelper;
1988
1989 if (enFormat == ovf::OVFVersion_2_0)
1990 {
1991 if(uLoop == 2)
1992 {
1993 if (desc.type == VirtualSystemDescriptionType_NetworkAdapter)
1994 {
1995 itemElement = "epasd:";
1996 pItem = pelmVirtualHardwareSection->createChild("EthernetPortItem");
1997 }
1998 else if (desc.type == VirtualSystemDescriptionType_CDROM ||
1999 desc.type == VirtualSystemDescriptionType_HardDiskImage)
2000 {
2001 itemElement = "sasd:";
2002 pItem = pelmVirtualHardwareSection->createChild("StorageItem");
2003 }
2004 else
2005 pItem = NULL;
2006 }
2007 else
2008 {
2009 itemElement = "rasd:";
2010 pItem = pelmVirtualHardwareSection->createChild("Item");
2011 }
2012 }
2013 else
2014 {
2015 itemElement = "rasd:";
2016 pItem = pelmVirtualHardwareSection->createChild("Item");
2017 }
2018
2019 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
2020 // the elements from the rasd: namespace must be sorted by letter, and VMware
2021 // actually requires this as well (see public bug #6612)
2022
2023 if (lAddress != -1)
2024 {
2025 //pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
2026 itemElementHelper = itemElement;
2027 pItemHelper = pItem->createChild(itemElementHelper.append("Address").c_str());
2028 pItemHelper->addContent(Utf8StrFmt("%d", lAddress));
2029 }
2030
2031 if (lAddressOnParent != -1)
2032 {
2033 //pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
2034 itemElementHelper = itemElement;
2035 pItemHelper = pItem->createChild(itemElementHelper.append("AddressOnParent").c_str());
2036 pItemHelper->addContent(Utf8StrFmt("%d", lAddressOnParent));
2037 }
2038
2039 if (!strAllocationUnits.isEmpty())
2040 {
2041 //pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
2042 itemElementHelper = itemElement;
2043 pItemHelper = pItem->createChild(itemElementHelper.append("AllocationUnits").c_str());
2044 pItemHelper->addContent(strAllocationUnits);
2045 }
2046
2047 if (lAutomaticAllocation != -1)
2048 {
2049 //pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
2050 itemElementHelper = itemElement;
2051 pItemHelper = pItem->createChild(itemElementHelper.append("AutomaticAllocation").c_str());
2052 pItemHelper->addContent((lAutomaticAllocation) ? "true" : "false" );
2053 }
2054
2055 if (lBusNumber != -1)
2056 {
2057 if (enFormat == ovf::OVFVersion_0_9)
2058 {
2059 // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool
2060 //pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
2061 itemElementHelper = itemElement;
2062 pItemHelper = pItem->createChild(itemElementHelper.append("BusNumber").c_str());
2063 pItemHelper->addContent(Utf8StrFmt("%d", lBusNumber));
2064 }
2065 }
2066
2067 if (!strCaption.isEmpty())
2068 {
2069 //pItem->createChild("rasd:Caption")->addContent(strCaption);
2070 itemElementHelper = itemElement;
2071 pItemHelper = pItem->createChild(itemElementHelper.append("Caption").c_str());
2072 pItemHelper->addContent(strCaption);
2073 }
2074
2075 if (!strConnection.isEmpty())
2076 {
2077 //pItem->createChild("rasd:Connection")->addContent(strConnection);
2078 itemElementHelper = itemElement;
2079 pItemHelper = pItem->createChild(itemElementHelper.append("Connection").c_str());
2080 pItemHelper->addContent(strConnection);
2081 }
2082
2083 if (!strDescription.isEmpty())
2084 {
2085 //pItem->createChild("rasd:Description")->addContent(strDescription);
2086 itemElementHelper = itemElement;
2087 pItemHelper = pItem->createChild(itemElementHelper.append("Description").c_str());
2088 pItemHelper->addContent(strDescription);
2089 }
2090
2091 if (!strCaption.isEmpty())
2092 {
2093 if (enFormat == ovf::OVFVersion_1_0)
2094 {
2095 //pItem->createChild("rasd:ElementName")->addContent(strCaption);
2096 itemElementHelper = itemElement;
2097 pItemHelper = pItem->createChild(itemElementHelper.append("ElementName").c_str());
2098 pItemHelper->addContent(strCaption);
2099 }
2100 }
2101
2102 if (!strHostResource.isEmpty())
2103 {
2104 //pItem->createChild("rasd:HostResource")->addContent(strHostResource);
2105 itemElementHelper = itemElement;
2106 pItemHelper = pItem->createChild(itemElementHelper.append("HostResource").c_str());
2107 pItemHelper->addContent(strHostResource);
2108 }
2109
2110 {
2111 // <rasd:InstanceID>1</rasd:InstanceID>
2112 itemElementHelper = itemElement;
2113 if (enFormat == ovf::OVFVersion_0_9)
2114 //pelmInstanceID = pItem->createChild("rasd:InstanceId");
2115 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceId").c_str());
2116 else
2117 //pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
2118 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceID").c_str());
2119
2120 pItemHelper->addContent(Utf8StrFmt("%d", ulInstanceID++));
2121 }
2122
2123 if (ulParent)
2124 {
2125 //pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
2126 itemElementHelper = itemElement;
2127 pItemHelper = pItem->createChild(itemElementHelper.append("Parent").c_str());
2128 pItemHelper->addContent(Utf8StrFmt("%d", ulParent));
2129 }
2130
2131 if (!strResourceSubType.isEmpty())
2132 {
2133 //pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
2134 itemElementHelper = itemElement;
2135 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceSubType").c_str());
2136 pItemHelper->addContent(strResourceSubType);
2137 }
2138
2139 {
2140 // <rasd:ResourceType>3</rasd:ResourceType>
2141 //pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
2142 itemElementHelper = itemElement;
2143 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceType").c_str());
2144 pItemHelper->addContent(Utf8StrFmt("%d", type));
2145 }
2146
2147 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2148 if (lVirtualQuantity != -1)
2149 {
2150 //pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2151 itemElementHelper = itemElement;
2152 pItemHelper = pItem->createChild(itemElementHelper.append("VirtualQuantity").c_str());
2153 pItemHelper->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2154 }
2155 }
2156 }
2157 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
2158
2159 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
2160 // under the vbox: namespace
2161 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
2162 // ovf:required="false" tells other OVF parsers that they can ignore this thing
2163 pelmVBoxMachine->setAttribute("ovf:required", "false");
2164 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
2165 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
2166
2167 // create an empty machine config
2168 // use the same settings version as the current VM settings file
2169 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(&vsdescThis->m->pMachine->i_getSettingsFileFull());
2170
2171 writeLock.release();
2172 try
2173 {
2174 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
2175 // fill the machine config
2176 vsdescThis->m->pMachine->i_copyMachineDataToSettings(*pConfig);
2177 pConfig->machineUserData.strName = strVMName;
2178
2179 // Apply export tweaks to machine settings
2180 bool fStripAllMACs = m->optListExport.contains(ExportOptions_StripAllMACs);
2181 bool fStripAllNonNATMACs = m->optListExport.contains(ExportOptions_StripAllNonNATMACs);
2182 if (fStripAllMACs || fStripAllNonNATMACs)
2183 {
2184 for (settings::NetworkAdaptersList::iterator
2185 it = pConfig->hardwareMachine.llNetworkAdapters.begin();
2186 it != pConfig->hardwareMachine.llNetworkAdapters.end();
2187 ++it)
2188 {
2189 settings::NetworkAdapter &nic = *it;
2190 if (fStripAllMACs || (fStripAllNonNATMACs && nic.mode != NetworkAttachmentType_NAT))
2191 nic.strMACAddress.setNull();
2192 }
2193 }
2194
2195 // write the machine config to the vbox:Machine element
2196 pConfig->buildMachineXML(*pelmVBoxMachine,
2197 settings::MachineConfigFile::BuildMachineXML_WriteVBoxVersionAttribute
2198 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
2199 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
2200 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
2201 pllElementsWithUuidAttributes);
2202 delete pConfig;
2203 }
2204 catch (...)
2205 {
2206 writeLock.acquire();
2207 delete pConfig;
2208 throw;
2209 }
2210 writeLock.acquire();
2211}
2212
2213/**
2214 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
2215 * and therefore runs on the OVF/OVA write worker thread.
2216 *
2217 * This runs in one context:
2218 *
2219 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl();
2220 *
2221 * @param pTask
2222 * @return
2223 */
2224HRESULT Appliance::i_writeFS(TaskOVF *pTask)
2225{
2226 LogFlowFuncEnter();
2227 LogFlowFunc(("ENTER appliance %p\n", this));
2228
2229 AutoCaller autoCaller(this);
2230 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2231
2232 HRESULT rc = S_OK;
2233
2234 // Lock the media tree early to make sure nobody else tries to make changes
2235 // to the tree. Also lock the IAppliance object for writing.
2236 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
2237 // Additional protect the IAppliance object, cause we leave the lock
2238 // when starting the disk export and we don't won't block other
2239 // callers on this lengthy operations.
2240 m->state = ApplianceExporting;
2241
2242 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
2243 rc = i_writeFSOVF(pTask, multiLock);
2244 else
2245 rc = i_writeFSOVA(pTask, multiLock);
2246
2247 // reset the state so others can call methods again
2248 m->state = ApplianceIdle;
2249
2250 LogFlowFunc(("rc=%Rhrc\n", rc));
2251 LogFlowFuncLeave();
2252 return rc;
2253}
2254
2255HRESULT Appliance::i_writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
2256{
2257 LogFlowFuncEnter();
2258
2259 /*
2260 * Create write-to-dir file system stream for the target directory.
2261 * This unifies the disk access with the TAR based OVA variant.
2262 */
2263 HRESULT hrc;
2264 int vrc;
2265 RTVFSFSSTREAM hVfsFss2Dir = NIL_RTVFSFSSTREAM;
2266 try
2267 {
2268 Utf8Str strTargetDir(pTask->locInfo.strPath);
2269 strTargetDir.stripFilename();
2270 vrc = RTVfsFsStrmToNormalDir(strTargetDir.c_str(), 0 /*fFlags*/, &hVfsFss2Dir);
2271 if (RT_SUCCESS(vrc))
2272 hrc = S_OK;
2273 else
2274 hrc = setErrorVrc(vrc, tr("Failed to open directory '%s' (%Rrc)"), strTargetDir.c_str(), vrc);
2275 }
2276 catch (std::bad_alloc &)
2277 {
2278 hrc = E_OUTOFMEMORY;
2279 }
2280 if (SUCCEEDED(hrc))
2281 {
2282 /*
2283 * Join i_writeFSOVA. On failure, delete (undo) anything we might
2284 * have written to the disk before failing.
2285 */
2286 hrc = i_writeFSImpl(pTask, writeLock, hVfsFss2Dir);
2287 if (FAILED(hrc))
2288 RTVfsFsStrmToDirUndo(hVfsFss2Dir);
2289 RTVfsFsStrmRelease(hVfsFss2Dir);
2290 }
2291
2292 LogFlowFuncLeave();
2293 return hrc;
2294}
2295
2296HRESULT Appliance::i_writeFSOVA(TaskOVF *pTask, AutoWriteLockBase &writeLock)
2297{
2298 LogFlowFuncEnter();
2299
2300 /*
2301 * Open the output file and attach a TAR creator to it.
2302 * The OVF 1.1.0 spec specifies the TAR format to be compatible with USTAR
2303 * according to POSIX 1003.1-2008. We use the 1988 spec here as it's the
2304 * only variant we currently implement.
2305 */
2306 HRESULT hrc;
2307 RTVFSIOSTREAM hVfsIosTar;
2308 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
2309 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2310 &hVfsIosTar);
2311 if (RT_SUCCESS(vrc))
2312 {
2313 RTVFSFSSTREAM hVfsFssTar;
2314 vrc = RTZipTarFsStreamToIoStream(hVfsIosTar, RTZIPTARFORMAT_USTAR, 0 /*fFlags*/, &hVfsFssTar);
2315 RTVfsIoStrmRelease(hVfsIosTar);
2316 if (RT_SUCCESS(vrc))
2317 {
2318 RTZipTarFsStreamSetFileMode(hVfsFssTar, 0660, 0440);
2319 RTZipTarFsStreamSetOwner(hVfsFssTar, VBOX_VERSION_MAJOR,
2320 pTask->enFormat == ovf::OVFVersion_0_9 ? "vboxovf09"
2321 : pTask->enFormat == ovf::OVFVersion_1_0 ? "vboxovf10"
2322 : pTask->enFormat == ovf::OVFVersion_2_0 ? "vboxovf20"
2323 : "vboxovf");
2324 RTZipTarFsStreamSetGroup(hVfsFssTar, VBOX_VERSION_MINOR,
2325 Utf8StrFmt("vbox_v" RT_XSTR(VBOX_VERSION_MAJOR) "." RT_XSTR(VBOX_VERSION_MINOR) "."
2326 RT_XSTR(VBOX_VERSION_BUILD) "r%RU32", RTBldCfgRevision()).c_str());
2327
2328 hrc = i_writeFSImpl(pTask, writeLock, hVfsFssTar);
2329 RTVfsFsStrmRelease(hVfsFssTar);
2330 }
2331 else
2332 hrc = setErrorVrc(vrc, tr("Failed create TAR creator for '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2333
2334 /* Delete the OVA on failure. */
2335 if (FAILED(hrc))
2336 RTFileDelete(pTask->locInfo.strPath.c_str());
2337 }
2338 else
2339 hrc = setErrorVrc(vrc, tr("Failed to open '%s' for writing (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2340
2341 LogFlowFuncLeave();
2342 return hrc;
2343}
2344
2345/**
2346 * Upload the image to the OCI Storage service, next import the
2347 * uploaded image into internal OCI image format and launch an
2348 * instance with this image in the OCI Compute service.
2349 */
2350HRESULT Appliance::i_exportCloudImpl(TaskCloud *pTask)
2351{
2352 LogFlowFuncEnter();
2353
2354 HRESULT hrc = S_OK;
2355 ComPtr<ICloudProviderManager> cpm;
2356 hrc = mVirtualBox->COMGETTER(CloudProviderManager)(cpm.asOutParam());
2357 if (FAILED(hrc))
2358 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud provider manager object wasn't found"), __FUNCTION__);
2359
2360 Utf8Str strProviderName = pTask->locInfo.strProvider;
2361 ComPtr<ICloudProvider> cloudProvider;
2362 ComPtr<ICloudProfile> cloudProfile;
2363 hrc = cpm->GetProviderByShortName(Bstr(strProviderName.c_str()).raw(), cloudProvider.asOutParam());
2364
2365 if (FAILED(hrc))
2366 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud provider object wasn't found"), __FUNCTION__);
2367
2368 ComPtr<IVirtualSystemDescription> vsd = m->virtualSystemDescriptions.front();
2369
2370 com::SafeArray<VirtualSystemDescriptionType_T> retTypes;
2371 com::SafeArray<BSTR> aRefs;
2372 com::SafeArray<BSTR> aOvfValues;
2373 com::SafeArray<BSTR> aVBoxValues;
2374 com::SafeArray<BSTR> aExtraConfigValues;
2375
2376 hrc = vsd->GetDescriptionByType(VirtualSystemDescriptionType_CloudProfileName,
2377 ComSafeArrayAsOutParam(retTypes),
2378 ComSafeArrayAsOutParam(aRefs),
2379 ComSafeArrayAsOutParam(aOvfValues),
2380 ComSafeArrayAsOutParam(aVBoxValues),
2381 ComSafeArrayAsOutParam(aExtraConfigValues));
2382 if (FAILED(hrc))
2383 return hrc;
2384
2385 Utf8Str profileName(aVBoxValues[0]);
2386 if (profileName.isEmpty())
2387 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud user profile name wasn't found"), __FUNCTION__);
2388
2389 hrc = cloudProvider->GetProfileByName(aVBoxValues[0], cloudProfile.asOutParam());
2390 if (FAILED(hrc))
2391 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud profile object wasn't found"), __FUNCTION__);
2392
2393 ComObjPtr<ICloudClient> cloudClient;
2394 hrc = cloudProfile->CreateCloudClient(cloudClient.asOutParam());
2395 if (FAILED(hrc))
2396 return setError(VBOX_E_OBJECT_NOT_FOUND, tr("%s: Cloud client object wasn't found"), __FUNCTION__);
2397
2398 if (m->virtualSystemDescriptions.size() == 1)
2399 {
2400 ComPtr<IVirtualBox> VBox(mVirtualBox);
2401 hrc = cloudClient->ExportVM(m->virtualSystemDescriptions.front(), pTask->pProgress);
2402 }
2403 else
2404 hrc = setErrorVrc(VERR_MISMATCH, tr("Export to Cloud isn't supported for more than one VM instance."));
2405
2406 LogFlowFuncLeave();
2407 return hrc;
2408}
2409
2410
2411/**
2412 * Writes the Oracle Public Cloud appliance.
2413 *
2414 * It expect raw disk images inside a gzipped tarball. We enable sparse files
2415 * to save diskspace on the target host system.
2416 */
2417HRESULT Appliance::i_writeFSOPC(TaskOPC *pTask)
2418{
2419 LogFlowFuncEnter();
2420 HRESULT hrc = S_OK;
2421
2422 // Lock the media tree early to make sure nobody else tries to make changes
2423 // to the tree. Also lock the IAppliance object for writing.
2424 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
2425 // Additional protect the IAppliance object, cause we leave the lock
2426 // when starting the disk export and we don't won't block other
2427 // callers on this lengthy operations.
2428 m->state = ApplianceExporting;
2429
2430 /*
2431 * We're duplicating parts of i_writeFSImpl here because that's simpler
2432 * and creates less spaghetti code.
2433 */
2434 std::list<Utf8Str> lstTarballs;
2435
2436 /*
2437 * Use i_buildXML to build a stack of disk images. We don't care about the XML doc here.
2438 */
2439 XMLStack stack;
2440 {
2441 xml::Document doc;
2442 i_buildXML(multiLock, doc, stack, pTask->locInfo.strPath, ovf::OVFVersion_2_0);
2443 }
2444
2445 /*
2446 * Process the disk images.
2447 */
2448 unsigned cTarballs = 0;
2449 for (list<Utf8Str>::const_iterator it = stack.mapDiskSequence.begin();
2450 it != stack.mapDiskSequence.end();
2451 ++it)
2452 {
2453 const Utf8Str &strDiskID = *it;
2454 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2455 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent; // where the VBox image is
2456
2457 /*
2458 * Some skipping.
2459 */
2460 if (pDiskEntry->skipIt)
2461 continue;
2462
2463 /* Skip empty media (DVD-ROM, floppy). */
2464 if (strSrcFilePath.isEmpty())
2465 continue;
2466
2467 /* Only deal with harddisk and DVD-ROMs, skip any floppies for now. */
2468 if ( pDiskEntry->type != VirtualSystemDescriptionType_HardDiskImage
2469 && pDiskEntry->type != VirtualSystemDescriptionType_CDROM)
2470 continue;
2471
2472 /*
2473 * Locate the Medium object for this entry (by location/path).
2474 */
2475 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2476 ComObjPtr<Medium> ptrSourceDisk;
2477 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2478 hrc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true /*aSetError*/, &ptrSourceDisk);
2479 else
2480 hrc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD, NULL /*aId*/, strSrcFilePath,
2481 true /*aSetError*/, &ptrSourceDisk);
2482 if (FAILED(hrc))
2483 break;
2484 if (strSrcFilePath.isEmpty())
2485 continue;
2486
2487 /*
2488 * Figure out the names.
2489 */
2490
2491 /* The name inside the tarball. Replace the suffix of harddisk images with ".img". */
2492 Utf8Str strInsideName = pDiskEntry->strOvf;
2493 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2494 strInsideName.stripSuffix().append(".img");
2495
2496 /* The first tarball we create uses the specified name. Subsequent
2497 takes the name from the disk entry or something. */
2498 Utf8Str strTarballPath = pTask->locInfo.strPath;
2499 if (cTarballs > 0)
2500 {
2501 strTarballPath.stripFilename().append(RTPATH_SLASH_STR).append(pDiskEntry->strOvf);
2502 const char *pszExt = RTPathSuffix(pDiskEntry->strOvf.c_str());
2503 if (pszExt && pszExt[0] == '.' && pszExt[1] != '\0')
2504 {
2505 strTarballPath.stripSuffix();
2506 if (pDiskEntry->type != VirtualSystemDescriptionType_HardDiskImage)
2507 strTarballPath.append("_").append(&pszExt[1]);
2508 }
2509 strTarballPath.append(".tar.gz");
2510 }
2511 cTarballs++;
2512
2513 /*
2514 * Create the tar output stream.
2515 */
2516 RTVFSIOSTREAM hVfsIosFile;
2517 int vrc = RTVfsIoStrmOpenNormal(strTarballPath.c_str(),
2518 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2519 &hVfsIosFile);
2520 if (RT_SUCCESS(vrc))
2521 {
2522 RTVFSIOSTREAM hVfsIosGzip = NIL_RTVFSIOSTREAM;
2523 vrc = RTZipGzipCompressIoStream(hVfsIosFile, 0 /*fFlags*/, 6 /*uLevel*/, &hVfsIosGzip);
2524 RTVfsIoStrmRelease(hVfsIosFile);
2525
2526 /** @todo insert I/O thread here between gzip and the tar creator. Needs
2527 * implementing. */
2528
2529 RTVFSFSSTREAM hVfsFssTar = NIL_RTVFSFSSTREAM;
2530 if (RT_SUCCESS(vrc))
2531 vrc = RTZipTarFsStreamToIoStream(hVfsIosGzip, RTZIPTARFORMAT_GNU, RTZIPTAR_C_SPARSE, &hVfsFssTar);
2532 RTVfsIoStrmRelease(hVfsIosGzip);
2533 if (RT_SUCCESS(vrc))
2534 {
2535 RTZipTarFsStreamSetFileMode(hVfsFssTar, 0660, 0440);
2536 RTZipTarFsStreamSetOwner(hVfsFssTar, VBOX_VERSION_MAJOR, "vboxopc10");
2537 RTZipTarFsStreamSetGroup(hVfsFssTar, VBOX_VERSION_MINOR,
2538 Utf8StrFmt("vbox_v" RT_XSTR(VBOX_VERSION_MAJOR) "." RT_XSTR(VBOX_VERSION_MINOR) "."
2539 RT_XSTR(VBOX_VERSION_BUILD) "r%RU32", RTBldCfgRevision()).c_str());
2540
2541 /*
2542 * Let the Medium code do the heavy work.
2543 *
2544 * The exporting requests a lock on the media tree. So temporarily
2545 * leave the appliance lock.
2546 */
2547 multiLock.release();
2548
2549 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%Rbn'"), strTarballPath.c_str()).raw(),
2550 pDiskEntry->ulSizeMB); // operation's weight, as set up
2551 // with the IProgress originally
2552 hrc = ptrSourceDisk->i_addRawToFss(strInsideName.c_str(), m->m_pSecretKeyStore, hVfsFssTar,
2553 pTask->pProgress, true /*fSparse*/);
2554
2555 multiLock.acquire();
2556 if (SUCCEEDED(hrc))
2557 {
2558 /*
2559 * Complete and close the tarball.
2560 */
2561 vrc = RTVfsFsStrmEnd(hVfsFssTar);
2562 RTVfsFsStrmRelease(hVfsFssTar);
2563 hVfsFssTar = NIL_RTVFSFSSTREAM;
2564 if (RT_SUCCESS(vrc))
2565 {
2566 /* Remember the tarball name for cleanup. */
2567 try
2568 {
2569 lstTarballs.push_back(strTarballPath.c_str());
2570 strTarballPath.setNull();
2571 }
2572 catch (std::bad_alloc &)
2573 { hrc = E_OUTOFMEMORY; }
2574 }
2575 else
2576 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc,
2577 tr("Error completing TAR file '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2578 }
2579 }
2580 else
2581 hrc = setErrorVrc(vrc, tr("Failed to TAR creator instance for '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2582
2583 if (FAILED(hrc) && strTarballPath.isNotEmpty())
2584 RTFileDelete(strTarballPath.c_str());
2585 }
2586 else
2587 hrc = setErrorVrc(vrc, tr("Failed to create '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2588 if (FAILED(hrc))
2589 break;
2590 }
2591
2592 /*
2593 * Delete output files on failure.
2594 */
2595 if (FAILED(hrc))
2596 for (list<Utf8Str>::const_iterator it = lstTarballs.begin(); it != lstTarballs.end(); ++it)
2597 RTFileDelete(it->c_str());
2598
2599 // reset the state so others can call methods again
2600 m->state = ApplianceIdle;
2601
2602 LogFlowFuncLeave();
2603 return hrc;
2604
2605}
2606
2607HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase &writeLock, RTVFSFSSTREAM hVfsFssDst)
2608{
2609 LogFlowFuncEnter();
2610
2611 HRESULT rc = S_OK;
2612 int vrc;
2613 try
2614 {
2615 // the XML stack contains two maps for disks and networks, which allows us to
2616 // a) have a list of unique disk names (to make sure the same disk name is only added once)
2617 // and b) keep a list of all networks
2618 XMLStack stack;
2619 // Scope this to free the memory as soon as this is finished
2620 {
2621 /* Construct the OVF name. */
2622 Utf8Str strOvfFile(pTask->locInfo.strPath);
2623 strOvfFile.stripPath().stripSuffix().append(".ovf");
2624
2625 /* Render a valid ovf document into a memory buffer. The unknown
2626 version upgrade relates to the OPC hack up in Appliance::write(). */
2627 xml::Document doc;
2628 i_buildXML(writeLock, doc, stack, pTask->locInfo.strPath,
2629 pTask->enFormat != ovf::OVFVersion_unknown ? pTask->enFormat : ovf::OVFVersion_2_0);
2630
2631 void *pvBuf = NULL;
2632 size_t cbSize = 0;
2633 xml::XmlMemWriter writer;
2634 writer.write(doc, &pvBuf, &cbSize);
2635 if (RT_UNLIKELY(!pvBuf))
2636 throw setError(VBOX_E_FILE_ERROR, tr("Could not create OVF file '%s'"), strOvfFile.c_str());
2637
2638 /* Write the ovf file to "disk". */
2639 rc = i_writeBufferToFile(hVfsFssDst, strOvfFile.c_str(), pvBuf, cbSize);
2640 if (FAILED(rc))
2641 throw rc;
2642 }
2643
2644 // We need a proper format description
2645 ComObjPtr<MediumFormat> formatTemp;
2646
2647 ComObjPtr<MediumFormat> format;
2648 // Scope for the AutoReadLock
2649 {
2650 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2651 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2652 // We are always exporting to VMDK stream optimized for now
2653 formatTemp = pSysProps->i_mediumFormatFromExtension("iso");
2654
2655 format = pSysProps->i_mediumFormat("VMDK");
2656 if (format.isNull())
2657 throw setError(VBOX_E_NOT_SUPPORTED,
2658 tr("Invalid medium storage format"));
2659 }
2660
2661 // Finally, write out the disks!
2662 //use the list stack.mapDiskSequence where the disks were put as the "VirtualSystem"s had been placed
2663 //in the OVF description file. I.e. we have one "VirtualSystem" in the OVF file, we extract all disks
2664 //attached to it. And these disks are stored in the stack.mapDiskSequence. Next we shift to the next
2665 //"VirtualSystem" and repeat the operation.
2666 //And here we go through the list and extract all disks in the same sequence
2667 for (list<Utf8Str>::const_iterator
2668 it = stack.mapDiskSequence.begin();
2669 it != stack.mapDiskSequence.end();
2670 ++it)
2671 {
2672 const Utf8Str &strDiskID = *it;
2673 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2674
2675 // source path: where the VBox image is
2676 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
2677
2678 //skip empty Medium. In common, It's may be empty CD/DVD
2679 if (strSrcFilePath.isEmpty() ||
2680 pDiskEntry->skipIt == true)
2681 continue;
2682
2683 // Do NOT check here whether the file exists. findHardDisk will
2684 // figure that out, and filesystem-based tests are simply wrong
2685 // in the general case (think of iSCSI).
2686
2687 // clone the disk:
2688 ComObjPtr<Medium> pSourceDisk;
2689
2690 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2691
2692 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2693 {
2694 rc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2695 if (FAILED(rc)) throw rc;
2696 }
2697 else//may be CD or DVD
2698 {
2699 rc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD,
2700 NULL,
2701 strSrcFilePath,
2702 true,
2703 &pSourceDisk);
2704 if (FAILED(rc)) throw rc;
2705 }
2706
2707 Bstr uuidSource;
2708 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2709 if (FAILED(rc)) throw rc;
2710 Guid guidSource(uuidSource);
2711
2712 // output filename
2713 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2714
2715 // target path needs to be composed from where the output OVF is
2716 const Utf8Str &strTargetFilePath = strTargetFileNameOnly;
2717
2718 // The exporting requests a lock on the media tree. So leave our lock temporary.
2719 writeLock.release();
2720 try
2721 {
2722 // advance to the next operation
2723 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"),
2724 RTPathFilename(strTargetFilePath.c_str())).raw(),
2725 pDiskEntry->ulSizeMB); // operation's weight, as set up
2726 // with the IProgress originally
2727
2728 // create a flat copy of the source disk image
2729 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2730 {
2731 /*
2732 * Export a disk image.
2733 */
2734 /* For compressed VMDK fun, we let i_exportFile produce the image bytes. */
2735 RTVFSIOSTREAM hVfsIosDst;
2736 vrc = RTVfsFsStrmPushFile(hVfsFssDst, strTargetFilePath.c_str(), UINT64_MAX,
2737 NULL /*paObjInfo*/, 0 /*cObjInfo*/, RTVFSFSSTRM_PUSH_F_STREAM, &hVfsIosDst);
2738 if (RT_FAILURE(vrc))
2739 throw setErrorVrc(vrc, tr("RTVfsFsStrmPushFile failed for '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2740 hVfsIosDst = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosDst, strTargetFilePath.c_str(),
2741 false /*fRead*/);
2742 if (hVfsIosDst == NIL_RTVFSIOSTREAM)
2743 throw setError(E_FAIL, "i_manifestSetupDigestCalculationForGivenIoStream(%s)", strTargetFilePath.c_str());
2744
2745 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2746 format,
2747 MediumVariant_VmdkStreamOptimized,
2748 m->m_pSecretKeyStore,
2749 hVfsIosDst,
2750 pTask->pProgress);
2751 RTVfsIoStrmRelease(hVfsIosDst);
2752 }
2753 else
2754 {
2755 /*
2756 * Copy CD/DVD/floppy image.
2757 */
2758 Assert(pDiskEntry->type == VirtualSystemDescriptionType_CDROM);
2759 rc = pSourceDisk->i_addRawToFss(strTargetFilePath.c_str(), m->m_pSecretKeyStore, hVfsFssDst,
2760 pTask->pProgress, false /*fSparse*/);
2761 }
2762 if (FAILED(rc)) throw rc;
2763 }
2764 catch (HRESULT rc3)
2765 {
2766 writeLock.acquire();
2767 /// @todo file deletion on error? If not, we can remove that whole try/catch block.
2768 throw rc3;
2769 }
2770 // Finished, lock again (so nobody mess around with the medium tree
2771 // in the meantime)
2772 writeLock.acquire();
2773 }
2774
2775 if (m->fManifest)
2776 {
2777 // Create & write the manifest file
2778 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
2779 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2780 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2781 m->ulWeightForManifestOperation); // operation's weight, as set up
2782 // with the IProgress originally);
2783 /* Create a memory I/O stream and write the manifest to it. */
2784 RTVFSIOSTREAM hVfsIosManifest;
2785 vrc = RTVfsMemIoStrmCreate(NIL_RTVFSIOSTREAM, _1K, &hVfsIosManifest);
2786 if (RT_FAILURE(vrc))
2787 throw setErrorVrc(vrc, tr("RTVfsMemIoStrmCreate failed (%Rrc)"), vrc);
2788 if (m->hOurManifest != NIL_RTMANIFEST) /* In case it's empty. */
2789 vrc = RTManifestWriteStandard(m->hOurManifest, hVfsIosManifest);
2790 if (RT_SUCCESS(vrc))
2791 {
2792 /* Rewind the stream and add it to the output. */
2793 size_t cbIgnored;
2794 vrc = RTVfsIoStrmReadAt(hVfsIosManifest, 0 /*offset*/, &cbIgnored, 0, true /*fBlocking*/, &cbIgnored);
2795 if (RT_SUCCESS(vrc))
2796 {
2797 RTVFSOBJ hVfsObjManifest = RTVfsObjFromIoStream(hVfsIosManifest);
2798 vrc = RTVfsFsStrmAdd(hVfsFssDst, strMfFileName.c_str(), hVfsObjManifest, 0 /*fFlags*/);
2799 if (RT_SUCCESS(vrc))
2800 rc = S_OK;
2801 else
2802 rc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for the manifest (%Rrc)"), vrc);
2803 }
2804 else
2805 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2806 }
2807 else
2808 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2809 RTVfsIoStrmRelease(hVfsIosManifest);
2810 if (FAILED(rc))
2811 throw rc;
2812 }
2813 }
2814 catch (RTCError &x) // includes all XML exceptions
2815 {
2816 rc = setError(VBOX_E_FILE_ERROR,
2817 x.what());
2818 }
2819 catch (HRESULT aRC)
2820 {
2821 rc = aRC;
2822 }
2823
2824 LogFlowFunc(("rc=%Rhrc\n", rc));
2825 LogFlowFuncLeave();
2826
2827 return rc;
2828}
2829
2830
2831/**
2832 * Writes a memory buffer to a file in the output file system stream.
2833 *
2834 * @returns COM status code.
2835 * @param hVfsFssDst The file system stream to add the file to.
2836 * @param pszFilename The file name (w/ path if desired).
2837 * @param pvContent Pointer to buffer containing the file content.
2838 * @param cbContent Size of the content.
2839 */
2840HRESULT Appliance::i_writeBufferToFile(RTVFSFSSTREAM hVfsFssDst, const char *pszFilename, const void *pvContent, size_t cbContent)
2841{
2842 /*
2843 * Create a VFS file around the memory, converting it to a base VFS object handle.
2844 */
2845 HRESULT hrc;
2846 RTVFSIOSTREAM hVfsIosSrc;
2847 int vrc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pvContent, cbContent, &hVfsIosSrc);
2848 if (RT_SUCCESS(vrc))
2849 {
2850 hVfsIosSrc = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosSrc, pszFilename);
2851 AssertReturn(hVfsIosSrc != NIL_RTVFSIOSTREAM,
2852 setErrorVrc(vrc, "i_manifestSetupDigestCalculationForGivenIoStream"));
2853
2854 RTVFSOBJ hVfsObj = RTVfsObjFromIoStream(hVfsIosSrc);
2855 RTVfsIoStrmRelease(hVfsIosSrc);
2856 AssertReturn(hVfsObj != NIL_RTVFSOBJ, E_FAIL);
2857
2858 /*
2859 * Add it to the stream.
2860 */
2861 vrc = RTVfsFsStrmAdd(hVfsFssDst, pszFilename, hVfsObj, 0);
2862 RTVfsObjRelease(hVfsObj);
2863 if (RT_SUCCESS(vrc))
2864 hrc = S_OK;
2865 else
2866 hrc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for '%s' (%Rrc)"), pszFilename, vrc);
2867 }
2868 else
2869 hrc = setErrorVrc(vrc, "RTVfsIoStrmFromBuffer");
2870 return hrc;
2871}
2872
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