VirtualBox

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

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

XmlFileWrite::write: Added a fSafe argument for safe writing of the xml file. See method description for details.

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