VirtualBox

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

Last change on this file since 32048 was 31698, checked in by vboxsync, 14 years ago

Main, frontends: unsigned long long -> long long

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