VirtualBox

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

Last change on this file since 31568 was 31562, checked in by vboxsync, 14 years ago

Main: merge IVirtualBox::FindHardDisk, GetHardDisk, FindDVDImage, GetDVDImage, FindFloppyImage and GetFloppyImage into one IVirtualBox::findMedium method

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