VirtualBox

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

Last change on this file since 30760 was 30760, checked in by vboxsync, 15 years ago

Main: separate internal machine data structs into MachineImplPrivate.h to significantly speed up compilation and for better interface separation; remove obsolete ConsoleEvents.h file

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 79.3 KB
Line 
1/* $Id: ApplianceImplExport.cpp 30760 2010-07-09 13:12:04Z 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.215389.xyz. 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/file.h>
20#include <iprt/path.h>
21#include <iprt/dir.h>
22#include <iprt/param.h>
23#include <iprt/s3.h>
24#include <iprt/manifest.h>
25
26#include "AudioAdapterImpl.h"
27#include "VirtualBoxImpl.h"
28#include "ProgressImpl.h"
29#include "MachineImplPrivate.h"
30#include "MediumAttachmentImpl.h"
31
32#include "ApplianceImplPrivate.h"
33
34#include "AutoCaller.h"
35#include "Logging.h"
36
37#include <VBox/version.h>
38#include <VBox/com/array.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 bstrName1 = mUserData->mName;
111 // get description
112 bstrDescription = mUserData->mDescription;
113 // get guest OS
114 bstrGuestOSType = mUserData->mOSTypeId;
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 Utf8Str strOsTypeVBox(bstrGuestOSType);
131 ovf::CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str());
132 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
133 "",
134 Utf8StrFmt("%RI32", cim),
135 strOsTypeVBox);
136
137 /* VM name */
138 Utf8Str strVMName(bstrName1);
139 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
140 "",
141 strVMName,
142 strVMName);
143
144 // description
145 Utf8Str strDescription(bstrDescription);
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 MediumAttachmentsList::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, 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 ULONG64 ullSize = 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)(&ullSize);
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", ullSize));
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)(ullSize / _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, 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 return setError(VBOX_E_FILE_ERROR,
575 tr("Appliance file must have .ovf extension"));
576
577 Utf8Str strFormat(format);
578 OVFFormat ovfF;
579 if (strFormat == "ovf-0.9")
580 ovfF = OVF_0_9;
581 else if (strFormat == "ovf-1.0")
582 ovfF = OVF_1_0;
583 else
584 return setError(VBOX_E_FILE_ERROR,
585 tr("Invalid format \"%s\" specified"), strFormat.c_str());
586
587 ComObjPtr<Progress> progress;
588 HRESULT rc = S_OK;
589 try
590 {
591 /* Parse all necessary info out of the URI */
592 parseURI(strPath, m->locInfo);
593 rc = writeImpl(ovfF, m->locInfo, progress);
594 }
595 catch (HRESULT aRC)
596 {
597 rc = aRC;
598 }
599
600 if (SUCCEEDED(rc))
601 /* Return progress to the caller */
602 progress.queryInterfaceTo(aProgress);
603
604 return rc;
605}
606
607////////////////////////////////////////////////////////////////////////////////
608//
609// Appliance private methods
610//
611////////////////////////////////////////////////////////////////////////////////
612
613/**
614 * Implementation for writing out the OVF to disk. This starts a new thread which will call
615 * Appliance::taskThreadWriteOVF().
616 *
617 * This is in a separate private method because it is used from two locations:
618 *
619 * 1) from the public Appliance::Write().
620 * 2) from Appliance::writeS3(), which got called from a previous instance of Appliance::taskThreadWriteOVF().
621 *
622 * @param aFormat
623 * @param aLocInfo
624 * @param aProgress
625 * @return
626 */
627HRESULT Appliance::writeImpl(OVFFormat aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
628{
629 HRESULT rc = S_OK;
630 try
631 {
632 rc = setUpProgress(aProgress,
633 BstrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
634 (aLocInfo.storageType == VFSType_File) ? WriteFile : WriteS3);
635
636 /* Initialize our worker task */
637 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress));
638 /* The OVF version to write */
639 task->enFormat = aFormat;
640
641 rc = task->startThread();
642 if (FAILED(rc)) throw rc;
643
644 /* Don't destruct on success */
645 task.release();
646 }
647 catch (HRESULT aRC)
648 {
649 rc = aRC;
650 }
651
652 return rc;
653}
654
655/**
656 * Called from Appliance::writeFS() for each virtual system (machine) that needs XML written out.
657 *
658 * @param elmToAddVirtualSystemsTo XML element to append elements to.
659 * @param vsdescThis The IVirtualSystemDescription instance for which to write XML.
660 * @param enFormat OVF format (0.9 or 1.0).
661 * @param stack Structure for temporary private data shared with caller.
662 */
663void Appliance::buildXMLForOneVirtualSystem(xml::ElementNode &elmToAddVirtualSystemsTo,
664 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
665 ComObjPtr<VirtualSystemDescription> &vsdescThis,
666 OVFFormat enFormat,
667 XMLStack &stack)
668{
669 LogFlowFunc(("ENTER appliance %p\n", this));
670
671 xml::ElementNode *pelmVirtualSystem;
672 if (enFormat == OVF_0_9)
673 {
674 // <Section xsi:type="ovf:NetworkSection_Type">
675 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
676 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
677 }
678 else
679 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
680
681 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
682
683 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
684 if (llName.size() != 1)
685 throw setError(VBOX_E_NOT_SUPPORTED,
686 tr("Missing VM name"));
687 Utf8Str &strVMName = llName.front()->strVboxCurrent;
688 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
689
690 // product info
691 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
692 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
693 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
694 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
695 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
696 bool fProduct = llProduct.size() && !llProduct.front()->strVboxCurrent.isEmpty();
697 bool fProductUrl = llProductUrl.size() && !llProductUrl.front()->strVboxCurrent.isEmpty();
698 bool fVendor = llVendor.size() && !llVendor.front()->strVboxCurrent.isEmpty();
699 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.front()->strVboxCurrent.isEmpty();
700 bool fVersion = llVersion.size() && !llVersion.front()->strVboxCurrent.isEmpty();
701 if (fProduct ||
702 fProductUrl ||
703 fVersion ||
704 fVendorUrl ||
705 fVersion)
706 {
707 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
708 <Info>Meta-information about the installed software</Info>
709 <Product>VAtest</Product>
710 <Vendor>SUN Microsystems</Vendor>
711 <Version>10.0</Version>
712 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
713 <VendorUrl>http://www.sun.com</VendorUrl>
714 </Section> */
715 xml::ElementNode *pelmAnnotationSection;
716 if (enFormat == OVF_0_9)
717 {
718 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
719 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
720 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
721 }
722 else
723 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
724
725 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
726 if (fProduct)
727 pelmAnnotationSection->createChild("Product")->addContent(llProduct.front()->strVboxCurrent);
728 if (fVendor)
729 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.front()->strVboxCurrent);
730 if (fVersion)
731 pelmAnnotationSection->createChild("Version")->addContent(llVersion.front()->strVboxCurrent);
732 if (fProductUrl)
733 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.front()->strVboxCurrent);
734 if (fVendorUrl)
735 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.front()->strVboxCurrent);
736 }
737
738 // description
739 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
740 if (llDescription.size() &&
741 !llDescription.front()->strVboxCurrent.isEmpty())
742 {
743 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
744 <Info>A human-readable annotation</Info>
745 <Annotation>Plan 9</Annotation>
746 </Section> */
747 xml::ElementNode *pelmAnnotationSection;
748 if (enFormat == OVF_0_9)
749 {
750 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
751 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
752 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
753 }
754 else
755 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
756
757 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
758 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.front()->strVboxCurrent);
759 }
760
761 // license
762 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
763 if (llLicense.size() &&
764 !llLicense.front()->strVboxCurrent.isEmpty())
765 {
766 /* <EulaSection>
767 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
768 <License ovf:msgid="1">License terms can go in here.</License>
769 </EulaSection> */
770 xml::ElementNode *pelmEulaSection;
771 if (enFormat == OVF_0_9)
772 {
773 pelmEulaSection = pelmVirtualSystem->createChild("Section");
774 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
775 }
776 else
777 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
778
779 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
780 pelmEulaSection->createChild("License")->addContent(llLicense.front()->strVboxCurrent);
781 }
782
783 // operating system
784 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
785 if (llOS.size() != 1)
786 throw setError(VBOX_E_NOT_SUPPORTED,
787 tr("Missing OS type"));
788 /* <OperatingSystemSection ovf:id="82">
789 <Info>Guest Operating System</Info>
790 <Description>Linux 2.6.x</Description>
791 </OperatingSystemSection> */
792 xml::ElementNode *pelmOperatingSystemSection;
793 if (enFormat == OVF_0_9)
794 {
795 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
796 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
797 }
798 else
799 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
800
801 pelmOperatingSystemSection->setAttribute("ovf:id", llOS.front()->strOvf);
802 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
803 Utf8Str strOSDesc;
804 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)llOS.front()->strOvf.toInt32(), "");
805 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
806
807 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
808 xml::ElementNode *pelmVirtualHardwareSection;
809 if (enFormat == OVF_0_9)
810 {
811 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
812 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
813 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
814 }
815 else
816 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
817
818 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
819
820 /* <System>
821 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
822 <vssd:ElementName>vmware</vssd:ElementName>
823 <vssd:InstanceID>1</vssd:InstanceID>
824 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
825 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
826 </System> */
827 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
828
829 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
830
831 // <vssd:InstanceId>0</vssd:InstanceId>
832 if (enFormat == OVF_0_9)
833 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
834 else // capitalization changed...
835 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
836
837 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
838 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
839 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
840 const char *pcszHardware = "virtualbox-2.2";
841 if (enFormat == OVF_0_9)
842 // pretend to be vmware compatible then
843 pcszHardware = "vmx-6";
844 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
845
846 // loop thru all description entries twice; once to write out all
847 // devices _except_ disk images, and a second time to assign the
848 // disk images; this is because disk images need to reference
849 // IDE controllers, and we can't know their instance IDs without
850 // assigning them first
851
852 uint32_t idIDEPrimaryController = 0;
853 int32_t lIDEPrimaryControllerIndex = 0;
854 uint32_t idIDESecondaryController = 0;
855 int32_t lIDESecondaryControllerIndex = 0;
856 uint32_t idSATAController = 0;
857 int32_t lSATAControllerIndex = 0;
858 uint32_t idSCSIController = 0;
859 int32_t lSCSIControllerIndex = 0;
860
861 uint32_t ulInstanceID = 1;
862
863 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
864 {
865 int32_t lIndexThis = 0;
866 list<VirtualSystemDescriptionEntry>::const_iterator itD;
867 for (itD = vsdescThis->m->llDescriptions.begin();
868 itD != vsdescThis->m->llDescriptions.end();
869 ++itD, ++lIndexThis)
870 {
871 const VirtualSystemDescriptionEntry &desc = *itD;
872
873 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVbox=%s, strExtraConfig=%s\n",
874 uLoop,
875 desc.ulIndex,
876 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
877 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
878 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
879 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
880 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
881 : Utf8StrFmt("%d", desc.type).c_str()),
882 desc.strRef.c_str(),
883 desc.strOvf.c_str(),
884 desc.strVboxCurrent.c_str(),
885 desc.strExtraConfigCurrent.c_str()));
886
887 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
888 Utf8Str strResourceSubType;
889
890 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
891 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
892
893 uint32_t ulParent = 0;
894
895 int32_t lVirtualQuantity = -1;
896 Utf8Str strAllocationUnits;
897
898 int32_t lAddress = -1;
899 int32_t lBusNumber = -1;
900 int32_t lAddressOnParent = -1;
901
902 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
903 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
904 Utf8Str strHostResource;
905
906 uint64_t uTemp;
907
908 switch (desc.type)
909 {
910 case VirtualSystemDescriptionType_CPU:
911 /* <Item>
912 <rasd:Caption>1 virtual CPU</rasd:Caption>
913 <rasd:Description>Number of virtual CPUs</rasd:Description>
914 <rasd:ElementName>virtual CPU</rasd:ElementName>
915 <rasd:InstanceID>1</rasd:InstanceID>
916 <rasd:ResourceType>3</rasd:ResourceType>
917 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
918 </Item> */
919 if (uLoop == 1)
920 {
921 strDescription = "Number of virtual CPUs";
922 type = ovf::ResourceType_Processor; // 3
923 desc.strVboxCurrent.toInt(uTemp);
924 lVirtualQuantity = (int32_t)uTemp;
925 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
926 }
927 break;
928
929 case VirtualSystemDescriptionType_Memory:
930 /* <Item>
931 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
932 <rasd:Caption>256 MB of memory</rasd:Caption>
933 <rasd:Description>Memory Size</rasd:Description>
934 <rasd:ElementName>Memory</rasd:ElementName>
935 <rasd:InstanceID>2</rasd:InstanceID>
936 <rasd:ResourceType>4</rasd:ResourceType>
937 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
938 </Item> */
939 if (uLoop == 1)
940 {
941 strDescription = "Memory Size";
942 type = ovf::ResourceType_Memory; // 4
943 desc.strVboxCurrent.toInt(uTemp);
944 lVirtualQuantity = (int32_t)(uTemp / _1M);
945 strAllocationUnits = "MegaBytes";
946 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
947 }
948 break;
949
950 case VirtualSystemDescriptionType_HardDiskControllerIDE:
951 /* <Item>
952 <rasd:Caption>ideController1</rasd:Caption>
953 <rasd:Description>IDE Controller</rasd:Description>
954 <rasd:InstanceId>5</rasd:InstanceId>
955 <rasd:ResourceType>5</rasd:ResourceType>
956 <rasd:Address>1</rasd:Address>
957 <rasd:BusNumber>1</rasd:BusNumber>
958 </Item> */
959 if (uLoop == 1)
960 {
961 strDescription = "IDE Controller";
962 type = ovf::ResourceType_IDEController; // 5
963 strResourceSubType = desc.strVboxCurrent;
964
965 if (!lIDEPrimaryControllerIndex)
966 {
967 // first IDE controller:
968 strCaption = "ideController0";
969 lAddress = 0;
970 lBusNumber = 0;
971 // remember this ID
972 idIDEPrimaryController = ulInstanceID;
973 lIDEPrimaryControllerIndex = lIndexThis;
974 }
975 else
976 {
977 // second IDE controller:
978 strCaption = "ideController1";
979 lAddress = 1;
980 lBusNumber = 1;
981 // remember this ID
982 idIDESecondaryController = ulInstanceID;
983 lIDESecondaryControllerIndex = lIndexThis;
984 }
985 }
986 break;
987
988 case VirtualSystemDescriptionType_HardDiskControllerSATA:
989 /* <Item>
990 <rasd:Caption>sataController0</rasd:Caption>
991 <rasd:Description>SATA Controller</rasd:Description>
992 <rasd:InstanceId>4</rasd:InstanceId>
993 <rasd:ResourceType>20</rasd:ResourceType>
994 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
995 <rasd:Address>0</rasd:Address>
996 <rasd:BusNumber>0</rasd:BusNumber>
997 </Item>
998 */
999 if (uLoop == 1)
1000 {
1001 strDescription = "SATA Controller";
1002 strCaption = "sataController0";
1003 type = ovf::ResourceType_OtherStorageDevice; // 20
1004 // it seems that OVFTool always writes these two, and since we can only
1005 // have one SATA controller, we'll use this as well
1006 lAddress = 0;
1007 lBusNumber = 0;
1008
1009 if ( desc.strVboxCurrent.isEmpty() // AHCI is the default in VirtualBox
1010 || (!desc.strVboxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1011 )
1012 strResourceSubType = "AHCI";
1013 else
1014 throw setError(VBOX_E_NOT_SUPPORTED,
1015 tr("Invalid config string \"%s\" in SATA controller"), desc.strVboxCurrent.c_str());
1016
1017 // remember this ID
1018 idSATAController = ulInstanceID;
1019 lSATAControllerIndex = lIndexThis;
1020 }
1021 break;
1022
1023 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1024 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1025 /* <Item>
1026 <rasd:Caption>scsiController0</rasd:Caption>
1027 <rasd:Description>SCSI Controller</rasd:Description>
1028 <rasd:InstanceId>4</rasd:InstanceId>
1029 <rasd:ResourceType>6</rasd:ResourceType>
1030 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1031 <rasd:Address>0</rasd:Address>
1032 <rasd:BusNumber>0</rasd:BusNumber>
1033 </Item>
1034 */
1035 if (uLoop == 1)
1036 {
1037 strDescription = "SCSI Controller";
1038 strCaption = "scsiController0";
1039 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1040 // it seems that OVFTool always writes these two, and since we can only
1041 // have one SATA controller, we'll use this as well
1042 lAddress = 0;
1043 lBusNumber = 0;
1044
1045 if ( desc.strVboxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1046 || (!desc.strVboxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1047 )
1048 strResourceSubType = "lsilogic";
1049 else if (!desc.strVboxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1050 strResourceSubType = "buslogic";
1051 else if (!desc.strVboxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1052 strResourceSubType = "lsilogicsas";
1053 else
1054 throw setError(VBOX_E_NOT_SUPPORTED,
1055 tr("Invalid config string \"%s\" in SCSI/SAS controller"), desc.strVboxCurrent.c_str());
1056
1057 // remember this ID
1058 idSCSIController = ulInstanceID;
1059 lSCSIControllerIndex = lIndexThis;
1060 }
1061 break;
1062
1063 case VirtualSystemDescriptionType_HardDiskImage:
1064 /* <Item>
1065 <rasd:Caption>disk1</rasd:Caption>
1066 <rasd:InstanceId>8</rasd:InstanceId>
1067 <rasd:ResourceType>17</rasd:ResourceType>
1068 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1069 <rasd:Parent>4</rasd:Parent>
1070 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1071 </Item> */
1072 if (uLoop == 2)
1073 {
1074 uint32_t cDisks = stack.mapDisks.size();
1075 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1076
1077 strDescription = "Disk Image";
1078 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1079 type = ovf::ResourceType_HardDisk; // 17
1080
1081 // the following references the "<Disks>" XML block
1082 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1083
1084 // controller=<index>;channel=<c>
1085 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1086 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1087 int32_t lControllerIndex = -1;
1088 if (pos1 != Utf8Str::npos)
1089 {
1090 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1091 if (lControllerIndex == lIDEPrimaryControllerIndex)
1092 ulParent = idIDEPrimaryController;
1093 else if (lControllerIndex == lIDESecondaryControllerIndex)
1094 ulParent = idIDESecondaryController;
1095 else if (lControllerIndex == lSCSIControllerIndex)
1096 ulParent = idSCSIController;
1097 else if (lControllerIndex == lSATAControllerIndex)
1098 ulParent = idSATAController;
1099 }
1100 if (pos2 != Utf8Str::npos)
1101 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1102
1103 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1104 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1105
1106 if ( !ulParent
1107 || lAddressOnParent == -1
1108 )
1109 throw setError(VBOX_E_NOT_SUPPORTED,
1110 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfigCurrent.c_str());
1111
1112 stack.mapDisks[strDiskID] = &desc;
1113 }
1114 break;
1115
1116 case VirtualSystemDescriptionType_Floppy:
1117 if (uLoop == 1)
1118 {
1119 strDescription = "Floppy Drive";
1120 strCaption = "floppy0"; // this is what OVFTool writes
1121 type = ovf::ResourceType_FloppyDrive; // 14
1122 lAutomaticAllocation = 0;
1123 lAddressOnParent = 0; // this is what OVFTool writes
1124 }
1125 break;
1126
1127 case VirtualSystemDescriptionType_CDROM:
1128 if (uLoop == 2)
1129 {
1130 // we can't have a CD without an IDE controller
1131 if (!idIDESecondaryController)
1132 throw setError(VBOX_E_NOT_SUPPORTED,
1133 tr("Can't have CD-ROM without secondary IDE controller"));
1134
1135 strDescription = "CD-ROM Drive";
1136 strCaption = "cdrom1"; // this is what OVFTool writes
1137 type = ovf::ResourceType_CDDrive; // 15
1138 lAutomaticAllocation = 1;
1139 ulParent = idIDESecondaryController;
1140 lAddressOnParent = 0; // this is what OVFTool writes
1141 }
1142 break;
1143
1144 case VirtualSystemDescriptionType_NetworkAdapter:
1145 /* <Item>
1146 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1147 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1148 <rasd:Connection>VM Network</rasd:Connection>
1149 <rasd:ElementName>VM network</rasd:ElementName>
1150 <rasd:InstanceID>3</rasd:InstanceID>
1151 <rasd:ResourceType>10</rasd:ResourceType>
1152 </Item> */
1153 if (uLoop == 1)
1154 {
1155 lAutomaticAllocation = 1;
1156 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1157 type = ovf::ResourceType_EthernetAdapter; // 10
1158 /* Set the hardware type to something useful.
1159 * To be compatible with vmware & others we set
1160 * PCNet32 for our PCNet types & E1000 for the
1161 * E1000 cards. */
1162 switch (desc.strVboxCurrent.toInt32())
1163 {
1164 case NetworkAdapterType_Am79C970A:
1165 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1166#ifdef VBOX_WITH_E1000
1167 case NetworkAdapterType_I82540EM:
1168 case NetworkAdapterType_I82545EM:
1169 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1170#endif /* VBOX_WITH_E1000 */
1171 }
1172 strConnection = desc.strOvf;
1173
1174 stack.mapNetworks[desc.strOvf] = true;
1175 }
1176 break;
1177
1178 case VirtualSystemDescriptionType_USBController:
1179 /* <Item ovf:required="false">
1180 <rasd:Caption>usb</rasd:Caption>
1181 <rasd:Description>USB Controller</rasd:Description>
1182 <rasd:InstanceId>3</rasd:InstanceId>
1183 <rasd:ResourceType>23</rasd:ResourceType>
1184 <rasd:Address>0</rasd:Address>
1185 <rasd:BusNumber>0</rasd:BusNumber>
1186 </Item> */
1187 if (uLoop == 1)
1188 {
1189 strDescription = "USB Controller";
1190 strCaption = "usb";
1191 type = ovf::ResourceType_USBController; // 23
1192 lAddress = 0; // this is what OVFTool writes
1193 lBusNumber = 0; // this is what OVFTool writes
1194 }
1195 break;
1196
1197 case VirtualSystemDescriptionType_SoundCard:
1198 /* <Item ovf:required="false">
1199 <rasd:Caption>sound</rasd:Caption>
1200 <rasd:Description>Sound Card</rasd:Description>
1201 <rasd:InstanceId>10</rasd:InstanceId>
1202 <rasd:ResourceType>35</rasd:ResourceType>
1203 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1204 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1205 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1206 </Item> */
1207 if (uLoop == 1)
1208 {
1209 strDescription = "Sound Card";
1210 strCaption = "sound";
1211 type = ovf::ResourceType_SoundCard; // 35
1212 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1213 lAutomaticAllocation = 0;
1214 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1215 }
1216 break;
1217 }
1218
1219 if (type)
1220 {
1221 xml::ElementNode *pItem;
1222
1223 pItem = pelmVirtualHardwareSection->createChild("Item");
1224
1225 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1226 // the elements from the rasd: namespace must be sorted by letter, and VMware
1227 // actually requires this as well (see public bug #6612)
1228
1229 if (lAddress != -1)
1230 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1231
1232 if (lAddressOnParent != -1)
1233 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1234
1235 if (!strAllocationUnits.isEmpty())
1236 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1237
1238 if (lAutomaticAllocation != -1)
1239 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1240
1241 if (lBusNumber != -1)
1242 if (enFormat == OVF_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool compatibility
1243 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1244
1245 if (!strCaption.isEmpty())
1246 pItem->createChild("rasd:Caption")->addContent(strCaption);
1247
1248 if (!strConnection.isEmpty())
1249 pItem->createChild("rasd:Connection")->addContent(strConnection);
1250
1251 if (!strDescription.isEmpty())
1252 pItem->createChild("rasd:Description")->addContent(strDescription);
1253
1254 if (!strCaption.isEmpty())
1255 if (enFormat == OVF_1_0)
1256 pItem->createChild("rasd:ElementName")->addContent(strCaption);
1257
1258 if (!strHostResource.isEmpty())
1259 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1260
1261 // <rasd:InstanceID>1</rasd:InstanceID>
1262 xml::ElementNode *pelmInstanceID;
1263 if (enFormat == OVF_0_9)
1264 pelmInstanceID = pItem->createChild("rasd:InstanceId");
1265 else
1266 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1267 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
1268
1269 if (ulParent)
1270 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1271
1272 if (!strResourceSubType.isEmpty())
1273 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1274
1275 // <rasd:ResourceType>3</rasd:ResourceType>
1276 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1277
1278 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1279 if (lVirtualQuantity != -1)
1280 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1281 }
1282 }
1283 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1284
1285 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1286 // under the vbox: namespace
1287 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1288 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1289 pelmVBoxMachine->setAttribute("ovf:required", "false");
1290 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1291 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1292
1293 // create an empty machine config
1294 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(NULL);
1295
1296 try
1297 {
1298 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1299 // fill the machine config
1300 vsdescThis->m->pMachine->copyMachineDataToSettings(*pConfig);
1301 // write the machine config to the vbox:Machine element
1302 pConfig->buildMachineXML(*pelmVBoxMachine,
1303 settings::MachineConfigFile::BuildMachineXML_WriteVboxVersionAttribute
1304 | settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia,
1305 // but not BuildMachineXML_IncludeSnapshots
1306 pllElementsWithUuidAttributes);
1307 delete pConfig;
1308 }
1309 catch (...)
1310 {
1311 delete pConfig;
1312 throw;
1313 }
1314}
1315
1316/**
1317 * Actual worker code for writing out OVF to disk. This is called from Appliance::taskThreadWriteOVF()
1318 * and therefore runs on the OVF write worker thread. This runs in two contexts:
1319 *
1320 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::writeImpl();
1321 *
1322 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::writeImpl(), which
1323 * called Appliance::writeS3(), which called Appliance::writeImpl(), which then called this. In other
1324 * words, to write to the cloud, the first worker thread first starts a second worker thread to create
1325 * temporary files and then uploads them to the S3 cloud server.
1326 *
1327 * @param pTask
1328 * @return
1329 */
1330HRESULT Appliance::writeFS(const LocationInfo &locInfo, const OVFFormat enFormat, ComObjPtr<Progress> &pProgress)
1331{
1332 LogFlowFunc(("ENTER appliance %p\n", this));
1333
1334 AutoCaller autoCaller(this);
1335 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1336
1337 HRESULT rc = S_OK;
1338
1339 try
1340 {
1341 AutoMultiWriteLock2 multiLock(&mVirtualBox->getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1342
1343 xml::Document doc;
1344 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
1345
1346 pelmRoot->setAttribute("ovf:version", (enFormat == OVF_1_0) ? "1.0" : "0.9");
1347 pelmRoot->setAttribute("xml:lang", "en-US");
1348
1349 Utf8Str strNamespace = (enFormat == OVF_0_9)
1350 ? "http://www.vmware.com/schema/ovf/1/envelope" // 0.9
1351 : "http://schemas.dmtf.org/ovf/envelope/1"; // 1.0
1352 pelmRoot->setAttribute("xmlns", strNamespace);
1353 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
1354
1355// pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
1356 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
1357 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
1358 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
1359 pelmRoot->setAttribute("xmlns:vbox", "http://www.215389.xyz/ovf/machine");
1360// pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
1361
1362 // <Envelope>/<References>
1363 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
1364
1365 /* <Envelope>/<DiskSection>:
1366 <DiskSection>
1367 <Info>List of the virtual disks used in the package</Info>
1368 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
1369 </DiskSection> */
1370 xml::ElementNode *pelmDiskSection;
1371 if (enFormat == OVF_0_9)
1372 {
1373 // <Section xsi:type="ovf:DiskSection_Type">
1374 pelmDiskSection = pelmRoot->createChild("Section");
1375 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
1376 }
1377 else
1378 pelmDiskSection = pelmRoot->createChild("DiskSection");
1379
1380 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
1381 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
1382
1383 // the XML stack contains two maps for disks and networks, which allows us to
1384 // a) have a list of unique disk names (to make sure the same disk name is only added once)
1385 // and b) keep a list of all networks
1386 XMLStack stack;
1387
1388 /* <Envelope>/<NetworkSection>:
1389 <NetworkSection>
1390 <Info>Logical networks used in the package</Info>
1391 <Network ovf:name="VM Network">
1392 <Description>The network that the LAMP Service will be available on</Description>
1393 </Network>
1394 </NetworkSection> */
1395 xml::ElementNode *pelmNetworkSection;
1396 if (enFormat == OVF_0_9)
1397 {
1398 // <Section xsi:type="ovf:NetworkSection_Type">
1399 pelmNetworkSection = pelmRoot->createChild("Section");
1400 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
1401 }
1402 else
1403 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
1404
1405 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
1406 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
1407
1408 // and here come the virtual systems:
1409
1410 // This can take a very long time so leave the locks; in particular, we have the media tree
1411 // lock which Medium::CloneTo() will request, and that would deadlock. Instead, protect
1412 // the appliance by resetting its state so we can safely leave the lock
1413 m->state = Data::ApplianceExporting;
1414 multiLock.release();
1415
1416 // write a collection if we have more than one virtual system _and_ we're
1417 // writing OVF 1.0; otherwise fail since ovftool can't import more than
1418 // one machine, it seems
1419 xml::ElementNode *pelmToAddVirtualSystemsTo;
1420 if (m->virtualSystemDescriptions.size() > 1)
1421 {
1422 if (enFormat == OVF_0_9)
1423 throw setError(VBOX_E_FILE_ERROR,
1424 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
1425
1426 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
1427 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
1428 }
1429 else
1430 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
1431
1432 // this list receives pointers to the XML elements in the machine XML which
1433 // might have UUIDs that need fixing after we know the UUIDs of the exported images
1434 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
1435
1436 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1437 /* Iterate throughs all virtual systems of that appliance */
1438 for (it = m->virtualSystemDescriptions.begin();
1439 it != m->virtualSystemDescriptions.end();
1440 ++it)
1441 {
1442 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
1443 buildXMLForOneVirtualSystem(*pelmToAddVirtualSystemsTo,
1444 &llElementsWithUuidAttributes,
1445 vsdescThis,
1446 enFormat,
1447 stack); // disks and networks stack
1448 }
1449
1450 // now, fill in the network section we set up empty above according
1451 // to the networks we found with the hardware items
1452 map<Utf8Str, bool>::const_iterator itN;
1453 for (itN = stack.mapNetworks.begin();
1454 itN != stack.mapNetworks.end();
1455 ++itN)
1456 {
1457 const Utf8Str &strNetwork = itN->first;
1458 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
1459 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
1460 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
1461 }
1462
1463 // Finally, write out the disks!
1464
1465 list<Utf8Str> diskList;
1466 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
1467 uint32_t ulFile = 1;
1468 for (itS = stack.mapDisks.begin();
1469 itS != stack.mapDisks.end();
1470 ++itS)
1471 {
1472 const Utf8Str &strDiskID = itS->first;
1473 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
1474
1475 // source path: where the VBox image is
1476 const Utf8Str &strSrcFilePath = pDiskEntry->strVboxCurrent;
1477 Bstr bstrSrcFilePath(strSrcFilePath);
1478 if (!RTPathExists(strSrcFilePath.c_str()))
1479 /* This isn't allowed */
1480 throw setError(VBOX_E_FILE_ERROR,
1481 tr("Source virtual disk image file '%s' doesn't exist"),
1482 strSrcFilePath.c_str());
1483
1484 // clone the disk:
1485 ComPtr<IMedium> pSourceDisk;
1486 ComPtr<IMedium> pTargetDisk;
1487 ComPtr<IProgress> pProgress2;
1488
1489 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
1490 rc = mVirtualBox->FindHardDisk(bstrSrcFilePath, pSourceDisk.asOutParam());
1491 if (FAILED(rc)) throw rc;
1492
1493 Bstr uuidSource;
1494 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1495 if (FAILED(rc)) throw rc;
1496 Guid guidSource(uuidSource);
1497
1498 // output filename
1499 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1500 // target path needs to be composed from where the output OVF is
1501 Utf8Str strTargetFilePath(locInfo.strPath);
1502 strTargetFilePath.stripFilename();
1503 strTargetFilePath.append("/");
1504 strTargetFilePath.append(strTargetFileNameOnly);
1505
1506 // We are always exporting to VMDK stream optimized for now
1507 Bstr bstrSrcFormat = L"VMDK";
1508
1509 // create a new hard disk interface for the destination disk image
1510 Log(("Creating target disk \"%s\"\n", strTargetFilePath.raw()));
1511 rc = mVirtualBox->CreateHardDisk(bstrSrcFormat, Bstr(strTargetFilePath), pTargetDisk.asOutParam());
1512 if (FAILED(rc)) throw rc;
1513
1514 // the target disk is now registered and needs to be removed again,
1515 // both after successful cloning or if anything goes bad!
1516 try
1517 {
1518 // create a flat copy of the source disk image
1519 rc = pSourceDisk->CloneTo(pTargetDisk, MediumVariant_VmdkStreamOptimized, NULL, pProgress2.asOutParam());
1520 if (FAILED(rc)) throw rc;
1521
1522 // advance to the next operation
1523 pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"), strTargetFilePath.c_str()),
1524 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally);
1525
1526 // now wait for the background disk operation to complete; this throws HRESULTs on error
1527 waitForAsyncProgress(pProgress, pProgress2);
1528 }
1529 catch (HRESULT rc3)
1530 {
1531 // upon error after registering, close the disk or
1532 // it'll stick in the registry forever
1533 pTargetDisk->Close();
1534 throw rc3;
1535 }
1536 diskList.push_back(strTargetFilePath);
1537
1538 // we need the following for the XML
1539 ULONG64 cbFile = 0; // actual file size
1540 rc = pTargetDisk->COMGETTER(Size)(&cbFile);
1541 if (FAILED(rc)) throw rc;
1542
1543 ULONG64 cbCapacity = 0; // size reported to guest
1544 rc = pTargetDisk->COMGETTER(LogicalSize)(&cbCapacity);
1545 if (FAILED(rc)) throw rc;
1546 // capacity is reported in megabytes, so...
1547 cbCapacity *= _1M;
1548
1549 Bstr uuidTarget;
1550 rc = pTargetDisk->COMGETTER(Id)(uuidTarget.asOutParam());
1551 if (FAILED(rc)) throw rc;
1552 Guid guidTarget(uuidTarget);
1553
1554 // upon success, close the disk as well
1555 rc = pTargetDisk->Close();
1556 if (FAILED(rc)) throw rc;
1557
1558 // now handle the XML for the disk:
1559 Utf8StrFmt strFileRef("file%RI32", ulFile++);
1560 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
1561 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
1562 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
1563 pelmFile->setAttribute("ovf:id", strFileRef);
1564 pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
1565
1566 // add disk to XML Disks section
1567 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
1568 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
1569 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
1570 pelmDisk->setAttribute("ovf:diskId", strDiskID);
1571 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
1572 pelmDisk->setAttribute("ovf:format",
1573 (enFormat == OVF_0_9)
1574 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftool chokes
1575 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
1576 // correct string as communicated to us by VMware (public bug #6612)
1577 );
1578
1579 // add the UUID of the newly created target image to the OVF disk element, but in the
1580 // vbox: namespace since it's not part of the standard
1581 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
1582
1583 // now, we might have other XML elements from vbox:Machine pointing to this image,
1584 // but those would refer to the UUID of the _source_ image (which we created the
1585 // export image from); those UUIDs need to be fixed to the export image
1586 for (std::list<xml::ElementNode*>::iterator eit = llElementsWithUuidAttributes.begin();
1587 eit != llElementsWithUuidAttributes.end();
1588 ++eit)
1589 {
1590 xml::ElementNode *pelmImage = *eit;
1591 // overwrite existing uuid attribute
1592 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
1593 }
1594 }
1595
1596 // now go write the XML
1597 xml::XmlFileWriter writer(doc);
1598 writer.write(locInfo.strPath.c_str(), false /*fSafe*/);
1599
1600 // Create & write the manifest file
1601 Utf8Str strMfFile = manifestFileName(locInfo.strPath.c_str());
1602 const char *pcszManifestFileOnly = RTPathFilename(strMfFile.c_str());
1603 pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), pcszManifestFileOnly),
1604 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally);
1605
1606 const char** ppManifestFiles = (const char**)RTMemAlloc(sizeof(char*)*diskList.size() + 1);
1607 ppManifestFiles[0] = locInfo.strPath.c_str();
1608 list<Utf8Str>::const_iterator it1;
1609 size_t i = 1;
1610 for (it1 = diskList.begin();
1611 it1 != diskList.end();
1612 ++it1, ++i)
1613 ppManifestFiles[i] = (*it1).c_str();
1614 int vrc = RTManifestWriteFiles(strMfFile.c_str(), ppManifestFiles, diskList.size()+1, NULL, NULL);
1615 RTMemFree(ppManifestFiles);
1616 if (RT_FAILURE(vrc))
1617 throw setError(VBOX_E_FILE_ERROR,
1618 tr("Could not create manifest file '%s' (%Rrc)"),
1619 pcszManifestFileOnly, vrc);
1620 }
1621 catch (iprt::Error &x) // includes all XML exceptions
1622 {
1623 rc = setError(VBOX_E_FILE_ERROR,
1624 x.what());
1625 }
1626 catch (HRESULT aRC)
1627 {
1628 rc = aRC;
1629 }
1630
1631 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1632 // reset the state so others can call methods again
1633 m->state = Data::ApplianceIdle;
1634
1635 LogFlowFunc(("rc=%Rhrc\n", rc));
1636 LogFlowFuncLeave();
1637
1638 return rc;
1639}
1640
1641/**
1642 * Worker code for writing out OVF to the cloud. This is called from Appliance::taskThreadWriteOVF()
1643 * in S3 mode and therefore runs on the OVF write worker thread. This then starts a second worker
1644 * thread to create temporary files (see Appliance::writeFS()).
1645 *
1646 * @param pTask
1647 * @return
1648 */
1649HRESULT Appliance::writeS3(TaskOVF *pTask)
1650{
1651 LogFlowFuncEnter();
1652 LogFlowFunc(("Appliance %p\n", this));
1653
1654 AutoCaller autoCaller(this);
1655 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1656
1657 HRESULT rc = S_OK;
1658
1659 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1660
1661 int vrc = VINF_SUCCESS;
1662 RTS3 hS3 = NIL_RTS3;
1663 char szOSTmpDir[RTPATH_MAX];
1664 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1665 /* The template for the temporary directory created below */
1666 char *pszTmpDir;
1667 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
1668 list< pair<Utf8Str, ULONG> > filesList;
1669
1670 // todo:
1671 // - usable error codes
1672 // - seems snapshot filenames are problematic {uuid}.vdi
1673 try
1674 {
1675 /* Extract the bucket */
1676 Utf8Str tmpPath = pTask->locInfo.strPath;
1677 Utf8Str bucket;
1678 parseBucket(tmpPath, bucket);
1679
1680 /* We need a temporary directory which we can put the OVF file & all
1681 * disk images in */
1682 vrc = RTDirCreateTemp(pszTmpDir);
1683 if (RT_FAILURE(vrc))
1684 throw setError(VBOX_E_FILE_ERROR,
1685 tr("Cannot create temporary directory '%s'"), pszTmpDir);
1686
1687 /* The temporary name of the target OVF file */
1688 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1689
1690 /* Prepare the temporary writing of the OVF */
1691 ComObjPtr<Progress> progress;
1692 /* Create a temporary file based location info for the sub task */
1693 LocationInfo li;
1694 li.strPath = strTmpOvf;
1695 rc = writeImpl(pTask->enFormat, li, progress);
1696 if (FAILED(rc)) throw rc;
1697
1698 /* Unlock the appliance for the writing thread */
1699 appLock.release();
1700 /* Wait until the writing is done, but report the progress back to the
1701 caller */
1702 ComPtr<IProgress> progressInt(progress);
1703 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1704
1705 /* Again lock the appliance for the next steps */
1706 appLock.acquire();
1707
1708 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
1709 if (RT_FAILURE(vrc))
1710 throw setError(VBOX_E_FILE_ERROR,
1711 tr("Cannot find source file '%s'"), strTmpOvf.c_str());
1712 /* Add the OVF file */
1713 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightForXmlOperation)); /* Use 1% of the total for the OVF file upload */
1714 Utf8Str strMfFile = manifestFileName(strTmpOvf);
1715 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightForXmlOperation)); /* Use 1% of the total for the manifest file upload */
1716
1717 /* Now add every disks of every virtual system */
1718 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1719 for (it = m->virtualSystemDescriptions.begin();
1720 it != m->virtualSystemDescriptions.end();
1721 ++it)
1722 {
1723 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1724 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1725 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1726 for (itH = avsdeHDs.begin();
1727 itH != avsdeHDs.end();
1728 ++itH)
1729 {
1730 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
1731 /* Target path needs to be composed from where the output OVF is */
1732 Utf8Str strTargetFilePath(strTmpOvf);
1733 strTargetFilePath.stripFilename();
1734 strTargetFilePath.append("/");
1735 strTargetFilePath.append(strTargetFileNameOnly);
1736 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
1737 if (RT_FAILURE(vrc))
1738 throw setError(VBOX_E_FILE_ERROR,
1739 tr("Cannot find source file '%s'"), strTargetFilePath.c_str());
1740 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
1741 }
1742 }
1743 /* Next we have to upload the OVF & all disk images */
1744 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1745 if (RT_FAILURE(vrc))
1746 throw setError(VBOX_E_IPRT_ERROR,
1747 tr("Cannot create S3 service handler"));
1748 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1749
1750 /* Upload all files */
1751 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1752 {
1753 const pair<Utf8Str, ULONG> &s = (*it1);
1754 char *pszFilename = RTPathFilename(s.first.c_str());
1755 /* Advance to the next operation */
1756 pTask->pProgress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename), s.second);
1757 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
1758 if (RT_FAILURE(vrc))
1759 {
1760 if (vrc == VERR_S3_CANCELED)
1761 break;
1762 else if (vrc == VERR_S3_ACCESS_DENIED)
1763 throw setError(E_ACCESSDENIED,
1764 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);
1765 else if (vrc == VERR_S3_NOT_FOUND)
1766 throw setError(VBOX_E_FILE_ERROR,
1767 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
1768 else
1769 throw setError(VBOX_E_IPRT_ERROR,
1770 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
1771 }
1772 }
1773 }
1774 catch(HRESULT aRC)
1775 {
1776 rc = aRC;
1777 }
1778 /* Cleanup */
1779 RTS3Destroy(hS3);
1780 /* Delete all files which where temporary created */
1781 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1782 {
1783 const char *pszFilePath = (*it1).first.c_str();
1784 if (RTPathExists(pszFilePath))
1785 {
1786 vrc = RTFileDelete(pszFilePath);
1787 if (RT_FAILURE(vrc))
1788 rc = setError(VBOX_E_FILE_ERROR,
1789 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
1790 }
1791 }
1792 /* Delete the temporary directory */
1793 if (RTPathExists(pszTmpDir))
1794 {
1795 vrc = RTDirRemove(pszTmpDir);
1796 if (RT_FAILURE(vrc))
1797 rc = setError(VBOX_E_FILE_ERROR,
1798 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1799 }
1800 if (pszTmpDir)
1801 RTStrFree(pszTmpDir);
1802
1803 LogFlowFunc(("rc=%Rhrc\n", rc));
1804 LogFlowFuncLeave();
1805
1806 return rc;
1807}
1808
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette