VirtualBox

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

Last change on this file since 30037 was 29984, checked in by vboxsync, 14 years ago

OVF: almost

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

© 2023 Oracle
ContactPrivacy policyTerms of Use