VirtualBox

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

最後變更 在這個檔案從27886是 27886,由 vboxsync 提交於 15 年 前

Main/OVF: document import code

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

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