VirtualBox

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

Last change on this file since 32846 was 32837, checked in by vboxsync, 14 years ago

Main: separate ovf creation and disk exporting

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