VirtualBox

source: vbox/trunk/src/VBox/Main/ApplianceImplExport.cpp@ 32876

Last change on this file since 32876 was 32850, checked in by vboxsync, 14 years ago

Main: utilize Medium::exportFile on Appliance export

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