VirtualBox

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

Last change on this file since 33146 was 33102, checked in by vboxsync, 14 years ago

Main/Appliance: rip out the bogus "does image exist" checks, they prevent exporting VMs with iSCSI disks and other non-file based media

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 88.3 KB
Line 
1/* $Id: ApplianceImplExport.cpp 33102 2010-10-13 12:13:44Z 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
804 // Do NOT check here whether the file exists. FindMedium will figure
805 // that out, and filesystem-based tests are simply wrong in the
806 // general case (think of iSCSI).
807
808 // We need some info from the source disks
809 ComPtr<IMedium> pSourceDisk;
810
811 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
812 HRESULT rc = mVirtualBox->FindMedium(bstrSrcFilePath.raw(), DeviceType_HardDisk, pSourceDisk.asOutParam());
813 if (FAILED(rc)) throw rc;
814
815 Bstr uuidSource;
816 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
817 if (FAILED(rc)) throw rc;
818 Guid guidSource(uuidSource);
819
820 // output filename
821 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
822 // target path needs to be composed from where the output OVF is
823 Utf8Str strTargetFilePath(strPath);
824 strTargetFilePath.stripFilename();
825 strTargetFilePath.append("/");
826 strTargetFilePath.append(strTargetFileNameOnly);
827
828 // We are always exporting to VMDK stream optimized for now
829 Bstr bstrSrcFormat = L"VMDK";
830
831 diskList.push_back(strTargetFilePath);
832
833 LONG64 cbCapacity = 0; // size reported to guest
834 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
835 if (FAILED(rc)) throw rc;
836 // Todo r=poetzsch: wrong it is reported in bytes ...
837 // capacity is reported in megabytes, so...
838 //cbCapacity *= _1M;
839
840 Guid guidTarget; /* Creates a new uniq number for the target disk. */
841 guidTarget.create();
842
843 // now handle the XML for the disk:
844 Utf8StrFmt strFileRef("file%RI32", ulFile++);
845 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
846 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
847 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
848 pelmFile->setAttribute("ovf:id", strFileRef);
849 // Todo: the actual size is not available at this point of time,
850 // cause the disk will be compressed. The 1.0 standard says this is
851 // optional! 1.1 isn't fully clear if the "gzip" format is used.
852 // Need to be checked. */
853 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
854
855 // add disk to XML Disks section
856 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
857 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
858 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
859 pelmDisk->setAttribute("ovf:diskId", strDiskID);
860 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
861 pelmDisk->setAttribute("ovf:format",
862 (enFormat == OVF_0_9)
863 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftool chokes
864 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
865 // correct string as communicated to us by VMware (public bug #6612)
866 );
867
868 // add the UUID of the newly target image to the OVF disk element, but in the
869 // vbox: namespace since it's not part of the standard
870 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
871
872 // now, we might have other XML elements from vbox:Machine pointing to this image,
873 // but those would refer to the UUID of the _source_ image (which we created the
874 // export image from); those UUIDs need to be fixed to the export image
875 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
876 for (std::list<xml::ElementNode*>::iterator eit = llElementsWithUuidAttributes.begin();
877 eit != llElementsWithUuidAttributes.end();
878 ++eit)
879 {
880 xml::ElementNode *pelmImage = *eit;
881 Utf8Str strUUID;
882 pelmImage->getAttributeValue("uuid", strUUID);
883 if (strUUID == strGuidSourceCurly)
884 // overwrite existing uuid attribute
885 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
886 }
887 }
888}
889
890/**
891 * Called from Appliance::buildXML() for each virtual system (machine) that
892 * needs XML written out.
893 *
894 * @param writeLock The current write lock.
895 * @param elmToAddVirtualSystemsTo XML element to append elements to.
896 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
897 * with UUID attributes for quick
898 * fixing by caller later
899 * @param vsdescThis The IVirtualSystemDescription
900 * instance for which to write XML.
901 * @param enFormat OVF format (0.9 or 1.0).
902 * @param stack Structure for temporary private
903 * data shared with caller.
904 */
905void Appliance::buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
906 xml::ElementNode &elmToAddVirtualSystemsTo,
907 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
908 ComObjPtr<VirtualSystemDescription> &vsdescThis,
909 OVFFormat enFormat,
910 XMLStack &stack)
911{
912 LogFlowFunc(("ENTER appliance %p\n", this));
913
914 xml::ElementNode *pelmVirtualSystem;
915 if (enFormat == OVF_0_9)
916 {
917 // <Section xsi:type="ovf:NetworkSection_Type">
918 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
919 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
920 }
921 else
922 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
923
924 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
925
926 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
927 if (llName.size() != 1)
928 throw setError(VBOX_E_NOT_SUPPORTED,
929 tr("Missing VM name"));
930 Utf8Str &strVMName = llName.front()->strVboxCurrent;
931 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
932
933 // product info
934 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
935 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
936 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
937 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
938 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
939 bool fProduct = llProduct.size() && !llProduct.front()->strVboxCurrent.isEmpty();
940 bool fProductUrl = llProductUrl.size() && !llProductUrl.front()->strVboxCurrent.isEmpty();
941 bool fVendor = llVendor.size() && !llVendor.front()->strVboxCurrent.isEmpty();
942 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.front()->strVboxCurrent.isEmpty();
943 bool fVersion = llVersion.size() && !llVersion.front()->strVboxCurrent.isEmpty();
944 if (fProduct ||
945 fProductUrl ||
946 fVersion ||
947 fVendorUrl ||
948 fVersion)
949 {
950 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
951 <Info>Meta-information about the installed software</Info>
952 <Product>VAtest</Product>
953 <Vendor>SUN Microsystems</Vendor>
954 <Version>10.0</Version>
955 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
956 <VendorUrl>http://www.sun.com</VendorUrl>
957 </Section> */
958 xml::ElementNode *pelmAnnotationSection;
959 if (enFormat == OVF_0_9)
960 {
961 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
962 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
963 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
964 }
965 else
966 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
967
968 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
969 if (fProduct)
970 pelmAnnotationSection->createChild("Product")->addContent(llProduct.front()->strVboxCurrent);
971 if (fVendor)
972 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.front()->strVboxCurrent);
973 if (fVersion)
974 pelmAnnotationSection->createChild("Version")->addContent(llVersion.front()->strVboxCurrent);
975 if (fProductUrl)
976 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.front()->strVboxCurrent);
977 if (fVendorUrl)
978 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.front()->strVboxCurrent);
979 }
980
981 // description
982 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
983 if (llDescription.size() &&
984 !llDescription.front()->strVboxCurrent.isEmpty())
985 {
986 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
987 <Info>A human-readable annotation</Info>
988 <Annotation>Plan 9</Annotation>
989 </Section> */
990 xml::ElementNode *pelmAnnotationSection;
991 if (enFormat == OVF_0_9)
992 {
993 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
994 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
995 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
996 }
997 else
998 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
999
1000 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1001 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.front()->strVboxCurrent);
1002 }
1003
1004 // license
1005 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
1006 if (llLicense.size() &&
1007 !llLicense.front()->strVboxCurrent.isEmpty())
1008 {
1009 /* <EulaSection>
1010 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1011 <License ovf:msgid="1">License terms can go in here.</License>
1012 </EulaSection> */
1013 xml::ElementNode *pelmEulaSection;
1014 if (enFormat == OVF_0_9)
1015 {
1016 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1017 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1018 }
1019 else
1020 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1021
1022 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1023 pelmEulaSection->createChild("License")->addContent(llLicense.front()->strVboxCurrent);
1024 }
1025
1026 // operating system
1027 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1028 if (llOS.size() != 1)
1029 throw setError(VBOX_E_NOT_SUPPORTED,
1030 tr("Missing OS type"));
1031 /* <OperatingSystemSection ovf:id="82">
1032 <Info>Guest Operating System</Info>
1033 <Description>Linux 2.6.x</Description>
1034 </OperatingSystemSection> */
1035 xml::ElementNode *pelmOperatingSystemSection;
1036 if (enFormat == OVF_0_9)
1037 {
1038 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1039 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1040 }
1041 else
1042 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1043
1044 pelmOperatingSystemSection->setAttribute("ovf:id", llOS.front()->strOvf);
1045 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1046 Utf8Str strOSDesc;
1047 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)llOS.front()->strOvf.toInt32(), "");
1048 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1049
1050 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1051 xml::ElementNode *pelmVirtualHardwareSection;
1052 if (enFormat == OVF_0_9)
1053 {
1054 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1055 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1056 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1057 }
1058 else
1059 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1060
1061 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1062
1063 /* <System>
1064 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1065 <vssd:ElementName>vmware</vssd:ElementName>
1066 <vssd:InstanceID>1</vssd:InstanceID>
1067 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1068 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1069 </System> */
1070 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1071
1072 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1073
1074 // <vssd:InstanceId>0</vssd:InstanceId>
1075 if (enFormat == OVF_0_9)
1076 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1077 else // capitalization changed...
1078 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1079
1080 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1081 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1082 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1083 const char *pcszHardware = "virtualbox-2.2";
1084 if (enFormat == OVF_0_9)
1085 // pretend to be vmware compatible then
1086 pcszHardware = "vmx-6";
1087 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1088
1089 // loop thru all description entries twice; once to write out all
1090 // devices _except_ disk images, and a second time to assign the
1091 // disk images; this is because disk images need to reference
1092 // IDE controllers, and we can't know their instance IDs without
1093 // assigning them first
1094
1095 uint32_t idIDEPrimaryController = 0;
1096 int32_t lIDEPrimaryControllerIndex = 0;
1097 uint32_t idIDESecondaryController = 0;
1098 int32_t lIDESecondaryControllerIndex = 0;
1099 uint32_t idSATAController = 0;
1100 int32_t lSATAControllerIndex = 0;
1101 uint32_t idSCSIController = 0;
1102 int32_t lSCSIControllerIndex = 0;
1103
1104 uint32_t ulInstanceID = 1;
1105
1106 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1107 {
1108 int32_t lIndexThis = 0;
1109 list<VirtualSystemDescriptionEntry>::const_iterator itD;
1110 for (itD = vsdescThis->m->llDescriptions.begin();
1111 itD != vsdescThis->m->llDescriptions.end();
1112 ++itD, ++lIndexThis)
1113 {
1114 const VirtualSystemDescriptionEntry &desc = *itD;
1115
1116 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVbox=%s, strExtraConfig=%s\n",
1117 uLoop,
1118 desc.ulIndex,
1119 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1120 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1121 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1122 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1123 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1124 : Utf8StrFmt("%d", desc.type).c_str()),
1125 desc.strRef.c_str(),
1126 desc.strOvf.c_str(),
1127 desc.strVboxCurrent.c_str(),
1128 desc.strExtraConfigCurrent.c_str()));
1129
1130 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1131 Utf8Str strResourceSubType;
1132
1133 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1134 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1135
1136 uint32_t ulParent = 0;
1137
1138 int32_t lVirtualQuantity = -1;
1139 Utf8Str strAllocationUnits;
1140
1141 int32_t lAddress = -1;
1142 int32_t lBusNumber = -1;
1143 int32_t lAddressOnParent = -1;
1144
1145 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1146 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1147 Utf8Str strHostResource;
1148
1149 uint64_t uTemp;
1150
1151 switch (desc.type)
1152 {
1153 case VirtualSystemDescriptionType_CPU:
1154 /* <Item>
1155 <rasd:Caption>1 virtual CPU</rasd:Caption>
1156 <rasd:Description>Number of virtual CPUs</rasd:Description>
1157 <rasd:ElementName>virtual CPU</rasd:ElementName>
1158 <rasd:InstanceID>1</rasd:InstanceID>
1159 <rasd:ResourceType>3</rasd:ResourceType>
1160 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1161 </Item> */
1162 if (uLoop == 1)
1163 {
1164 strDescription = "Number of virtual CPUs";
1165 type = ovf::ResourceType_Processor; // 3
1166 desc.strVboxCurrent.toInt(uTemp);
1167 lVirtualQuantity = (int32_t)uTemp;
1168 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
1169 }
1170 break;
1171
1172 case VirtualSystemDescriptionType_Memory:
1173 /* <Item>
1174 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1175 <rasd:Caption>256 MB of memory</rasd:Caption>
1176 <rasd:Description>Memory Size</rasd:Description>
1177 <rasd:ElementName>Memory</rasd:ElementName>
1178 <rasd:InstanceID>2</rasd:InstanceID>
1179 <rasd:ResourceType>4</rasd:ResourceType>
1180 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1181 </Item> */
1182 if (uLoop == 1)
1183 {
1184 strDescription = "Memory Size";
1185 type = ovf::ResourceType_Memory; // 4
1186 desc.strVboxCurrent.toInt(uTemp);
1187 lVirtualQuantity = (int32_t)(uTemp / _1M);
1188 strAllocationUnits = "MegaBytes";
1189 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
1190 }
1191 break;
1192
1193 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1194 /* <Item>
1195 <rasd:Caption>ideController1</rasd:Caption>
1196 <rasd:Description>IDE Controller</rasd:Description>
1197 <rasd:InstanceId>5</rasd:InstanceId>
1198 <rasd:ResourceType>5</rasd:ResourceType>
1199 <rasd:Address>1</rasd:Address>
1200 <rasd:BusNumber>1</rasd:BusNumber>
1201 </Item> */
1202 if (uLoop == 1)
1203 {
1204 strDescription = "IDE Controller";
1205 type = ovf::ResourceType_IDEController; // 5
1206 strResourceSubType = desc.strVboxCurrent;
1207
1208 if (!lIDEPrimaryControllerIndex)
1209 {
1210 // first IDE controller:
1211 strCaption = "ideController0";
1212 lAddress = 0;
1213 lBusNumber = 0;
1214 // remember this ID
1215 idIDEPrimaryController = ulInstanceID;
1216 lIDEPrimaryControllerIndex = lIndexThis;
1217 }
1218 else
1219 {
1220 // second IDE controller:
1221 strCaption = "ideController1";
1222 lAddress = 1;
1223 lBusNumber = 1;
1224 // remember this ID
1225 idIDESecondaryController = ulInstanceID;
1226 lIDESecondaryControllerIndex = lIndexThis;
1227 }
1228 }
1229 break;
1230
1231 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1232 /* <Item>
1233 <rasd:Caption>sataController0</rasd:Caption>
1234 <rasd:Description>SATA Controller</rasd:Description>
1235 <rasd:InstanceId>4</rasd:InstanceId>
1236 <rasd:ResourceType>20</rasd:ResourceType>
1237 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1238 <rasd:Address>0</rasd:Address>
1239 <rasd:BusNumber>0</rasd:BusNumber>
1240 </Item>
1241 */
1242 if (uLoop == 1)
1243 {
1244 strDescription = "SATA Controller";
1245 strCaption = "sataController0";
1246 type = ovf::ResourceType_OtherStorageDevice; // 20
1247 // it seems that OVFTool always writes these two, and since we can only
1248 // have one SATA controller, we'll use this as well
1249 lAddress = 0;
1250 lBusNumber = 0;
1251
1252 if ( desc.strVboxCurrent.isEmpty() // AHCI is the default in VirtualBox
1253 || (!desc.strVboxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1254 )
1255 strResourceSubType = "AHCI";
1256 else
1257 throw setError(VBOX_E_NOT_SUPPORTED,
1258 tr("Invalid config string \"%s\" in SATA controller"), desc.strVboxCurrent.c_str());
1259
1260 // remember this ID
1261 idSATAController = ulInstanceID;
1262 lSATAControllerIndex = lIndexThis;
1263 }
1264 break;
1265
1266 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1267 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1268 /* <Item>
1269 <rasd:Caption>scsiController0</rasd:Caption>
1270 <rasd:Description>SCSI Controller</rasd:Description>
1271 <rasd:InstanceId>4</rasd:InstanceId>
1272 <rasd:ResourceType>6</rasd:ResourceType>
1273 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1274 <rasd:Address>0</rasd:Address>
1275 <rasd:BusNumber>0</rasd:BusNumber>
1276 </Item>
1277 */
1278 if (uLoop == 1)
1279 {
1280 strDescription = "SCSI Controller";
1281 strCaption = "scsiController0";
1282 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1283 // it seems that OVFTool always writes these two, and since we can only
1284 // have one SATA controller, we'll use this as well
1285 lAddress = 0;
1286 lBusNumber = 0;
1287
1288 if ( desc.strVboxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1289 || (!desc.strVboxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1290 )
1291 strResourceSubType = "lsilogic";
1292 else if (!desc.strVboxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1293 strResourceSubType = "buslogic";
1294 else if (!desc.strVboxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1295 strResourceSubType = "lsilogicsas";
1296 else
1297 throw setError(VBOX_E_NOT_SUPPORTED,
1298 tr("Invalid config string \"%s\" in SCSI/SAS controller"), desc.strVboxCurrent.c_str());
1299
1300 // remember this ID
1301 idSCSIController = ulInstanceID;
1302 lSCSIControllerIndex = lIndexThis;
1303 }
1304 break;
1305
1306 case VirtualSystemDescriptionType_HardDiskImage:
1307 /* <Item>
1308 <rasd:Caption>disk1</rasd:Caption>
1309 <rasd:InstanceId>8</rasd:InstanceId>
1310 <rasd:ResourceType>17</rasd:ResourceType>
1311 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1312 <rasd:Parent>4</rasd:Parent>
1313 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1314 </Item> */
1315 if (uLoop == 2)
1316 {
1317 uint32_t cDisks = stack.mapDisks.size();
1318 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1319
1320 strDescription = "Disk Image";
1321 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1322 type = ovf::ResourceType_HardDisk; // 17
1323
1324 // the following references the "<Disks>" XML block
1325 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1326
1327 // controller=<index>;channel=<c>
1328 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1329 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1330 int32_t lControllerIndex = -1;
1331 if (pos1 != Utf8Str::npos)
1332 {
1333 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1334 if (lControllerIndex == lIDEPrimaryControllerIndex)
1335 ulParent = idIDEPrimaryController;
1336 else if (lControllerIndex == lIDESecondaryControllerIndex)
1337 ulParent = idIDESecondaryController;
1338 else if (lControllerIndex == lSCSIControllerIndex)
1339 ulParent = idSCSIController;
1340 else if (lControllerIndex == lSATAControllerIndex)
1341 ulParent = idSATAController;
1342 }
1343 if (pos2 != Utf8Str::npos)
1344 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1345
1346 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1347 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1348
1349 if ( !ulParent
1350 || lAddressOnParent == -1
1351 )
1352 throw setError(VBOX_E_NOT_SUPPORTED,
1353 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfigCurrent.c_str());
1354
1355 stack.mapDisks[strDiskID] = &desc;
1356 }
1357 break;
1358
1359 case VirtualSystemDescriptionType_Floppy:
1360 if (uLoop == 1)
1361 {
1362 strDescription = "Floppy Drive";
1363 strCaption = "floppy0"; // this is what OVFTool writes
1364 type = ovf::ResourceType_FloppyDrive; // 14
1365 lAutomaticAllocation = 0;
1366 lAddressOnParent = 0; // this is what OVFTool writes
1367 }
1368 break;
1369
1370 case VirtualSystemDescriptionType_CDROM:
1371 if (uLoop == 2)
1372 {
1373 // we can't have a CD without an IDE controller
1374 if (!idIDESecondaryController)
1375 throw setError(VBOX_E_NOT_SUPPORTED,
1376 tr("Can't have CD-ROM without secondary IDE controller"));
1377
1378 strDescription = "CD-ROM Drive";
1379 strCaption = "cdrom1"; // this is what OVFTool writes
1380 type = ovf::ResourceType_CDDrive; // 15
1381 lAutomaticAllocation = 1;
1382 ulParent = idIDESecondaryController;
1383 lAddressOnParent = 0; // this is what OVFTool writes
1384 }
1385 break;
1386
1387 case VirtualSystemDescriptionType_NetworkAdapter:
1388 /* <Item>
1389 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1390 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1391 <rasd:Connection>VM Network</rasd:Connection>
1392 <rasd:ElementName>VM network</rasd:ElementName>
1393 <rasd:InstanceID>3</rasd:InstanceID>
1394 <rasd:ResourceType>10</rasd:ResourceType>
1395 </Item> */
1396 if (uLoop == 1)
1397 {
1398 lAutomaticAllocation = 1;
1399 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1400 type = ovf::ResourceType_EthernetAdapter; // 10
1401 /* Set the hardware type to something useful.
1402 * To be compatible with vmware & others we set
1403 * PCNet32 for our PCNet types & E1000 for the
1404 * E1000 cards. */
1405 switch (desc.strVboxCurrent.toInt32())
1406 {
1407 case NetworkAdapterType_Am79C970A:
1408 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1409#ifdef VBOX_WITH_E1000
1410 case NetworkAdapterType_I82540EM:
1411 case NetworkAdapterType_I82545EM:
1412 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1413#endif /* VBOX_WITH_E1000 */
1414 }
1415 strConnection = desc.strOvf;
1416
1417 stack.mapNetworks[desc.strOvf] = true;
1418 }
1419 break;
1420
1421 case VirtualSystemDescriptionType_USBController:
1422 /* <Item ovf:required="false">
1423 <rasd:Caption>usb</rasd:Caption>
1424 <rasd:Description>USB Controller</rasd:Description>
1425 <rasd:InstanceId>3</rasd:InstanceId>
1426 <rasd:ResourceType>23</rasd:ResourceType>
1427 <rasd:Address>0</rasd:Address>
1428 <rasd:BusNumber>0</rasd:BusNumber>
1429 </Item> */
1430 if (uLoop == 1)
1431 {
1432 strDescription = "USB Controller";
1433 strCaption = "usb";
1434 type = ovf::ResourceType_USBController; // 23
1435 lAddress = 0; // this is what OVFTool writes
1436 lBusNumber = 0; // this is what OVFTool writes
1437 }
1438 break;
1439
1440 case VirtualSystemDescriptionType_SoundCard:
1441 /* <Item ovf:required="false">
1442 <rasd:Caption>sound</rasd:Caption>
1443 <rasd:Description>Sound Card</rasd:Description>
1444 <rasd:InstanceId>10</rasd:InstanceId>
1445 <rasd:ResourceType>35</rasd:ResourceType>
1446 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1447 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1448 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1449 </Item> */
1450 if (uLoop == 1)
1451 {
1452 strDescription = "Sound Card";
1453 strCaption = "sound";
1454 type = ovf::ResourceType_SoundCard; // 35
1455 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1456 lAutomaticAllocation = 0;
1457 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1458 }
1459 break;
1460 }
1461
1462 if (type)
1463 {
1464 xml::ElementNode *pItem;
1465
1466 pItem = pelmVirtualHardwareSection->createChild("Item");
1467
1468 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1469 // the elements from the rasd: namespace must be sorted by letter, and VMware
1470 // actually requires this as well (see public bug #6612)
1471
1472 if (lAddress != -1)
1473 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1474
1475 if (lAddressOnParent != -1)
1476 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1477
1478 if (!strAllocationUnits.isEmpty())
1479 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1480
1481 if (lAutomaticAllocation != -1)
1482 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1483
1484 if (lBusNumber != -1)
1485 if (enFormat == OVF_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool compatibility
1486 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1487
1488 if (!strCaption.isEmpty())
1489 pItem->createChild("rasd:Caption")->addContent(strCaption);
1490
1491 if (!strConnection.isEmpty())
1492 pItem->createChild("rasd:Connection")->addContent(strConnection);
1493
1494 if (!strDescription.isEmpty())
1495 pItem->createChild("rasd:Description")->addContent(strDescription);
1496
1497 if (!strCaption.isEmpty())
1498 if (enFormat == OVF_1_0)
1499 pItem->createChild("rasd:ElementName")->addContent(strCaption);
1500
1501 if (!strHostResource.isEmpty())
1502 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1503
1504 // <rasd:InstanceID>1</rasd:InstanceID>
1505 xml::ElementNode *pelmInstanceID;
1506 if (enFormat == OVF_0_9)
1507 pelmInstanceID = pItem->createChild("rasd:InstanceId");
1508 else
1509 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1510 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
1511
1512 if (ulParent)
1513 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1514
1515 if (!strResourceSubType.isEmpty())
1516 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1517
1518 // <rasd:ResourceType>3</rasd:ResourceType>
1519 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1520
1521 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1522 if (lVirtualQuantity != -1)
1523 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1524 }
1525 }
1526 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1527
1528 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1529 // under the vbox: namespace
1530 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1531 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1532 pelmVBoxMachine->setAttribute("ovf:required", "false");
1533 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1534 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1535
1536 // create an empty machine config
1537 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(NULL);
1538
1539 writeLock.release();
1540 try
1541 {
1542 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1543 // fill the machine config
1544 vsdescThis->m->pMachine->copyMachineDataToSettings(*pConfig);
1545 // write the machine config to the vbox:Machine element
1546 pConfig->buildMachineXML(*pelmVBoxMachine,
1547 settings::MachineConfigFile::BuildMachineXML_WriteVboxVersionAttribute
1548 | settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia,
1549 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1550 pllElementsWithUuidAttributes);
1551 delete pConfig;
1552 }
1553 catch (...)
1554 {
1555 writeLock.acquire();
1556 delete pConfig;
1557 throw;
1558 }
1559 writeLock.acquire();
1560}
1561
1562/**
1563 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1564 * and therefore runs on the OVF/OVA write worker thread. This runs in two contexts:
1565 *
1566 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::writeImpl();
1567 *
1568 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
1569 * called Appliance::writeS3(), which called Appliance::writeImpl(), which then called this. In other
1570 * words, to write to the cloud, the first worker thread first starts a second worker thread to create
1571 * temporary files and then uploads them to the S3 cloud server.
1572 *
1573 * @param pTask
1574 * @return
1575 */
1576HRESULT Appliance::writeFS(TaskOVF *pTask)
1577{
1578 LogFlowFuncEnter();
1579 LogFlowFunc(("ENTER appliance %p\n", this));
1580
1581 AutoCaller autoCaller(this);
1582 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1583
1584 HRESULT rc = S_OK;
1585
1586 // Lock the media tree early to make sure nobody else tries to make changes
1587 // to the tree. Also lock the IAppliance object for writing.
1588 AutoMultiWriteLock2 multiLock(&mVirtualBox->getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1589 // Additional protect the IAppliance object, cause we leave the lock
1590 // when starting the disk export and we don't won't block other
1591 // callers on this lengthy operations.
1592 m->state = Data::ApplianceExporting;
1593
1594 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1595 rc = writeFSOVF(pTask, multiLock);
1596 else
1597 rc = writeFSOVA(pTask, multiLock);
1598
1599 // reset the state so others can call methods again
1600 m->state = Data::ApplianceIdle;
1601
1602 LogFlowFunc(("rc=%Rhrc\n", rc));
1603 LogFlowFuncLeave();
1604 return rc;
1605}
1606
1607HRESULT Appliance::writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1608{
1609 LogFlowFuncEnter();
1610
1611 HRESULT rc = S_OK;
1612
1613 PVDINTERFACEIO pSha1Callbacks = 0;
1614 PVDINTERFACEIO pRTFileCallbacks = 0;
1615 do
1616 {
1617 pSha1Callbacks = Sha1CreateInterface();
1618 if (!pSha1Callbacks)
1619 {
1620 rc = E_OUTOFMEMORY;
1621 break;
1622 }
1623 pRTFileCallbacks = RTFileCreateInterface();
1624 if (!pRTFileCallbacks)
1625 {
1626 rc = E_OUTOFMEMORY;
1627 break;
1628 }
1629
1630 SHA1STORAGE storage;
1631 RT_ZERO(storage);
1632 storage.fCreateDigest = m->fManifest;
1633 VDINTERFACE VDInterfaceIO;
1634 int vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IORTFile",
1635 VDINTERFACETYPE_IO, pRTFileCallbacks,
1636 0, &storage.pVDImageIfaces);
1637 if (RT_FAILURE(vrc))
1638 {
1639 rc = E_FAIL;
1640 break;
1641 }
1642 rc = writeFSImpl(pTask, writeLock, pSha1Callbacks, &storage);
1643 }while(0);
1644
1645 /* Cleanup */
1646 if (pSha1Callbacks)
1647 RTMemFree(pSha1Callbacks);
1648 if (pRTFileCallbacks)
1649 RTMemFree(pRTFileCallbacks);
1650
1651 LogFlowFuncLeave();
1652 return rc;
1653}
1654
1655HRESULT Appliance::writeFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1656{
1657 LogFlowFuncEnter();
1658
1659 RTTAR tar;
1660 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL);
1661 if (RT_FAILURE(vrc))
1662 return setError(VBOX_E_FILE_ERROR,
1663 tr("Could not create OVA file '%s' (%Rrc)"),
1664 pTask->locInfo.strPath.c_str(), vrc);
1665
1666 HRESULT rc = S_OK;
1667
1668 PVDINTERFACEIO pSha1Callbacks = 0;
1669 PVDINTERFACEIO pRTTarCallbacks = 0;
1670 do
1671 {
1672 pSha1Callbacks = Sha1CreateInterface();
1673 if (!pSha1Callbacks)
1674 {
1675 rc = E_OUTOFMEMORY;
1676 break;
1677 }
1678 pRTTarCallbacks = RTTarCreateInterface();
1679 if (!pRTTarCallbacks)
1680 {
1681 rc = E_OUTOFMEMORY;
1682 break;
1683 }
1684 VDINTERFACE VDInterfaceIO;
1685 SHA1STORAGE storage;
1686 RT_ZERO(storage);
1687 storage.fCreateDigest = m->fManifest;
1688 vrc = VDInterfaceAdd(&VDInterfaceIO, "Appliance::IORTTar",
1689 VDINTERFACETYPE_IO, pRTTarCallbacks,
1690 tar, &storage.pVDImageIfaces);
1691 if (RT_FAILURE(vrc))
1692 {
1693 rc = E_FAIL;
1694 break;
1695 }
1696 rc = writeFSImpl(pTask, writeLock, pSha1Callbacks, &storage);
1697 }while(0);
1698
1699 RTTarClose(tar);
1700
1701 /* Cleanup */
1702 if (pSha1Callbacks)
1703 RTMemFree(pSha1Callbacks);
1704 if (pRTTarCallbacks)
1705 RTMemFree(pRTTarCallbacks);
1706
1707 /* Delete ova file on error */
1708 if(FAILED(rc))
1709 RTFileDelete(pTask->locInfo.strPath.c_str());
1710
1711 LogFlowFuncLeave();
1712 return rc;
1713}
1714
1715HRESULT Appliance::writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pCallbacks, PSHA1STORAGE pStorage)
1716{
1717 LogFlowFuncEnter();
1718
1719 HRESULT rc = S_OK;
1720
1721 typedef pair<Utf8Str, Utf8Str> STRPAIR;
1722 list<STRPAIR> fileList;
1723 try
1724 {
1725 int vrc;
1726 // the XML stack contains two maps for disks and networks, which allows us to
1727 // a) have a list of unique disk names (to make sure the same disk name is only added once)
1728 // and b) keep a list of all networks
1729 XMLStack stack;
1730 // Scope this to free the memory as soon as this is finished
1731 {
1732 // Create a xml document
1733 xml::Document doc;
1734 // Now fully build a valid ovf document in memory
1735 buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
1736 // Create a memory buffer containing the XML. */
1737 void *pvBuf;
1738 size_t cbSize;
1739 xml::XmlMemWriter writer;
1740 writer.write(doc, &pvBuf, &cbSize);
1741 /* Extract the path */
1742 Utf8Str tmpPath = pTask->locInfo.strPath;
1743 /* Remove the extension and add ovf. */
1744 tmpPath.stripExt()
1745 .append(".ovf");
1746 /* Write the ovf file to disk. */
1747 vrc = Sha1WriteBuf(tmpPath.c_str(), pvBuf, cbSize, pCallbacks, pStorage);
1748 if (RT_FAILURE(vrc))
1749 throw setError(VBOX_E_FILE_ERROR,
1750 tr("Could not create OVF file '%s' (%Rrc)"),
1751 tmpPath.c_str(), vrc);
1752 fileList.push_back(STRPAIR(tmpPath, pStorage->strDigest));
1753 }
1754
1755 // We need a proper format description
1756 ComObjPtr<MediumFormat> format;
1757 // Scope for the AutoReadLock
1758 {
1759 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
1760 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
1761 // We are always exporting to VMDK stream optimized for now
1762 format = pSysProps->mediumFormat("VMDK");
1763 if (format.isNull())
1764 throw setError(VBOX_E_NOT_SUPPORTED,
1765 tr("Invalid medium storage format"));
1766 }
1767
1768 // Finally, write out the disks!
1769 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
1770 for (itS = stack.mapDisks.begin();
1771 itS != stack.mapDisks.end();
1772 ++itS)
1773 {
1774 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
1775
1776 // source path: where the VBox image is
1777 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
1778 Bstr bstrSrcFilePath(strSrcFilePath);
1779
1780 // Do NOT check here whether the file exists. findHardDisk will
1781 // figure that out, and filesystem-based tests are simply wrong
1782 // in the general case (think of iSCSI).
1783
1784 // clone the disk:
1785 ComObjPtr<Medium> pSourceDisk;
1786
1787 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
1788 rc = mVirtualBox->findHardDisk(NULL, bstrSrcFilePath.raw(), true, &pSourceDisk);
1789 if (FAILED(rc)) throw rc;
1790
1791 Bstr uuidSource;
1792 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1793 if (FAILED(rc)) throw rc;
1794 Guid guidSource(uuidSource);
1795
1796 // output filename
1797 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1798 // target path needs to be composed from where the output OVF is
1799 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
1800 strTargetFilePath.stripFilename()
1801 .append("/")
1802 .append(strTargetFileNameOnly);
1803
1804 // The exporting requests a lock on the media tree. So leave our lock temporary.
1805 writeLock.release();
1806 try
1807 {
1808 ComObjPtr<Progress> pProgress2;
1809 pProgress2.createObject();
1810 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetFilePath.c_str()).raw(), TRUE);
1811 if (FAILED(rc)) throw rc;
1812
1813 // advance to the next operation
1814 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"), RTPathFilename(strTargetFilePath.c_str())).raw(),
1815 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally
1816
1817 // create a flat copy of the source disk image
1818 rc = pSourceDisk->exportFile(strTargetFilePath.c_str(), format, MediumVariant_VmdkStreamOptimized, pCallbacks, pStorage, pProgress2);
1819 if (FAILED(rc)) throw rc;
1820
1821 ComPtr<IProgress> pProgress3(pProgress2);
1822 // now wait for the background disk operation to complete; this throws HRESULTs on error
1823 waitForAsyncProgress(pTask->pProgress, pProgress3);
1824 }
1825 catch (HRESULT rc3)
1826 {
1827 writeLock.acquire();
1828 // Todo: file deletion on error? If not, we can remove that whole try/catch block.
1829 throw rc3;
1830 }
1831 // Finished, lock again (so nobody mess around with the medium tree
1832 // in the meantime)
1833 writeLock.acquire();
1834 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
1835 }
1836
1837 if (m->fManifest)
1838 {
1839 // Create & write the manifest file
1840 Utf8Str strMfFilePath = manifestFileName(pTask->locInfo.strPath.c_str());
1841 Utf8Str strMfFileName = Utf8Str(strMfFilePath)
1842 .stripPath();
1843 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
1844 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally);
1845 const char** ppManifestFiles = (const char**)RTMemAlloc(sizeof(char*) * fileList.size());
1846 const char** ppManifestDigests = (const char**)RTMemAlloc(sizeof(char*) * fileList.size());
1847 size_t i = 0;
1848 list<STRPAIR>::const_iterator it1;
1849 for (it1 = fileList.begin();
1850 it1 != fileList.end();
1851 ++it1, ++i)
1852 {
1853 ppManifestFiles[i] = (*it1).first.c_str();
1854 ppManifestDigests[i] = (*it1).second.c_str();
1855 }
1856 void *pvBuf;
1857 size_t cbSize;
1858 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, ppManifestFiles, ppManifestDigests, fileList.size());
1859 RTMemFree(ppManifestFiles);
1860 RTMemFree(ppManifestDigests);
1861 if (RT_FAILURE(vrc))
1862 throw setError(VBOX_E_FILE_ERROR,
1863 tr("Could not create manifest file '%s' (%Rrc)"),
1864 strMfFileName.c_str(), vrc);
1865 /* Disable digest creation for the manifest file. */
1866 pStorage->fCreateDigest = false;
1867 /* Write the manifest file to disk. */
1868 vrc = Sha1WriteBuf(strMfFilePath.c_str(), pvBuf, cbSize, pCallbacks, pStorage);
1869 RTMemFree(pvBuf);
1870 if (RT_FAILURE(vrc))
1871 throw setError(VBOX_E_FILE_ERROR,
1872 tr("Could not create manifest file '%s' (%Rrc)"),
1873 strMfFilePath.c_str(), vrc);
1874 }
1875 }
1876 catch (iprt::Error &x) // includes all XML exceptions
1877 {
1878 rc = setError(VBOX_E_FILE_ERROR,
1879 x.what());
1880 }
1881 catch (HRESULT aRC)
1882 {
1883 rc = aRC;
1884 }
1885
1886 /* Cleanup on error */
1887 if (FAILED(rc))
1888 {
1889 list<STRPAIR>::const_iterator it1;
1890 for (it1 = fileList.begin();
1891 it1 != fileList.end();
1892 ++it1)
1893 pCallbacks->pfnDelete(pStorage, (*it1).first.c_str());
1894 }
1895
1896 LogFlowFunc(("rc=%Rhrc\n", rc));
1897 LogFlowFuncLeave();
1898
1899 return rc;
1900}
1901
1902/**
1903 * Worker code for writing out OVF to the cloud. This is called from Appliance::taskThreadWriteOVF()
1904 * in S3 mode and therefore runs on the OVF write worker thread. This then starts a second worker
1905 * thread to create temporary files (see Appliance::writeFS()).
1906 *
1907 * @param pTask
1908 * @return
1909 */
1910HRESULT Appliance::writeS3(TaskOVF *pTask)
1911{
1912 LogFlowFuncEnter();
1913 LogFlowFunc(("Appliance %p\n", this));
1914
1915 AutoCaller autoCaller(this);
1916 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1917
1918 HRESULT rc = S_OK;
1919
1920 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1921
1922 int vrc = VINF_SUCCESS;
1923 RTS3 hS3 = NIL_RTS3;
1924 char szOSTmpDir[RTPATH_MAX];
1925 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1926 /* The template for the temporary directory created below */
1927 char *pszTmpDir;
1928 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
1929 list< pair<Utf8Str, ULONG> > filesList;
1930
1931 // todo:
1932 // - usable error codes
1933 // - seems snapshot filenames are problematic {uuid}.vdi
1934 try
1935 {
1936 /* Extract the bucket */
1937 Utf8Str tmpPath = pTask->locInfo.strPath;
1938 Utf8Str bucket;
1939 parseBucket(tmpPath, bucket);
1940
1941 /* We need a temporary directory which we can put the OVF file & all
1942 * disk images in */
1943 vrc = RTDirCreateTemp(pszTmpDir);
1944 if (RT_FAILURE(vrc))
1945 throw setError(VBOX_E_FILE_ERROR,
1946 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1947
1948 /* The temporary name of the target OVF file */
1949 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1950
1951 /* Prepare the temporary writing of the OVF */
1952 ComObjPtr<Progress> progress;
1953 /* Create a temporary file based location info for the sub task */
1954 LocationInfo li;
1955 li.strPath = strTmpOvf;
1956 rc = writeImpl(pTask->enFormat, li, progress);
1957 if (FAILED(rc)) throw rc;
1958
1959 /* Unlock the appliance for the writing thread */
1960 appLock.release();
1961 /* Wait until the writing is done, but report the progress back to the
1962 caller */
1963 ComPtr<IProgress> progressInt(progress);
1964 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1965
1966 /* Again lock the appliance for the next steps */
1967 appLock.acquire();
1968
1969 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
1970 if (RT_FAILURE(vrc))
1971 throw setError(VBOX_E_FILE_ERROR,
1972 tr("Cannot find source file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
1973 /* Add the OVF file */
1974 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightForXmlOperation)); /* Use 1% of the total for the OVF file upload */
1975 /* Add the manifest file */
1976 if (m->fManifest)
1977 {
1978 Utf8Str strMfFile = manifestFileName(strTmpOvf);
1979 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightForXmlOperation)); /* Use 1% of the total for the manifest file upload */
1980 }
1981
1982 /* Now add every disks of every virtual system */
1983 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1984 for (it = m->virtualSystemDescriptions.begin();
1985 it != m->virtualSystemDescriptions.end();
1986 ++it)
1987 {
1988 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1989 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1990 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1991 for (itH = avsdeHDs.begin();
1992 itH != avsdeHDs.end();
1993 ++itH)
1994 {
1995 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
1996 /* Target path needs to be composed from where the output OVF is */
1997 Utf8Str strTargetFilePath(strTmpOvf);
1998 strTargetFilePath.stripFilename();
1999 strTargetFilePath.append("/");
2000 strTargetFilePath.append(strTargetFileNameOnly);
2001 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
2002 if (RT_FAILURE(vrc))
2003 throw setError(VBOX_E_FILE_ERROR,
2004 tr("Cannot find source file '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2005 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
2006 }
2007 }
2008 /* Next we have to upload the OVF & all disk images */
2009 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2010 if (RT_FAILURE(vrc))
2011 throw setError(VBOX_E_IPRT_ERROR,
2012 tr("Cannot create S3 service handler"));
2013 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2014
2015 /* Upload all files */
2016 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2017 {
2018 const pair<Utf8Str, ULONG> &s = (*it1);
2019 char *pszFilename = RTPathFilename(s.first.c_str());
2020 /* Advance to the next operation */
2021 pTask->pProgress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename).raw(), s.second);
2022 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
2023 if (RT_FAILURE(vrc))
2024 {
2025 if (vrc == VERR_S3_CANCELED)
2026 break;
2027 else if (vrc == VERR_S3_ACCESS_DENIED)
2028 throw setError(E_ACCESSDENIED,
2029 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);
2030 else if (vrc == VERR_S3_NOT_FOUND)
2031 throw setError(VBOX_E_FILE_ERROR,
2032 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
2033 else
2034 throw setError(VBOX_E_IPRT_ERROR,
2035 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
2036 }
2037 }
2038 }
2039 catch(HRESULT aRC)
2040 {
2041 rc = aRC;
2042 }
2043 /* Cleanup */
2044 RTS3Destroy(hS3);
2045 /* Delete all files which where temporary created */
2046 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2047 {
2048 const char *pszFilePath = (*it1).first.c_str();
2049 if (RTPathExists(pszFilePath))
2050 {
2051 vrc = RTFileDelete(pszFilePath);
2052 if (RT_FAILURE(vrc))
2053 rc = setError(VBOX_E_FILE_ERROR,
2054 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2055 }
2056 }
2057 /* Delete the temporary directory */
2058 if (RTPathExists(pszTmpDir))
2059 {
2060 vrc = RTDirRemove(pszTmpDir);
2061 if (RT_FAILURE(vrc))
2062 rc = setError(VBOX_E_FILE_ERROR,
2063 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2064 }
2065 if (pszTmpDir)
2066 RTStrFree(pszTmpDir);
2067
2068 LogFlowFunc(("rc=%Rhrc\n", rc));
2069 LogFlowFuncLeave();
2070
2071 return rc;
2072}
2073
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