VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/ApplianceImplExport.cpp@ 73893

Last change on this file since 73893 was 73893, checked in by vboxsync, 7 years ago

bugref:9152. Build fixes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 118.5 KB
Line 
1/* $Id: ApplianceImplExport.cpp 73893 2018-08-26 15:40:27Z vboxsync $ */
2/** @file
3 * IAppliance and IVirtualSystem COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2008-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <iprt/path.h>
19#include <iprt/dir.h>
20#include <iprt/param.h>
21#include <iprt/s3.h>
22#include <iprt/manifest.h>
23#include <iprt/stream.h>
24#include <iprt/zip.h>
25
26#include <VBox/version.h>
27
28#include "ApplianceImpl.h"
29#include "VirtualBoxImpl.h"
30#include "ProgressImpl.h"
31#include "MachineImpl.h"
32#include "MediumImpl.h"
33#include "MediumFormatImpl.h"
34#include "Global.h"
35#include "SystemPropertiesImpl.h"
36
37#include "AutoCaller.h"
38#include "Logging.h"
39
40#include "ApplianceImplPrivate.h"
41
42using namespace std;
43
44////////////////////////////////////////////////////////////////////////////////
45//
46// IMachine public methods
47//
48////////////////////////////////////////////////////////////////////////////////
49
50// This code is here so we won't have to include the appliance headers in the
51// IMachine implementation, and we also need to access private appliance data.
52
53/**
54* Public method implementation.
55* @param aAppliance Appliance object.
56* @param aLocation Where to store the appliance.
57* @param aDescription Appliance description.
58* @return
59*/
60HRESULT Machine::exportTo(const ComPtr<IAppliance> &aAppliance, const com::Utf8Str &aLocation,
61 ComPtr<IVirtualSystemDescription> &aDescription)
62{
63 HRESULT rc = S_OK;
64
65 if (!aAppliance)
66 return E_POINTER;
67
68 ComObjPtr<VirtualSystemDescription> pNewDesc;
69
70 try
71 {
72 IAppliance *iAppliance = aAppliance;
73 Appliance *pAppliance = static_cast<Appliance*>(iAppliance);
74
75 LocationInfo locInfo;
76 i_parseURI(aLocation, locInfo);
77
78 Utf8Str strBasename(locInfo.strPath);
79 strBasename.stripPath().stripSuffix();
80 if (locInfo.strPath.endsWith(".tar.gz", Utf8Str::CaseSensitive))
81 strBasename.stripSuffix();
82
83 // create a new virtual system to store in the appliance
84 rc = pNewDesc.createObject();
85 if (FAILED(rc)) throw rc;
86 rc = pNewDesc->init();
87 if (FAILED(rc)) throw rc;
88
89 // store the machine object so we can dump the XML in Appliance::Write()
90 pNewDesc->m->pMachine = this;
91
92 // first, call the COM methods, as they request locks
93 BOOL fUSBEnabled = FALSE;
94 com::SafeIfaceArray<IUSBController> usbControllers;
95 rc = COMGETTER(USBControllers)(ComSafeArrayAsOutParam(usbControllers));
96 if (SUCCEEDED(rc))
97 {
98 for (unsigned i = 0; i < usbControllers.size(); ++i)
99 {
100 USBControllerType_T enmType;
101
102 rc = usbControllers[i]->COMGETTER(Type)(&enmType);
103 if (FAILED(rc)) throw rc;
104
105 if (enmType == USBControllerType_OHCI)
106 fUSBEnabled = TRUE;
107 }
108 }
109
110 // request the machine lock while accessing internal members
111 AutoReadLock alock1(this COMMA_LOCKVAL_SRC_POS);
112
113 ComPtr<IAudioAdapter> pAudioAdapter = mAudioAdapter;
114 BOOL fAudioEnabled;
115 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
116 if (FAILED(rc)) throw rc;
117 AudioControllerType_T audioController;
118 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
119 if (FAILED(rc)) throw rc;
120
121 // get name
122 Utf8Str strVMName = mUserData->s.strName;
123 // get description
124 Utf8Str strDescription = mUserData->s.strDescription;
125 // get guest OS
126 Utf8Str strOsTypeVBox = mUserData->s.strOsType;
127 // CPU count
128 uint32_t cCPUs = mHWData->mCPUCount;
129 // memory size in MB
130 uint32_t ulMemSizeMB = mHWData->mMemorySize;
131 // VRAM size?
132 // BIOS settings?
133 // 3D acceleration enabled?
134 // hardware virtualization enabled?
135 // nested paging enabled?
136 // HWVirtExVPIDEnabled?
137 // PAEEnabled?
138 // Long mode enabled?
139 BOOL fLongMode;
140 rc = GetCPUProperty(CPUPropertyType_LongMode, &fLongMode);
141 if (FAILED(rc)) throw rc;
142
143 // snapshotFolder?
144 // VRDPServer?
145
146 /* Guest OS type */
147 ovf::CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str(), fLongMode);
148 pNewDesc->i_addEntry(VirtualSystemDescriptionType_OS,
149 "",
150 Utf8StrFmt("%RI32", cim),
151 strOsTypeVBox);
152
153 /* VM name */
154 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Name,
155 "",
156 strVMName,
157 strVMName);
158
159 // description
160 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Description,
161 "",
162 strDescription,
163 strDescription);
164
165 /* CPU count*/
166 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
167 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CPU,
168 "",
169 strCpuCount,
170 strCpuCount);
171
172 /* Memory */
173 Utf8Str strMemory = Utf8StrFmt("%RI64", (uint64_t)ulMemSizeMB * _1M);
174 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Memory,
175 "",
176 strMemory,
177 strMemory);
178
179 // the one VirtualBox IDE controller has two channels with two ports each, which is
180 // considered two IDE controllers with two ports each by OVF, so export it as two
181 int32_t lIDEControllerPrimaryIndex = 0;
182 int32_t lIDEControllerSecondaryIndex = 0;
183 int32_t lSATAControllerIndex = 0;
184 int32_t lSCSIControllerIndex = 0;
185
186 /* Fetch all available storage controllers */
187 com::SafeIfaceArray<IStorageController> nwControllers;
188 rc = COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(nwControllers));
189 if (FAILED(rc)) throw rc;
190
191 ComPtr<IStorageController> pIDEController;
192 ComPtr<IStorageController> pSATAController;
193 ComPtr<IStorageController> pSCSIController;
194 ComPtr<IStorageController> pSASController;
195 for (size_t j = 0; j < nwControllers.size(); ++j)
196 {
197 StorageBus_T eType;
198 rc = nwControllers[j]->COMGETTER(Bus)(&eType);
199 if (FAILED(rc)) throw rc;
200 if ( eType == StorageBus_IDE
201 && pIDEController.isNull())
202 pIDEController = nwControllers[j];
203 else if ( eType == StorageBus_SATA
204 && pSATAController.isNull())
205 pSATAController = nwControllers[j];
206 else if ( eType == StorageBus_SCSI
207 && pSATAController.isNull())
208 pSCSIController = nwControllers[j];
209 else if ( eType == StorageBus_SAS
210 && pSASController.isNull())
211 pSASController = nwControllers[j];
212 }
213
214// <const name="HardDiskControllerIDE" value="6" />
215 if (!pIDEController.isNull())
216 {
217 StorageControllerType_T ctlr;
218 rc = pIDEController->COMGETTER(ControllerType)(&ctlr);
219 if (FAILED(rc)) throw rc;
220
221 Utf8Str strVBox;
222 switch (ctlr)
223 {
224 case StorageControllerType_PIIX3: strVBox = "PIIX3"; break;
225 case StorageControllerType_PIIX4: strVBox = "PIIX4"; break;
226 case StorageControllerType_ICH6: strVBox = "ICH6"; break;
227 default: break; /* Shut up MSC. */
228 }
229
230 if (strVBox.length())
231 {
232 lIDEControllerPrimaryIndex = (int32_t)pNewDesc->m->maDescriptions.size();
233 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
234 Utf8StrFmt("%d", lIDEControllerPrimaryIndex), // strRef
235 strVBox, // aOvfValue
236 strVBox); // aVBoxValue
237 lIDEControllerSecondaryIndex = lIDEControllerPrimaryIndex + 1;
238 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
239 Utf8StrFmt("%d", lIDEControllerSecondaryIndex),
240 strVBox,
241 strVBox);
242 }
243 }
244
245// <const name="HardDiskControllerSATA" value="7" />
246 if (!pSATAController.isNull())
247 {
248 Utf8Str strVBox = "AHCI";
249 lSATAControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
250 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
251 Utf8StrFmt("%d", lSATAControllerIndex),
252 strVBox,
253 strVBox);
254 }
255
256// <const name="HardDiskControllerSCSI" value="8" />
257 if (!pSCSIController.isNull())
258 {
259 StorageControllerType_T ctlr;
260 rc = pSCSIController->COMGETTER(ControllerType)(&ctlr);
261 if (SUCCEEDED(rc))
262 {
263 Utf8Str strVBox = "LsiLogic"; // the default in VBox
264 switch (ctlr)
265 {
266 case StorageControllerType_LsiLogic: strVBox = "LsiLogic"; break;
267 case StorageControllerType_BusLogic: strVBox = "BusLogic"; break;
268 default: break; /* Shut up MSC. */
269 }
270 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
271 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
272 Utf8StrFmt("%d", lSCSIControllerIndex),
273 strVBox,
274 strVBox);
275 }
276 else
277 throw rc;
278 }
279
280 if (!pSASController.isNull())
281 {
282 // VirtualBox considers the SAS controller a class of its own but in OVF
283 // it should be a SCSI controller
284 Utf8Str strVBox = "LsiLogicSas";
285 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
286 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSAS,
287 Utf8StrFmt("%d", lSCSIControllerIndex),
288 strVBox,
289 strVBox);
290 }
291
292// <const name="HardDiskImage" value="9" />
293// <const name="Floppy" value="18" />
294// <const name="CDROM" value="19" />
295
296 for (MediumAttachmentList::const_iterator
297 it = mMediumAttachments->begin();
298 it != mMediumAttachments->end();
299 ++it)
300 {
301 ComObjPtr<MediumAttachment> pHDA = *it;
302
303 // the attachment's data
304 ComPtr<IMedium> pMedium;
305 ComPtr<IStorageController> ctl;
306 Bstr controllerName;
307
308 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
309 if (FAILED(rc)) throw rc;
310
311 rc = GetStorageControllerByName(controllerName.raw(), ctl.asOutParam());
312 if (FAILED(rc)) throw rc;
313
314 StorageBus_T storageBus;
315 DeviceType_T deviceType;
316 LONG lChannel;
317 LONG lDevice;
318
319 rc = ctl->COMGETTER(Bus)(&storageBus);
320 if (FAILED(rc)) throw rc;
321
322 rc = pHDA->COMGETTER(Type)(&deviceType);
323 if (FAILED(rc)) throw rc;
324
325 rc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
326 if (FAILED(rc)) throw rc;
327
328 rc = pHDA->COMGETTER(Port)(&lChannel);
329 if (FAILED(rc)) throw rc;
330
331 rc = pHDA->COMGETTER(Device)(&lDevice);
332 if (FAILED(rc)) throw rc;
333
334 Utf8Str strTargetImageName;
335 Utf8Str strLocation;
336 LONG64 llSize = 0;
337
338 if ( deviceType == DeviceType_HardDisk
339 && pMedium)
340 {
341 Bstr bstrLocation;
342
343 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
344 if (FAILED(rc)) throw rc;
345 strLocation = bstrLocation;
346
347 // find the source's base medium for two things:
348 // 1) we'll use its name to determine the name of the target disk, which is readable,
349 // as opposed to the UUID filename of a differencing image, if pMedium is one
350 // 2) we need the size of the base image so we can give it to addEntry(), and later
351 // on export, the progress will be based on that (and not the diff image)
352 ComPtr<IMedium> pBaseMedium;
353 rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
354 // returns pMedium if there are no diff images
355 if (FAILED(rc)) throw rc;
356
357 strTargetImageName = Utf8StrFmt("%s-disk%.3d.vmdk", strBasename.c_str(), ++pAppliance->m->cDisks);
358 if (strTargetImageName.length() > RTTAR_NAME_MAX)
359 throw setError(VBOX_E_NOT_SUPPORTED,
360 tr("Cannot attach disk '%s' -- file name too long"), strTargetImageName.c_str());
361
362 // force reading state, or else size will be returned as 0
363 MediumState_T ms;
364 rc = pBaseMedium->RefreshState(&ms);
365 if (FAILED(rc)) throw rc;
366
367 rc = pBaseMedium->COMGETTER(Size)(&llSize);
368 if (FAILED(rc)) throw rc;
369
370 /* If the medium is encrypted add the key identifier to the list. */
371 IMedium *iBaseMedium = pBaseMedium;
372 Medium *pBase = static_cast<Medium*>(iBaseMedium);
373 const com::Utf8Str strKeyId = pBase->i_getKeyId();
374 if (!strKeyId.isEmpty())
375 {
376 IMedium *iMedium = pMedium;
377 Medium *pMed = static_cast<Medium*>(iMedium);
378 com::Guid mediumUuid = pMed->i_getId();
379 bool fKnown = false;
380
381 /* Check whether the ID is already in our sequence, add it otherwise. */
382 for (unsigned i = 0; i < pAppliance->m->m_vecPasswordIdentifiers.size(); i++)
383 {
384 if (strKeyId.equals(pAppliance->m->m_vecPasswordIdentifiers[i]))
385 {
386 fKnown = true;
387 break;
388 }
389 }
390
391 if (!fKnown)
392 {
393 GUIDVEC vecMediumIds;
394
395 vecMediumIds.push_back(mediumUuid);
396 pAppliance->m->m_vecPasswordIdentifiers.push_back(strKeyId);
397 pAppliance->m->m_mapPwIdToMediumIds.insert(std::pair<com::Utf8Str, GUIDVEC>(strKeyId, vecMediumIds));
398 }
399 else
400 {
401 std::map<com::Utf8Str, GUIDVEC>::iterator itMap = pAppliance->m->m_mapPwIdToMediumIds.find(strKeyId);
402 if (itMap == pAppliance->m->m_mapPwIdToMediumIds.end())
403 throw setError(E_FAIL, tr("Internal error adding a medium UUID to the map"));
404 itMap->second.push_back(mediumUuid);
405 }
406 }
407 }
408 else if ( deviceType == DeviceType_DVD
409 && pMedium)
410 {
411 /*
412 * check the minimal rules to grant access to export an image
413 * 1. no host drive CD/DVD image
414 * 2. the image must be accessible and readable
415 * 3. only ISO image is exported
416 */
417
418 //1. no host drive CD/DVD image
419 BOOL fHostDrive = false;
420 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
421 if (FAILED(rc)) throw rc;
422
423 if(fHostDrive)
424 continue;
425
426 //2. the image must be accessible and readable
427 MediumState_T ms;
428 rc = pMedium->RefreshState(&ms);
429 if (FAILED(rc)) throw rc;
430
431 if (ms != MediumState_Created)
432 continue;
433
434 //3. only ISO image is exported
435 Bstr bstrLocation;
436 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
437 if (FAILED(rc)) throw rc;
438
439 strLocation = bstrLocation;
440
441 Utf8Str ext = strLocation;
442 ext.assignEx(RTPathSuffix(ext.c_str()));//returns extension with dot (".iso")
443
444 int eq = ext.compare(".iso", Utf8Str::CaseInsensitive);
445 if (eq != 0)
446 continue;
447
448 strTargetImageName = Utf8StrFmt("%s-disk%.3d.iso", strBasename.c_str(), ++pAppliance->m->cDisks);
449 if (strTargetImageName.length() > RTTAR_NAME_MAX)
450 throw setError(VBOX_E_NOT_SUPPORTED,
451 tr("Cannot attach image '%s' -- file name too long"), strTargetImageName.c_str());
452
453 rc = pMedium->COMGETTER(Size)(&llSize);
454 if (FAILED(rc)) throw rc;
455 }
456 // and how this translates to the virtual system
457 int32_t lControllerVsys = 0;
458 LONG lChannelVsys;
459
460 switch (storageBus)
461 {
462 case StorageBus_IDE:
463 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
464 // and it must be updated when that is changed!
465 // Before 3.2 we exported one IDE controller with channel 0-3, but we now maintain
466 // compatibility with what VMware does and export two IDE controllers with two channels each
467
468 if (lChannel == 0 && lDevice == 0) // primary master
469 {
470 lControllerVsys = lIDEControllerPrimaryIndex;
471 lChannelVsys = 0;
472 }
473 else if (lChannel == 0 && lDevice == 1) // primary slave
474 {
475 lControllerVsys = lIDEControllerPrimaryIndex;
476 lChannelVsys = 1;
477 }
478 else if (lChannel == 1 && lDevice == 0) // secondary master; by default this is the CD-ROM but
479 // as of VirtualBox 3.1 that can change
480 {
481 lControllerVsys = lIDEControllerSecondaryIndex;
482 lChannelVsys = 0;
483 }
484 else if (lChannel == 1 && lDevice == 1) // secondary slave
485 {
486 lControllerVsys = lIDEControllerSecondaryIndex;
487 lChannelVsys = 1;
488 }
489 else
490 throw setError(VBOX_E_NOT_SUPPORTED,
491 tr("Cannot handle medium attachment: channel is %d, device is %d"), lChannel, lDevice);
492 break;
493
494 case StorageBus_SATA:
495 lChannelVsys = lChannel; // should be between 0 and 29
496 lControllerVsys = lSATAControllerIndex;
497 break;
498
499 case StorageBus_SCSI:
500 case StorageBus_SAS:
501 lChannelVsys = lChannel; // should be between 0 and 15
502 lControllerVsys = lSCSIControllerIndex;
503 break;
504
505 case StorageBus_Floppy:
506 lChannelVsys = 0;
507 lControllerVsys = 0;
508 break;
509
510 default:
511 throw setError(VBOX_E_NOT_SUPPORTED,
512 tr("Cannot handle medium attachment: storageBus is %d, channel is %d, device is %d"),
513 storageBus, lChannel, lDevice);
514 }
515
516 Utf8StrFmt strExtra("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys);
517 Utf8Str strEmpty;
518
519 switch (deviceType)
520 {
521 case DeviceType_HardDisk:
522 Log(("Adding VirtualSystemDescriptionType_HardDiskImage, disk size: %RI64\n", llSize));
523 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskImage,
524 strTargetImageName, // disk ID: let's use the name
525 strTargetImageName, // OVF value:
526 strLocation, // vbox value: media path
527 (uint32_t)(llSize / _1M),
528 strExtra);
529 break;
530
531 case DeviceType_DVD:
532 Log(("Adding VirtualSystemDescriptionType_CDROM, disk size: %RI64\n", llSize));
533 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CDROM,
534 strTargetImageName, // disk ID
535 strTargetImageName, // OVF value
536 strLocation, // vbox value
537 (uint32_t)(llSize / _1M),// ulSize
538 strExtra);
539 break;
540
541 case DeviceType_Floppy:
542 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Floppy,
543 strEmpty, // disk ID
544 strEmpty, // OVF value
545 strEmpty, // vbox value
546 1, // ulSize
547 strExtra);
548 break;
549
550 default: break; /* Shut up MSC. */
551 }
552 }
553
554// <const name="NetworkAdapter" />
555 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(i_getChipsetType());
556 size_t a;
557 for (a = 0; a < maxNetworkAdapters; ++a)
558 {
559 ComPtr<INetworkAdapter> pNetworkAdapter;
560 BOOL fEnabled;
561 NetworkAdapterType_T adapterType;
562 NetworkAttachmentType_T attachmentType;
563
564 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
565 if (FAILED(rc)) throw rc;
566 /* Enable the network card & set the adapter type */
567 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
568 if (FAILED(rc)) throw rc;
569
570 if (fEnabled)
571 {
572 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
573 if (FAILED(rc)) throw rc;
574
575 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
576 if (FAILED(rc)) throw rc;
577
578 Utf8Str strAttachmentType = convertNetworkAttachmentTypeToString(attachmentType);
579 pNewDesc->i_addEntry(VirtualSystemDescriptionType_NetworkAdapter,
580 "", // ref
581 strAttachmentType, // orig
582 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
583 0,
584 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
585 }
586 }
587
588// <const name="USBController" />
589#ifdef VBOX_WITH_USB
590 if (fUSBEnabled)
591 pNewDesc->i_addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
592#endif /* VBOX_WITH_USB */
593
594// <const name="SoundCard" />
595 if (fAudioEnabled)
596 pNewDesc->i_addEntry(VirtualSystemDescriptionType_SoundCard,
597 "",
598 "ensoniq1371", // this is what OVFTool writes and VMware supports
599 Utf8StrFmt("%RI32", audioController));
600
601 /* We return the new description to the caller */
602 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
603 copy.queryInterfaceTo(aDescription.asOutParam());
604
605 AutoWriteLock alock(pAppliance COMMA_LOCKVAL_SRC_POS);
606 // finally, add the virtual system to the appliance
607 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
608 }
609 catch(HRESULT arc)
610 {
611 rc = arc;
612 }
613
614 return rc;
615}
616
617////////////////////////////////////////////////////////////////////////////////
618//
619// IAppliance public methods
620//
621////////////////////////////////////////////////////////////////////////////////
622
623/**
624 * Public method implementation.
625 * @param aFormat Appliance format.
626 * @param aOptions Export options.
627 * @param aPath Path to write the appliance to.
628 * @param aProgress Progress object.
629 * @return
630 */
631HRESULT Appliance::write(const com::Utf8Str &aFormat,
632 const std::vector<ExportOptions_T> &aOptions,
633 const com::Utf8Str &aPath,
634 ComPtr<IProgress> &aProgress)
635{
636 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
637
638 m->optListExport.clear();
639 if (aOptions.size())
640 {
641 for (size_t i = 0; i < aOptions.size(); ++i)
642 {
643 m->optListExport.insert(i, aOptions[i]);
644 }
645 }
646
647 HRESULT rc = S_OK;
648// AssertReturn(!(m->optListExport.contains(ExportOptions_CreateManifest)
649// && m->optListExport.contains(ExportOptions_ExportDVDImages)), E_INVALIDARG);
650
651 /* Parse all necessary info out of the URI */
652 i_parseURI(aPath, m->locInfo);
653
654 if (m->locInfo.storageType == VFSType_OCI)//(isCloudDestination(aPath))
655 {
656 rc = S_OK;
657 ComObjPtr<Progress> progress;
658 try
659 {
660 switch (m->locInfo.storageType)
661 {
662 case VFSType_OCI:
663 rc = i_writeOCIImpl(m->locInfo, progress);
664 break;
665// case VFSType_GCP:
666// rc = i_writeGCPImpl(m->locInfo, progress);
667// break;
668// case VFSType_Amazon:
669// rc = i_writeAmazonImpl(m->locInfo, progress);
670// break;
671// case VFSType_Azure:
672// rc = i_writeAzureImpl(m->locInfo, progress);
673// break;
674 default:
675 break;
676 }
677
678 }
679 catch (HRESULT aRC)
680 {
681 rc = aRC;
682 }
683
684 if (SUCCEEDED(rc))
685 /* Return progress to the caller */
686 progress.queryInterfaceTo(aProgress.asOutParam());
687 }
688 else
689 {
690 m->fExportISOImages = m->optListExport.contains(ExportOptions_ExportDVDImages);
691
692 if (!m->fExportISOImages)/* remove all ISO images from VirtualSystemDescription */
693 {
694 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
695 it = m->virtualSystemDescriptions.begin();
696 it != m->virtualSystemDescriptions.end();
697 ++it)
698 {
699 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
700 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
701 std::list<VirtualSystemDescriptionEntry*>::const_iterator itSkipped = skipped.begin();
702 while (itSkipped != skipped.end())
703 {
704 (*itSkipped)->skipIt = true;
705 ++itSkipped;
706 }
707 }
708 }
709
710 // do not allow entering this method if the appliance is busy reading or writing
711 if (!i_isApplianceIdle())
712 return E_ACCESSDENIED;
713
714 // figure the export format. We exploit the unknown version value for oracle public cloud.
715 ovf::OVFVersion_T ovfF;
716 if (aFormat == "ovf-0.9")
717 ovfF = ovf::OVFVersion_0_9;
718 else if (aFormat == "ovf-1.0")
719 ovfF = ovf::OVFVersion_1_0;
720 else if (aFormat == "ovf-2.0")
721 ovfF = ovf::OVFVersion_2_0;
722 else if (aFormat == "opc-1.0")
723 ovfF = ovf::OVFVersion_unknown;
724 else
725 return setError(VBOX_E_FILE_ERROR,
726 tr("Invalid format \"%s\" specified"), aFormat.c_str());
727
728 // Check the extension.
729 if (ovfF == ovf::OVFVersion_unknown)
730 {
731 if (!aPath.endsWith(".tar.gz", Utf8Str::CaseInsensitive))
732 return setError(VBOX_E_FILE_ERROR,
733 tr("OPC appliance file must have .tar.gz extension"));
734 }
735 else if ( !aPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
736 && !aPath.endsWith(".ova", Utf8Str::CaseInsensitive))
737 return setError(VBOX_E_FILE_ERROR, tr("Appliance file must have .ovf or .ova extension"));
738
739
740 /* As of OVF 2.0 we have to use SHA-256 in the manifest. */
741 m->fManifest = m->optListExport.contains(ExportOptions_CreateManifest);
742 if (m->fManifest)
743 m->fDigestTypes = ovfF >= ovf::OVFVersion_2_0 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1;
744 Assert(m->hOurManifest == NIL_RTMANIFEST);
745
746 /* Check whether all passwords are supplied or error out. */
747 if (m->m_cPwProvided < m->m_vecPasswordIdentifiers.size())
748 return setError(VBOX_E_INVALID_OBJECT_STATE,
749 tr("Appliance export failed because not all passwords were provided for all encrypted media"));
750
751 ComObjPtr<Progress> progress;
752 rc = S_OK;
753 try
754 {
755 /* Parse all necessary info out of the URI */
756 i_parseURI(aPath, m->locInfo);
757
758 switch (ovfF)
759 {
760 case ovf::OVFVersion_unknown:
761 rc = i_writeOPCImpl(ovfF, m->locInfo, progress);
762 break;
763 default:
764 rc = i_writeImpl(ovfF, m->locInfo, progress);
765 break;
766 }
767
768 }
769 catch (HRESULT aRC)
770 {
771 rc = aRC;
772 }
773
774 if (SUCCEEDED(rc))
775 /* Return progress to the caller */
776 progress.queryInterfaceTo(aProgress.asOutParam());
777 }
778
779 return rc;
780}
781
782////////////////////////////////////////////////////////////////////////////////
783//
784// Appliance private methods
785//
786////////////////////////////////////////////////////////////////////////////////
787
788/*******************************************************************************
789 * Export stuff
790 ******************************************************************************/
791
792/**
793 * Implementation for writing out the OVF to disk. This starts a new thread which will call
794 * Appliance::taskThreadWriteOVF().
795 *
796 * This is in a separate private method because it is used from two locations:
797 *
798 * 1) from the public Appliance::Write().
799 *
800 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl(), which
801 * called Appliance::i_writeFSOVA(), which called Appliance::i_writeImpl(), which then called this again.
802 *
803 * @param aFormat
804 * @param aLocInfo
805 * @param aProgress
806 * @return
807 */
808HRESULT Appliance::i_writeImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
809{
810 HRESULT rc;
811 try
812 {
813 rc = i_setUpProgress(aProgress,
814 BstrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
815 (aLocInfo.storageType == VFSType_File) ? WriteFile : WriteS3);
816
817 /* Initialize our worker task */
818 TaskOVF* task = NULL;
819 try
820 {
821 task = new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress);
822 }
823 catch(...)
824 {
825 delete task;
826 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
827 tr("Could not create TaskOVF object for for writing out the OVF to disk"));
828 }
829
830 /* The OVF version to write */
831 task->enFormat = aFormat;
832
833 rc = task->createThread();
834 if (FAILED(rc)) throw rc;
835
836 }
837 catch (HRESULT aRC)
838 {
839 rc = aRC;
840 }
841
842 return rc;
843}
844
845
846HRESULT Appliance::i_writeOCIImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
847{
848 HRESULT rc;
849 try
850 {
851 //remove all disks from the VirtualSystemDescription exept one
852 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
853 it = m->virtualSystemDescriptions.begin();
854 it != m->virtualSystemDescriptions.end();
855 ++it)
856 {
857 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
858 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
859 std::list<VirtualSystemDescriptionEntry*>::const_iterator itSkipped = skipped.begin();
860 while (itSkipped != skipped.end())
861 {
862 (*itSkipped)->skipIt = true;
863 ++itSkipped;
864 }
865
866 skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
867 itSkipped = skipped.begin();
868 while (itSkipped != skipped.end())
869 {
870 Utf8Str path = (*itSkipped)->strVBoxCurrent;
871 // Locate the Medium object for this entry (by location/path).
872 Log(("Finding source disk \"%s\"\n", path.c_str()));
873 ComObjPtr<Medium> ptrSourceDisk;
874 rc = mVirtualBox->i_findHardDiskByLocation(path, true , &ptrSourceDisk);
875 ++itSkipped;
876 }
877 }
878
879 SetUpProgressMode mode;
880 switch (aLocInfo.storageType)
881 {
882 case VFSType_S3:
883 mode = WriteS3;
884 break;
885 case VFSType_Cloud:
886 case VFSType_OCI:
887 mode = ExportOCI;
888 break;
889 case VFSType_File:
890 mode = WriteFile;
891 break;
892 case VFSType_WebDav:
893 case VFSType_32BitHack:
894 break;
895 }
896 rc = i_setUpProgress(aProgress,
897 BstrFmt(tr("Export appliance to Cloud '%s'"), aLocInfo.strPath.c_str()),
898 mode);
899
900 // Initialize our worker task
901 TaskOCI* task = NULL;
902 try
903 {
904 task = new Appliance::TaskOCI(this, TaskOCI::Export, aLocInfo, aProgress);
905 }
906 catch(...)
907 {
908 delete task;
909 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
910 tr("Could not create TaskOCI object for exporting to OCI"));
911 }
912
913 rc = task->createThread();
914 if (FAILED(rc)) throw rc;
915
916 }
917 catch (HRESULT aRC)
918 {
919 rc = aRC;
920 }
921
922 return rc;
923}
924
925HRESULT Appliance::i_writeOPCImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
926{
927 HRESULT rc;
928 try
929 {
930 rc = i_setUpProgress(aProgress,
931 BstrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
932 (aLocInfo.storageType == VFSType_File) ? WriteFile : WriteS3);
933
934 /* Initialize our worker task */
935 TaskOPC* task = NULL;
936 try
937 {
938 task = new Appliance::TaskOPC(this, TaskOPC::Export, aLocInfo, aProgress);
939 }
940 catch(...)
941 {
942 delete task;
943 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
944 tr("Could not create TaskOPC object for for writing out the OPC to disk"));
945 }
946
947 rc = task->createThread();
948 if (FAILED(rc)) throw rc;
949
950 }
951 catch (HRESULT aRC)
952 {
953 rc = aRC;
954 }
955
956 return rc;
957}
958
959
960/**
961 * Called from Appliance::i_writeFS() for creating a XML document for this
962 * Appliance.
963 *
964 * @param writeLock The current write lock.
965 * @param doc The xml document to fill.
966 * @param stack Structure for temporary private
967 * data shared with caller.
968 * @param strPath Path to the target OVF.
969 * instance for which to write XML.
970 * @param enFormat OVF format (0.9 or 1.0).
971 */
972void Appliance::i_buildXML(AutoWriteLockBase& writeLock,
973 xml::Document &doc,
974 XMLStack &stack,
975 const Utf8Str &strPath,
976 ovf::OVFVersion_T enFormat)
977{
978 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
979
980 pelmRoot->setAttribute("ovf:version", enFormat == ovf::OVFVersion_2_0 ? "2.0"
981 : enFormat == ovf::OVFVersion_1_0 ? "1.0"
982 : "0.9");
983 pelmRoot->setAttribute("xml:lang", "en-US");
984
985 Utf8Str strNamespace;
986
987 if (enFormat == ovf::OVFVersion_0_9)
988 {
989 strNamespace = ovf::OVF09_URI_string;
990 }
991 else if (enFormat == ovf::OVFVersion_1_0)
992 {
993 strNamespace = ovf::OVF10_URI_string;
994 }
995 else
996 {
997 strNamespace = ovf::OVF20_URI_string;
998 }
999
1000 pelmRoot->setAttribute("xmlns", strNamespace);
1001 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
1002
1003 // pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
1004 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
1005 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
1006 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
1007 pelmRoot->setAttribute("xmlns:vbox", "http://www.virtualbox.org/ovf/machine");
1008 // pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
1009
1010 if (enFormat == ovf::OVFVersion_2_0)
1011 {
1012 pelmRoot->setAttribute("xmlns:epasd",
1013 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_EthernetPortAllocationSettingData.xsd");
1014 pelmRoot->setAttribute("xmlns:sasd",
1015 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_StorageAllocationSettingData.xsd");
1016 }
1017
1018 // <Envelope>/<References>
1019 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
1020
1021 /* <Envelope>/<DiskSection>:
1022 <DiskSection>
1023 <Info>List of the virtual disks used in the package</Info>
1024 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
1025 </DiskSection> */
1026 xml::ElementNode *pelmDiskSection;
1027 if (enFormat == ovf::OVFVersion_0_9)
1028 {
1029 // <Section xsi:type="ovf:DiskSection_Type">
1030 pelmDiskSection = pelmRoot->createChild("Section");
1031 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
1032 }
1033 else
1034 pelmDiskSection = pelmRoot->createChild("DiskSection");
1035
1036 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
1037 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
1038
1039 /* <Envelope>/<NetworkSection>:
1040 <NetworkSection>
1041 <Info>Logical networks used in the package</Info>
1042 <Network ovf:name="VM Network">
1043 <Description>The network that the LAMP Service will be available on</Description>
1044 </Network>
1045 </NetworkSection> */
1046 xml::ElementNode *pelmNetworkSection;
1047 if (enFormat == ovf::OVFVersion_0_9)
1048 {
1049 // <Section xsi:type="ovf:NetworkSection_Type">
1050 pelmNetworkSection = pelmRoot->createChild("Section");
1051 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
1052 }
1053 else
1054 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
1055
1056 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
1057 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
1058
1059 // and here come the virtual systems:
1060
1061 // write a collection if we have more than one virtual system _and_ we're
1062 // writing OVF 1.0; otherwise fail since ovftool can't import more than
1063 // one machine, it seems
1064 xml::ElementNode *pelmToAddVirtualSystemsTo;
1065 if (m->virtualSystemDescriptions.size() > 1)
1066 {
1067 if (enFormat == ovf::OVFVersion_0_9)
1068 throw setError(VBOX_E_FILE_ERROR,
1069 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
1070
1071 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
1072 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
1073 }
1074 else
1075 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
1076
1077 // this list receives pointers to the XML elements in the machine XML which
1078 // might have UUIDs that need fixing after we know the UUIDs of the exported images
1079 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
1080 uint32_t ulFile = 1;
1081 /* Iterate through all virtual systems of that appliance */
1082 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
1083 itV = m->virtualSystemDescriptions.begin();
1084 itV != m->virtualSystemDescriptions.end();
1085 ++itV)
1086 {
1087 ComObjPtr<VirtualSystemDescription> vsdescThis = *itV;
1088 i_buildXMLForOneVirtualSystem(writeLock,
1089 *pelmToAddVirtualSystemsTo,
1090 &llElementsWithUuidAttributes,
1091 vsdescThis,
1092 enFormat,
1093 stack); // disks and networks stack
1094
1095 list<Utf8Str> diskList;
1096
1097 for (list<Utf8Str>::const_iterator
1098 itDisk = stack.mapDiskSequenceForOneVM.begin();
1099 itDisk != stack.mapDiskSequenceForOneVM.end();
1100 ++itDisk)
1101 {
1102 const Utf8Str &strDiskID = *itDisk;
1103 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
1104
1105 // source path: where the VBox image is
1106 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
1107 Bstr bstrSrcFilePath(strSrcFilePath);
1108
1109 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1110 if (strSrcFilePath.isEmpty() ||
1111 pDiskEntry->skipIt == true)
1112 continue;
1113
1114 // Do NOT check here whether the file exists. FindMedium will figure
1115 // that out, and filesystem-based tests are simply wrong in the
1116 // general case (think of iSCSI).
1117
1118 // We need some info from the source disks
1119 ComPtr<IMedium> pSourceDisk;
1120 //DeviceType_T deviceType = DeviceType_HardDisk;// by default
1121
1122 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
1123
1124 HRESULT rc;
1125
1126 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
1127 {
1128 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
1129 DeviceType_HardDisk,
1130 AccessMode_ReadWrite,
1131 FALSE /* fForceNewUuid */,
1132 pSourceDisk.asOutParam());
1133 if (FAILED(rc))
1134 throw rc;
1135 }
1136 else if (pDiskEntry->type == VirtualSystemDescriptionType_CDROM)//may be, this is CD/DVD
1137 {
1138 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
1139 DeviceType_DVD,
1140 AccessMode_ReadOnly,
1141 FALSE,
1142 pSourceDisk.asOutParam());
1143 if (FAILED(rc))
1144 throw rc;
1145 }
1146
1147 Bstr uuidSource;
1148 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
1149 if (FAILED(rc)) throw rc;
1150 Guid guidSource(uuidSource);
1151
1152 // output filename
1153 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
1154
1155 // target path needs to be composed from where the output OVF is
1156 Utf8Str strTargetFilePath(strPath);
1157 strTargetFilePath.stripFilename();
1158 strTargetFilePath.append("/");
1159 strTargetFilePath.append(strTargetFileNameOnly);
1160
1161 // We are always exporting to VMDK stream optimized for now
1162 //Bstr bstrSrcFormat = L"VMDK";//not used
1163
1164 diskList.push_back(strTargetFilePath);
1165
1166 LONG64 cbCapacity = 0; // size reported to guest
1167 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
1168 if (FAILED(rc)) throw rc;
1169 /// @todo r=poetzsch: wrong it is reported in bytes ...
1170 // capacity is reported in megabytes, so...
1171 //cbCapacity *= _1M;
1172
1173 Guid guidTarget; /* Creates a new uniq number for the target disk. */
1174 guidTarget.create();
1175
1176 // now handle the XML for the disk:
1177 Utf8StrFmt strFileRef("file%RI32", ulFile++);
1178 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
1179 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
1180 pelmFile->setAttribute("ovf:id", strFileRef);
1181 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
1182 /// @todo the actual size is not available at this point of time,
1183 // cause the disk will be compressed. The 1.0 standard says this is
1184 // optional! 1.1 isn't fully clear if the "gzip" format is used.
1185 // Need to be checked. */
1186 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
1187
1188 // add disk to XML Disks section
1189 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
1190 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
1191 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
1192 pelmDisk->setAttribute("ovf:diskId", strDiskID);
1193 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
1194
1195 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)//deviceType == DeviceType_HardDisk
1196 {
1197 pelmDisk->setAttribute("ovf:format",
1198 (enFormat == ovf::OVFVersion_0_9)
1199 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftoo
1200 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
1201 // correct string as communicated to us by VMware (public bug #6612)
1202 );
1203 }
1204 else //pDiskEntry->type == VirtualSystemDescriptionType_CDROM, deviceType == DeviceType_DVD
1205 {
1206 pelmDisk->setAttribute("ovf:format",
1207 "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
1208 );
1209 }
1210
1211 // add the UUID of the newly target image to the OVF disk element, but in the
1212 // vbox: namespace since it's not part of the standard
1213 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
1214
1215 // now, we might have other XML elements from vbox:Machine pointing to this image,
1216 // but those would refer to the UUID of the _source_ image (which we created the
1217 // export image from); those UUIDs need to be fixed to the export image
1218 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
1219 for (std::list<xml::ElementNode*>::const_iterator
1220 it = llElementsWithUuidAttributes.begin();
1221 it != llElementsWithUuidAttributes.end();
1222 ++it)
1223 {
1224 xml::ElementNode *pelmImage = *it;
1225 Utf8Str strUUID;
1226 pelmImage->getAttributeValue("uuid", strUUID);
1227 if (strUUID == strGuidSourceCurly)
1228 // overwrite existing uuid attribute
1229 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
1230 }
1231 }
1232 llElementsWithUuidAttributes.clear();
1233 stack.mapDiskSequenceForOneVM.clear();
1234 }
1235
1236 // now, fill in the network section we set up empty above according
1237 // to the networks we found with the hardware items
1238 for (map<Utf8Str, bool>::const_iterator
1239 it = stack.mapNetworks.begin();
1240 it != stack.mapNetworks.end();
1241 ++it)
1242 {
1243 const Utf8Str &strNetwork = it->first;
1244 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
1245 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
1246 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
1247 }
1248
1249}
1250
1251/**
1252 * Called from Appliance::i_buildXML() for each virtual system (machine) that
1253 * needs XML written out.
1254 *
1255 * @param writeLock The current write lock.
1256 * @param elmToAddVirtualSystemsTo XML element to append elements to.
1257 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
1258 * with UUID attributes for quick
1259 * fixing by caller later
1260 * @param vsdescThis The IVirtualSystemDescription
1261 * instance for which to write XML.
1262 * @param enFormat OVF format (0.9 or 1.0).
1263 * @param stack Structure for temporary private
1264 * data shared with caller.
1265 */
1266void Appliance::i_buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
1267 xml::ElementNode &elmToAddVirtualSystemsTo,
1268 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
1269 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1270 ovf::OVFVersion_T enFormat,
1271 XMLStack &stack)
1272{
1273 LogFlowFunc(("ENTER appliance %p\n", this));
1274
1275 xml::ElementNode *pelmVirtualSystem;
1276 if (enFormat == ovf::OVFVersion_0_9)
1277 {
1278 // <Section xsi:type="ovf:NetworkSection_Type">
1279 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
1280 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
1281 }
1282 else
1283 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
1284
1285 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
1286
1287 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
1288 if (llName.empty())
1289 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing VM name"));
1290 Utf8Str &strVMName = llName.back()->strVBoxCurrent;
1291 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
1292
1293 // product info
1294 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->i_findByType(VirtualSystemDescriptionType_Product);
1295 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_ProductUrl);
1296 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->i_findByType(VirtualSystemDescriptionType_Vendor);
1297 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_VendorUrl);
1298 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->i_findByType(VirtualSystemDescriptionType_Version);
1299 bool fProduct = llProduct.size() && !llProduct.back()->strVBoxCurrent.isEmpty();
1300 bool fProductUrl = llProductUrl.size() && !llProductUrl.back()->strVBoxCurrent.isEmpty();
1301 bool fVendor = llVendor.size() && !llVendor.back()->strVBoxCurrent.isEmpty();
1302 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.back()->strVBoxCurrent.isEmpty();
1303 bool fVersion = llVersion.size() && !llVersion.back()->strVBoxCurrent.isEmpty();
1304 if (fProduct || fProductUrl || fVendor || fVendorUrl || fVersion)
1305 {
1306 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1307 <Info>Meta-information about the installed software</Info>
1308 <Product>VAtest</Product>
1309 <Vendor>SUN Microsystems</Vendor>
1310 <Version>10.0</Version>
1311 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
1312 <VendorUrl>http://www.sun.com</VendorUrl>
1313 </Section> */
1314 xml::ElementNode *pelmAnnotationSection;
1315 if (enFormat == ovf::OVFVersion_0_9)
1316 {
1317 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1318 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1319 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
1320 }
1321 else
1322 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
1323
1324 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
1325 if (fProduct)
1326 pelmAnnotationSection->createChild("Product")->addContent(llProduct.back()->strVBoxCurrent);
1327 if (fVendor)
1328 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.back()->strVBoxCurrent);
1329 if (fVersion)
1330 pelmAnnotationSection->createChild("Version")->addContent(llVersion.back()->strVBoxCurrent);
1331 if (fProductUrl)
1332 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.back()->strVBoxCurrent);
1333 if (fVendorUrl)
1334 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.back()->strVBoxCurrent);
1335 }
1336
1337 // description
1338 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
1339 if (llDescription.size() &&
1340 !llDescription.back()->strVBoxCurrent.isEmpty())
1341 {
1342 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1343 <Info>A human-readable annotation</Info>
1344 <Annotation>Plan 9</Annotation>
1345 </Section> */
1346 xml::ElementNode *pelmAnnotationSection;
1347 if (enFormat == ovf::OVFVersion_0_9)
1348 {
1349 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1350 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1351 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
1352 }
1353 else
1354 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
1355
1356 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1357 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.back()->strVBoxCurrent);
1358 }
1359
1360 // license
1361 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->i_findByType(VirtualSystemDescriptionType_License);
1362 if (llLicense.size() &&
1363 !llLicense.back()->strVBoxCurrent.isEmpty())
1364 {
1365 /* <EulaSection>
1366 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1367 <License ovf:msgid="1">License terms can go in here.</License>
1368 </EulaSection> */
1369 xml::ElementNode *pelmEulaSection;
1370 if (enFormat == ovf::OVFVersion_0_9)
1371 {
1372 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1373 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1374 }
1375 else
1376 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1377
1378 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1379 pelmEulaSection->createChild("License")->addContent(llLicense.back()->strVBoxCurrent);
1380 }
1381
1382 // operating system
1383 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
1384 if (llOS.empty())
1385 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing OS type"));
1386 /* <OperatingSystemSection ovf:id="82">
1387 <Info>Guest Operating System</Info>
1388 <Description>Linux 2.6.x</Description>
1389 </OperatingSystemSection> */
1390 VirtualSystemDescriptionEntry *pvsdeOS = llOS.back();
1391 xml::ElementNode *pelmOperatingSystemSection;
1392 if (enFormat == ovf::OVFVersion_0_9)
1393 {
1394 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1395 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1396 }
1397 else
1398 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1399
1400 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1401 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1402 Utf8Str strOSDesc;
1403 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1404 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1405 // add the VirtualBox ostype in a custom tag in a different namespace
1406 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1407 pelmVBoxOSType->setAttribute("ovf:required", "false");
1408 pelmVBoxOSType->addContent(pvsdeOS->strVBoxCurrent);
1409
1410 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1411 xml::ElementNode *pelmVirtualHardwareSection;
1412 if (enFormat == ovf::OVFVersion_0_9)
1413 {
1414 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1415 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1416 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1417 }
1418 else
1419 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1420
1421 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1422
1423 /* <System>
1424 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1425 <vssd:ElementName>vmware</vssd:ElementName>
1426 <vssd:InstanceID>1</vssd:InstanceID>
1427 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1428 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1429 </System> */
1430 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1431
1432 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1433
1434 // <vssd:InstanceId>0</vssd:InstanceId>
1435 if (enFormat == ovf::OVFVersion_0_9)
1436 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1437 else // capitalization changed...
1438 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1439
1440 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1441 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1442 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1443 const char *pcszHardware = "virtualbox-2.2";
1444 if (enFormat == ovf::OVFVersion_0_9)
1445 // pretend to be vmware compatible then
1446 pcszHardware = "vmx-6";
1447 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1448
1449 // loop thru all description entries twice; once to write out all
1450 // devices _except_ disk images, and a second time to assign the
1451 // disk images; this is because disk images need to reference
1452 // IDE controllers, and we can't know their instance IDs without
1453 // assigning them first
1454
1455 uint32_t idIDEPrimaryController = 0;
1456 int32_t lIDEPrimaryControllerIndex = 0;
1457 uint32_t idIDESecondaryController = 0;
1458 int32_t lIDESecondaryControllerIndex = 0;
1459 uint32_t idSATAController = 0;
1460 int32_t lSATAControllerIndex = 0;
1461 uint32_t idSCSIController = 0;
1462 int32_t lSCSIControllerIndex = 0;
1463
1464 uint32_t ulInstanceID = 1;
1465
1466 uint32_t cDVDs = 0;
1467
1468 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1469 {
1470 int32_t lIndexThis = 0;
1471 for (vector<VirtualSystemDescriptionEntry>::const_iterator
1472 it = vsdescThis->m->maDescriptions.begin();
1473 it != vsdescThis->m->maDescriptions.end();
1474 ++it, ++lIndexThis)
1475 {
1476 const VirtualSystemDescriptionEntry &desc = *it;
1477
1478 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVBox=%s, strExtraConfig=%s\n",
1479 uLoop,
1480 desc.ulIndex,
1481 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1482 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1483 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1484 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1485 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1486 : Utf8StrFmt("%d", desc.type).c_str()),
1487 desc.strRef.c_str(),
1488 desc.strOvf.c_str(),
1489 desc.strVBoxCurrent.c_str(),
1490 desc.strExtraConfigCurrent.c_str()));
1491
1492 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1493 Utf8Str strResourceSubType;
1494
1495 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1496 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1497
1498 uint32_t ulParent = 0;
1499
1500 int32_t lVirtualQuantity = -1;
1501 Utf8Str strAllocationUnits;
1502
1503 int32_t lAddress = -1;
1504 int32_t lBusNumber = -1;
1505 int32_t lAddressOnParent = -1;
1506
1507 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1508 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1509 Utf8Str strHostResource;
1510
1511 uint64_t uTemp;
1512
1513 ovf::VirtualHardwareItem vhi;
1514 ovf::StorageItem si;
1515 ovf::EthernetPortItem epi;
1516
1517 switch (desc.type)
1518 {
1519 case VirtualSystemDescriptionType_CPU:
1520 /* <Item>
1521 <rasd:Caption>1 virtual CPU</rasd:Caption>
1522 <rasd:Description>Number of virtual CPUs</rasd:Description>
1523 <rasd:ElementName>virtual CPU</rasd:ElementName>
1524 <rasd:InstanceID>1</rasd:InstanceID>
1525 <rasd:ResourceType>3</rasd:ResourceType>
1526 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1527 </Item> */
1528 if (uLoop == 1)
1529 {
1530 strDescription = "Number of virtual CPUs";
1531 type = ovf::ResourceType_Processor; // 3
1532 desc.strVBoxCurrent.toInt(uTemp);
1533 lVirtualQuantity = (int32_t)uTemp;
1534 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool
1535 // won't eat the item
1536 }
1537 break;
1538
1539 case VirtualSystemDescriptionType_Memory:
1540 /* <Item>
1541 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1542 <rasd:Caption>256 MB of memory</rasd:Caption>
1543 <rasd:Description>Memory Size</rasd:Description>
1544 <rasd:ElementName>Memory</rasd:ElementName>
1545 <rasd:InstanceID>2</rasd:InstanceID>
1546 <rasd:ResourceType>4</rasd:ResourceType>
1547 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1548 </Item> */
1549 if (uLoop == 1)
1550 {
1551 strDescription = "Memory Size";
1552 type = ovf::ResourceType_Memory; // 4
1553 desc.strVBoxCurrent.toInt(uTemp);
1554 lVirtualQuantity = (int32_t)(uTemp / _1M);
1555 strAllocationUnits = "MegaBytes";
1556 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool
1557 // won't eat the item
1558 }
1559 break;
1560
1561 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1562 /* <Item>
1563 <rasd:Caption>ideController1</rasd:Caption>
1564 <rasd:Description>IDE Controller</rasd:Description>
1565 <rasd:InstanceId>5</rasd:InstanceId>
1566 <rasd:ResourceType>5</rasd:ResourceType>
1567 <rasd:Address>1</rasd:Address>
1568 <rasd:BusNumber>1</rasd:BusNumber>
1569 </Item> */
1570 if (uLoop == 1)
1571 {
1572 strDescription = "IDE Controller";
1573 type = ovf::ResourceType_IDEController; // 5
1574 strResourceSubType = desc.strVBoxCurrent;
1575
1576 if (!lIDEPrimaryControllerIndex)
1577 {
1578 // first IDE controller:
1579 strCaption = "ideController0";
1580 lAddress = 0;
1581 lBusNumber = 0;
1582 // remember this ID
1583 idIDEPrimaryController = ulInstanceID;
1584 lIDEPrimaryControllerIndex = lIndexThis;
1585 }
1586 else
1587 {
1588 // second IDE controller:
1589 strCaption = "ideController1";
1590 lAddress = 1;
1591 lBusNumber = 1;
1592 // remember this ID
1593 idIDESecondaryController = ulInstanceID;
1594 lIDESecondaryControllerIndex = lIndexThis;
1595 }
1596 }
1597 break;
1598
1599 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1600 /* <Item>
1601 <rasd:Caption>sataController0</rasd:Caption>
1602 <rasd:Description>SATA Controller</rasd:Description>
1603 <rasd:InstanceId>4</rasd:InstanceId>
1604 <rasd:ResourceType>20</rasd:ResourceType>
1605 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1606 <rasd:Address>0</rasd:Address>
1607 <rasd:BusNumber>0</rasd:BusNumber>
1608 </Item>
1609 */
1610 if (uLoop == 1)
1611 {
1612 strDescription = "SATA Controller";
1613 strCaption = "sataController0";
1614 type = ovf::ResourceType_OtherStorageDevice; // 20
1615 // it seems that OVFTool always writes these two, and since we can only
1616 // have one SATA controller, we'll use this as well
1617 lAddress = 0;
1618 lBusNumber = 0;
1619
1620 if ( desc.strVBoxCurrent.isEmpty() // AHCI is the default in VirtualBox
1621 || (!desc.strVBoxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1622 )
1623 strResourceSubType = "AHCI";
1624 else
1625 throw setError(VBOX_E_NOT_SUPPORTED,
1626 tr("Invalid config string \"%s\" in SATA controller"), desc.strVBoxCurrent.c_str());
1627
1628 // remember this ID
1629 idSATAController = ulInstanceID;
1630 lSATAControllerIndex = lIndexThis;
1631 }
1632 break;
1633
1634 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1635 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1636 /* <Item>
1637 <rasd:Caption>scsiController0</rasd:Caption>
1638 <rasd:Description>SCSI Controller</rasd:Description>
1639 <rasd:InstanceId>4</rasd:InstanceId>
1640 <rasd:ResourceType>6</rasd:ResourceType>
1641 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1642 <rasd:Address>0</rasd:Address>
1643 <rasd:BusNumber>0</rasd:BusNumber>
1644 </Item>
1645 */
1646 if (uLoop == 1)
1647 {
1648 strDescription = "SCSI Controller";
1649 strCaption = "scsiController0";
1650 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1651 // it seems that OVFTool always writes these two, and since we can only
1652 // have one SATA controller, we'll use this as well
1653 lAddress = 0;
1654 lBusNumber = 0;
1655
1656 if ( desc.strVBoxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1657 || (!desc.strVBoxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1658 )
1659 strResourceSubType = "lsilogic";
1660 else if (!desc.strVBoxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1661 strResourceSubType = "buslogic";
1662 else if (!desc.strVBoxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1663 strResourceSubType = "lsilogicsas";
1664 else
1665 throw setError(VBOX_E_NOT_SUPPORTED,
1666 tr("Invalid config string \"%s\" in SCSI/SAS controller"),
1667 desc.strVBoxCurrent.c_str());
1668
1669 // remember this ID
1670 idSCSIController = ulInstanceID;
1671 lSCSIControllerIndex = lIndexThis;
1672 }
1673 break;
1674
1675 case VirtualSystemDescriptionType_HardDiskImage:
1676 /* <Item>
1677 <rasd:Caption>disk1</rasd:Caption>
1678 <rasd:InstanceId>8</rasd:InstanceId>
1679 <rasd:ResourceType>17</rasd:ResourceType>
1680 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1681 <rasd:Parent>4</rasd:Parent>
1682 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1683 </Item> */
1684 if (uLoop == 2)
1685 {
1686 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1687 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1688
1689 strDescription = "Disk Image";
1690 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1691 type = ovf::ResourceType_HardDisk; // 17
1692
1693 // the following references the "<Disks>" XML block
1694 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1695
1696 // controller=<index>;channel=<c>
1697 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1698 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1699 int32_t lControllerIndex = -1;
1700 if (pos1 != Utf8Str::npos)
1701 {
1702 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1703 if (lControllerIndex == lIDEPrimaryControllerIndex)
1704 ulParent = idIDEPrimaryController;
1705 else if (lControllerIndex == lIDESecondaryControllerIndex)
1706 ulParent = idIDESecondaryController;
1707 else if (lControllerIndex == lSCSIControllerIndex)
1708 ulParent = idSCSIController;
1709 else if (lControllerIndex == lSATAControllerIndex)
1710 ulParent = idSATAController;
1711 }
1712 if (pos2 != Utf8Str::npos)
1713 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1714
1715 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1716 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex,
1717 ulParent, lAddressOnParent));
1718
1719 if ( !ulParent
1720 || lAddressOnParent == -1
1721 )
1722 throw setError(VBOX_E_NOT_SUPPORTED,
1723 tr("Missing or bad extra config string in hard disk image: \"%s\""),
1724 desc.strExtraConfigCurrent.c_str());
1725
1726 stack.mapDisks[strDiskID] = &desc;
1727
1728 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1729 //in the OVF description file.
1730 stack.mapDiskSequence.push_back(strDiskID);
1731 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1732 }
1733 break;
1734
1735 case VirtualSystemDescriptionType_Floppy:
1736 if (uLoop == 1)
1737 {
1738 strDescription = "Floppy Drive";
1739 strCaption = "floppy0"; // this is what OVFTool writes
1740 type = ovf::ResourceType_FloppyDrive; // 14
1741 lAutomaticAllocation = 0;
1742 lAddressOnParent = 0; // this is what OVFTool writes
1743 }
1744 break;
1745
1746 case VirtualSystemDescriptionType_CDROM:
1747 /* <Item>
1748 <rasd:Caption>cdrom1</rasd:Caption>
1749 <rasd:InstanceId>8</rasd:InstanceId>
1750 <rasd:ResourceType>15</rasd:ResourceType>
1751 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1752 <rasd:Parent>4</rasd:Parent>
1753 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1754 </Item> */
1755 if (uLoop == 2)
1756 {
1757 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1758 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDisks);
1759 ++cDVDs;
1760 strDescription = "CD-ROM Drive";
1761 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1762 type = ovf::ResourceType_CDDrive; // 15
1763 lAutomaticAllocation = 1;
1764
1765 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1766 if (desc.strVBoxCurrent.isNotEmpty() &&
1767 desc.skipIt == false)
1768 {
1769 // the following references the "<Disks>" XML block
1770 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1771 }
1772
1773 // controller=<index>;channel=<c>
1774 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1775 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1776 int32_t lControllerIndex = -1;
1777 if (pos1 != Utf8Str::npos)
1778 {
1779 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1780 if (lControllerIndex == lIDEPrimaryControllerIndex)
1781 ulParent = idIDEPrimaryController;
1782 else if (lControllerIndex == lIDESecondaryControllerIndex)
1783 ulParent = idIDESecondaryController;
1784 else if (lControllerIndex == lSCSIControllerIndex)
1785 ulParent = idSCSIController;
1786 else if (lControllerIndex == lSATAControllerIndex)
1787 ulParent = idSATAController;
1788 }
1789 if (pos2 != Utf8Str::npos)
1790 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1791
1792 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1793 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex,
1794 lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1795
1796 if ( !ulParent
1797 || lAddressOnParent == -1
1798 )
1799 throw setError(VBOX_E_NOT_SUPPORTED,
1800 tr("Missing or bad extra config string in DVD drive medium: \"%s\""),
1801 desc.strExtraConfigCurrent.c_str());
1802
1803 stack.mapDisks[strDiskID] = &desc;
1804
1805 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1806 //in the OVF description file.
1807 stack.mapDiskSequence.push_back(strDiskID);
1808 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1809 // there is no DVD drive map to update because it is
1810 // handled completely with this entry.
1811 }
1812 break;
1813
1814 case VirtualSystemDescriptionType_NetworkAdapter:
1815 /* <Item>
1816 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1817 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1818 <rasd:Connection>VM Network</rasd:Connection>
1819 <rasd:ElementName>VM network</rasd:ElementName>
1820 <rasd:InstanceID>3</rasd:InstanceID>
1821 <rasd:ResourceType>10</rasd:ResourceType>
1822 </Item> */
1823 if (uLoop == 2)
1824 {
1825 lAutomaticAllocation = 1;
1826 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1827 type = ovf::ResourceType_EthernetAdapter; // 10
1828 /* Set the hardware type to something useful.
1829 * To be compatible with vmware & others we set
1830 * PCNet32 for our PCNet types & E1000 for the
1831 * E1000 cards. */
1832 switch (desc.strVBoxCurrent.toInt32())
1833 {
1834 case NetworkAdapterType_Am79C970A:
1835 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1836#ifdef VBOX_WITH_E1000
1837 case NetworkAdapterType_I82540EM:
1838 case NetworkAdapterType_I82545EM:
1839 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1840#endif /* VBOX_WITH_E1000 */
1841 }
1842 strConnection = desc.strOvf;
1843
1844 stack.mapNetworks[desc.strOvf] = true;
1845 }
1846 break;
1847
1848 case VirtualSystemDescriptionType_USBController:
1849 /* <Item ovf:required="false">
1850 <rasd:Caption>usb</rasd:Caption>
1851 <rasd:Description>USB Controller</rasd:Description>
1852 <rasd:InstanceId>3</rasd:InstanceId>
1853 <rasd:ResourceType>23</rasd:ResourceType>
1854 <rasd:Address>0</rasd:Address>
1855 <rasd:BusNumber>0</rasd:BusNumber>
1856 </Item> */
1857 if (uLoop == 1)
1858 {
1859 strDescription = "USB Controller";
1860 strCaption = "usb";
1861 type = ovf::ResourceType_USBController; // 23
1862 lAddress = 0; // this is what OVFTool writes
1863 lBusNumber = 0; // this is what OVFTool writes
1864 }
1865 break;
1866
1867 case VirtualSystemDescriptionType_SoundCard:
1868 /* <Item ovf:required="false">
1869 <rasd:Caption>sound</rasd:Caption>
1870 <rasd:Description>Sound Card</rasd:Description>
1871 <rasd:InstanceId>10</rasd:InstanceId>
1872 <rasd:ResourceType>35</rasd:ResourceType>
1873 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1874 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1875 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1876 </Item> */
1877 if (uLoop == 1)
1878 {
1879 strDescription = "Sound Card";
1880 strCaption = "sound";
1881 type = ovf::ResourceType_SoundCard; // 35
1882 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1883 lAutomaticAllocation = 0;
1884 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1885 }
1886 break;
1887
1888 default: break; /* Shut up MSC. */
1889 }
1890
1891 if (type)
1892 {
1893 xml::ElementNode *pItem;
1894 xml::ElementNode *pItemHelper;
1895 RTCString itemElement;
1896 RTCString itemElementHelper;
1897
1898 if (enFormat == ovf::OVFVersion_2_0)
1899 {
1900 if(uLoop == 2)
1901 {
1902 if (desc.type == VirtualSystemDescriptionType_NetworkAdapter)
1903 {
1904 itemElement = "epasd:";
1905 pItem = pelmVirtualHardwareSection->createChild("EthernetPortItem");
1906 }
1907 else if (desc.type == VirtualSystemDescriptionType_CDROM ||
1908 desc.type == VirtualSystemDescriptionType_HardDiskImage)
1909 {
1910 itemElement = "sasd:";
1911 pItem = pelmVirtualHardwareSection->createChild("StorageItem");
1912 }
1913 else
1914 pItem = NULL;
1915 }
1916 else
1917 {
1918 itemElement = "rasd:";
1919 pItem = pelmVirtualHardwareSection->createChild("Item");
1920 }
1921 }
1922 else
1923 {
1924 itemElement = "rasd:";
1925 pItem = pelmVirtualHardwareSection->createChild("Item");
1926 }
1927
1928 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1929 // the elements from the rasd: namespace must be sorted by letter, and VMware
1930 // actually requires this as well (see public bug #6612)
1931
1932 if (lAddress != -1)
1933 {
1934 //pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1935 itemElementHelper = itemElement;
1936 pItemHelper = pItem->createChild(itemElementHelper.append("Address").c_str());
1937 pItemHelper->addContent(Utf8StrFmt("%d", lAddress));
1938 }
1939
1940 if (lAddressOnParent != -1)
1941 {
1942 //pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1943 itemElementHelper = itemElement;
1944 pItemHelper = pItem->createChild(itemElementHelper.append("AddressOnParent").c_str());
1945 pItemHelper->addContent(Utf8StrFmt("%d", lAddressOnParent));
1946 }
1947
1948 if (!strAllocationUnits.isEmpty())
1949 {
1950 //pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1951 itemElementHelper = itemElement;
1952 pItemHelper = pItem->createChild(itemElementHelper.append("AllocationUnits").c_str());
1953 pItemHelper->addContent(strAllocationUnits);
1954 }
1955
1956 if (lAutomaticAllocation != -1)
1957 {
1958 //pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1959 itemElementHelper = itemElement;
1960 pItemHelper = pItem->createChild(itemElementHelper.append("AutomaticAllocation").c_str());
1961 pItemHelper->addContent((lAutomaticAllocation) ? "true" : "false" );
1962 }
1963
1964 if (lBusNumber != -1)
1965 {
1966 if (enFormat == ovf::OVFVersion_0_9)
1967 {
1968 // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool
1969 //pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1970 itemElementHelper = itemElement;
1971 pItemHelper = pItem->createChild(itemElementHelper.append("BusNumber").c_str());
1972 pItemHelper->addContent(Utf8StrFmt("%d", lBusNumber));
1973 }
1974 }
1975
1976 if (!strCaption.isEmpty())
1977 {
1978 //pItem->createChild("rasd:Caption")->addContent(strCaption);
1979 itemElementHelper = itemElement;
1980 pItemHelper = pItem->createChild(itemElementHelper.append("Caption").c_str());
1981 pItemHelper->addContent(strCaption);
1982 }
1983
1984 if (!strConnection.isEmpty())
1985 {
1986 //pItem->createChild("rasd:Connection")->addContent(strConnection);
1987 itemElementHelper = itemElement;
1988 pItemHelper = pItem->createChild(itemElementHelper.append("Connection").c_str());
1989 pItemHelper->addContent(strConnection);
1990 }
1991
1992 if (!strDescription.isEmpty())
1993 {
1994 //pItem->createChild("rasd:Description")->addContent(strDescription);
1995 itemElementHelper = itemElement;
1996 pItemHelper = pItem->createChild(itemElementHelper.append("Description").c_str());
1997 pItemHelper->addContent(strDescription);
1998 }
1999
2000 if (!strCaption.isEmpty())
2001 {
2002 if (enFormat == ovf::OVFVersion_1_0)
2003 {
2004 //pItem->createChild("rasd:ElementName")->addContent(strCaption);
2005 itemElementHelper = itemElement;
2006 pItemHelper = pItem->createChild(itemElementHelper.append("ElementName").c_str());
2007 pItemHelper->addContent(strCaption);
2008 }
2009 }
2010
2011 if (!strHostResource.isEmpty())
2012 {
2013 //pItem->createChild("rasd:HostResource")->addContent(strHostResource);
2014 itemElementHelper = itemElement;
2015 pItemHelper = pItem->createChild(itemElementHelper.append("HostResource").c_str());
2016 pItemHelper->addContent(strHostResource);
2017 }
2018
2019 {
2020 // <rasd:InstanceID>1</rasd:InstanceID>
2021 itemElementHelper = itemElement;
2022 if (enFormat == ovf::OVFVersion_0_9)
2023 //pelmInstanceID = pItem->createChild("rasd:InstanceId");
2024 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceId").c_str());
2025 else
2026 //pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
2027 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceID").c_str());
2028
2029 pItemHelper->addContent(Utf8StrFmt("%d", ulInstanceID++));
2030 }
2031
2032 if (ulParent)
2033 {
2034 //pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
2035 itemElementHelper = itemElement;
2036 pItemHelper = pItem->createChild(itemElementHelper.append("Parent").c_str());
2037 pItemHelper->addContent(Utf8StrFmt("%d", ulParent));
2038 }
2039
2040 if (!strResourceSubType.isEmpty())
2041 {
2042 //pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
2043 itemElementHelper = itemElement;
2044 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceSubType").c_str());
2045 pItemHelper->addContent(strResourceSubType);
2046 }
2047
2048 {
2049 // <rasd:ResourceType>3</rasd:ResourceType>
2050 //pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
2051 itemElementHelper = itemElement;
2052 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceType").c_str());
2053 pItemHelper->addContent(Utf8StrFmt("%d", type));
2054 }
2055
2056 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2057 if (lVirtualQuantity != -1)
2058 {
2059 //pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2060 itemElementHelper = itemElement;
2061 pItemHelper = pItem->createChild(itemElementHelper.append("VirtualQuantity").c_str());
2062 pItemHelper->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2063 }
2064 }
2065 }
2066 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
2067
2068 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
2069 // under the vbox: namespace
2070 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
2071 // ovf:required="false" tells other OVF parsers that they can ignore this thing
2072 pelmVBoxMachine->setAttribute("ovf:required", "false");
2073 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
2074 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
2075
2076 // create an empty machine config
2077 // use the same settings version as the current VM settings file
2078 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(&vsdescThis->m->pMachine->i_getSettingsFileFull());
2079
2080 writeLock.release();
2081 try
2082 {
2083 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
2084 // fill the machine config
2085 vsdescThis->m->pMachine->i_copyMachineDataToSettings(*pConfig);
2086 pConfig->machineUserData.strName = strVMName;
2087
2088 // Apply export tweaks to machine settings
2089 bool fStripAllMACs = m->optListExport.contains(ExportOptions_StripAllMACs);
2090 bool fStripAllNonNATMACs = m->optListExport.contains(ExportOptions_StripAllNonNATMACs);
2091 if (fStripAllMACs || fStripAllNonNATMACs)
2092 {
2093 for (settings::NetworkAdaptersList::iterator
2094 it = pConfig->hardwareMachine.llNetworkAdapters.begin();
2095 it != pConfig->hardwareMachine.llNetworkAdapters.end();
2096 ++it)
2097 {
2098 settings::NetworkAdapter &nic = *it;
2099 if (fStripAllMACs || (fStripAllNonNATMACs && nic.mode != NetworkAttachmentType_NAT))
2100 nic.strMACAddress.setNull();
2101 }
2102 }
2103
2104 // write the machine config to the vbox:Machine element
2105 pConfig->buildMachineXML(*pelmVBoxMachine,
2106 settings::MachineConfigFile::BuildMachineXML_WriteVBoxVersionAttribute
2107 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
2108 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
2109 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
2110 pllElementsWithUuidAttributes);
2111 delete pConfig;
2112 }
2113 catch (...)
2114 {
2115 writeLock.acquire();
2116 delete pConfig;
2117 throw;
2118 }
2119 writeLock.acquire();
2120}
2121
2122/**
2123 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
2124 * and therefore runs on the OVF/OVA write worker thread.
2125 *
2126 * This runs in one context:
2127 *
2128 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl();
2129 *
2130 * @param pTask
2131 * @return
2132 */
2133HRESULT Appliance::i_writeFS(TaskOVF *pTask)
2134{
2135 LogFlowFuncEnter();
2136 LogFlowFunc(("ENTER appliance %p\n", this));
2137
2138 AutoCaller autoCaller(this);
2139 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2140
2141 HRESULT rc = S_OK;
2142
2143 // Lock the media tree early to make sure nobody else tries to make changes
2144 // to the tree. Also lock the IAppliance object for writing.
2145 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
2146 // Additional protect the IAppliance object, cause we leave the lock
2147 // when starting the disk export and we don't won't block other
2148 // callers on this lengthy operations.
2149 m->state = Data::ApplianceExporting;
2150
2151 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
2152 rc = i_writeFSOVF(pTask, multiLock);
2153 else
2154 rc = i_writeFSOVA(pTask, multiLock);
2155
2156 // reset the state so others can call methods again
2157 m->state = Data::ApplianceIdle;
2158
2159 LogFlowFunc(("rc=%Rhrc\n", rc));
2160 LogFlowFuncLeave();
2161 return rc;
2162}
2163
2164HRESULT Appliance::i_writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
2165{
2166 LogFlowFuncEnter();
2167
2168 /*
2169 * Create write-to-dir file system stream for the target directory.
2170 * This unifies the disk access with the TAR based OVA variant.
2171 */
2172 HRESULT hrc;
2173 int vrc;
2174 RTVFSFSSTREAM hVfsFss2Dir = NIL_RTVFSFSSTREAM;
2175 try
2176 {
2177 Utf8Str strTargetDir(pTask->locInfo.strPath);
2178 strTargetDir.stripFilename();
2179 vrc = RTVfsFsStrmToNormalDir(strTargetDir.c_str(), 0 /*fFlags*/, &hVfsFss2Dir);
2180 if (RT_SUCCESS(vrc))
2181 hrc = S_OK;
2182 else
2183 hrc = setErrorVrc(vrc, tr("Failed to open directory '%s' (%Rrc)"), strTargetDir.c_str(), vrc);
2184 }
2185 catch (std::bad_alloc &)
2186 {
2187 hrc = E_OUTOFMEMORY;
2188 }
2189 if (SUCCEEDED(hrc))
2190 {
2191 /*
2192 * Join i_writeFSOVA. On failure, delete (undo) anything we might
2193 * have written to the disk before failing.
2194 */
2195 hrc = i_writeFSImpl(pTask, writeLock, hVfsFss2Dir);
2196 if (FAILED(hrc))
2197 RTVfsFsStrmToDirUndo(hVfsFss2Dir);
2198 RTVfsFsStrmRelease(hVfsFss2Dir);
2199 }
2200
2201 LogFlowFuncLeave();
2202 return hrc;
2203}
2204
2205HRESULT Appliance::i_writeFSOVA(TaskOVF *pTask, AutoWriteLockBase &writeLock)
2206{
2207 LogFlowFuncEnter();
2208
2209 /*
2210 * Open the output file and attach a TAR creator to it.
2211 * The OVF 1.1.0 spec specifies the TAR format to be compatible with USTAR
2212 * according to POSIX 1003.1-2008. We use the 1988 spec here as it's the
2213 * only variant we currently implement.
2214 */
2215 HRESULT hrc;
2216 RTVFSIOSTREAM hVfsIosTar;
2217 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
2218 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2219 &hVfsIosTar);
2220 if (RT_SUCCESS(vrc))
2221 {
2222 RTVFSFSSTREAM hVfsFssTar;
2223 vrc = RTZipTarFsStreamToIoStream(hVfsIosTar, RTZIPTARFORMAT_USTAR, 0 /*fFlags*/, &hVfsFssTar);
2224 RTVfsIoStrmRelease(hVfsIosTar);
2225 if (RT_SUCCESS(vrc))
2226 {
2227 RTZipTarFsStreamSetFileMode(hVfsFssTar, 0660, 0440);
2228 RTZipTarFsStreamSetOwner(hVfsFssTar, VBOX_VERSION_MAJOR,
2229 pTask->enFormat == ovf::OVFVersion_0_9 ? "vboxovf09"
2230 : pTask->enFormat == ovf::OVFVersion_1_0 ? "vboxovf10"
2231 : pTask->enFormat == ovf::OVFVersion_2_0 ? "vboxovf20"
2232 : "vboxovf");
2233 RTZipTarFsStreamSetGroup(hVfsFssTar, VBOX_VERSION_MINOR,
2234 "vbox_v" RT_XSTR(VBOX_VERSION_MAJOR) "." RT_XSTR(VBOX_VERSION_MINOR) "."
2235 RT_XSTR(VBOX_VERSION_BUILD) "r" RT_XSTR(VBOX_SVN_REV));
2236
2237 hrc = i_writeFSImpl(pTask, writeLock, hVfsFssTar);
2238 RTVfsFsStrmRelease(hVfsFssTar);
2239 }
2240 else
2241 hrc = setErrorVrc(vrc, tr("Failed create TAR creator for '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2242
2243 /* Delete the OVA on failure. */
2244 if (FAILED(hrc))
2245 RTFileDelete(pTask->locInfo.strPath.c_str());
2246 }
2247 else
2248 hrc = setErrorVrc(vrc, tr("Failed to open '%s' for writing (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2249
2250 LogFlowFuncLeave();
2251 return hrc;
2252}
2253
2254/**
2255 * Upload the image to the OCI Storage service, next import the
2256 * uploaded image into internal OCI image format and launch an
2257 * instance with this image in the OCI Compute service.
2258 */
2259HRESULT Appliance::i_writeFSOCI(TaskOCI *pTask)
2260{
2261 LogFlowFuncEnter();
2262 HRESULT hrc = S_OK;
2263
2264 return hrc;
2265}
2266
2267/**
2268 * Writes the Oracle Public Cloud appliance.
2269 *
2270 * It expect raw disk images inside a gzipped tarball. We enable sparse files
2271 * to save diskspace on the target host system.
2272 */
2273HRESULT Appliance::i_writeFSOPC(TaskOPC *pTask)
2274{
2275 LogFlowFuncEnter();
2276 HRESULT hrc = S_OK;
2277
2278 // Lock the media tree early to make sure nobody else tries to make changes
2279 // to the tree. Also lock the IAppliance object for writing.
2280 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
2281 // Additional protect the IAppliance object, cause we leave the lock
2282 // when starting the disk export and we don't won't block other
2283 // callers on this lengthy operations.
2284 m->state = Data::ApplianceExporting;
2285
2286 /*
2287 * We're duplicating parts of i_writeFSImpl here because that's simpler
2288 * and creates less spaghetti code.
2289 */
2290 std::list<Utf8Str> lstTarballs;
2291
2292 /*
2293 * Use i_buildXML to build a stack of disk images. We don't care about the XML doc here.
2294 */
2295 XMLStack stack;
2296 {
2297 xml::Document doc;
2298 i_buildXML(multiLock, doc, stack, pTask->locInfo.strPath, ovf::OVFVersion_2_0);
2299 }
2300
2301 /*
2302 * Process the disk images.
2303 */
2304 unsigned cTarballs = 0;
2305 for (list<Utf8Str>::const_iterator it = stack.mapDiskSequence.begin();
2306 it != stack.mapDiskSequence.end();
2307 ++it)
2308 {
2309 const Utf8Str &strDiskID = *it;
2310 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2311 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent; // where the VBox image is
2312
2313 /*
2314 * Some skipping.
2315 */
2316 if (pDiskEntry->skipIt)
2317 continue;
2318
2319 /* Skip empty media (DVD-ROM, floppy). */
2320 if (strSrcFilePath.isEmpty())
2321 continue;
2322
2323 /* Only deal with harddisk and DVD-ROMs, skip any floppies for now. */
2324 if ( pDiskEntry->type != VirtualSystemDescriptionType_HardDiskImage
2325 && pDiskEntry->type != VirtualSystemDescriptionType_CDROM)
2326 continue;
2327
2328 /*
2329 * Locate the Medium object for this entry (by location/path).
2330 */
2331 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2332 ComObjPtr<Medium> ptrSourceDisk;
2333 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2334 hrc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true /*aSetError*/, &ptrSourceDisk);
2335 else
2336 hrc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD, NULL /*aId*/, strSrcFilePath,
2337 true /*aSetError*/, &ptrSourceDisk);
2338 if (FAILED(hrc))
2339 break;
2340 if (strSrcFilePath.isEmpty())
2341 continue;
2342
2343 /*
2344 * Figure out the names.
2345 */
2346
2347 /* The name inside the tarball. Replace the suffix of harddisk images with ".img". */
2348 Utf8Str strInsideName = pDiskEntry->strOvf;
2349 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2350 strInsideName.stripSuffix().append(".img");
2351
2352 /* The first tarball we create uses the specified name. Subsequent
2353 takes the name from the disk entry or something. */
2354 Utf8Str strTarballPath = pTask->locInfo.strPath;
2355 if (cTarballs > 0)
2356 {
2357 strTarballPath.stripFilename().append(RTPATH_SLASH_STR).append(pDiskEntry->strOvf);
2358 const char *pszExt = RTPathSuffix(pDiskEntry->strOvf.c_str());
2359 if (pszExt && pszExt[0] == '.' && pszExt[1] != '\0')
2360 {
2361 strTarballPath.stripSuffix();
2362 if (pDiskEntry->type != VirtualSystemDescriptionType_HardDiskImage)
2363 strTarballPath.append("_").append(&pszExt[1]);
2364 }
2365 strTarballPath.append(".tar.gz");
2366 }
2367 cTarballs++;
2368
2369 /*
2370 * Create the tar output stream.
2371 */
2372 RTVFSIOSTREAM hVfsIosFile;
2373 int vrc = RTVfsIoStrmOpenNormal(strTarballPath.c_str(),
2374 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2375 &hVfsIosFile);
2376 if (RT_SUCCESS(vrc))
2377 {
2378 RTVFSIOSTREAM hVfsIosGzip = NIL_RTVFSIOSTREAM;
2379 vrc = RTZipGzipCompressIoStream(hVfsIosFile, 0 /*fFlags*/, 6 /*uLevel*/, &hVfsIosGzip);
2380 RTVfsIoStrmRelease(hVfsIosFile);
2381
2382 /** @todo insert I/O thread here between gzip and the tar creator. Needs
2383 * implementing. */
2384
2385 RTVFSFSSTREAM hVfsFssTar = NIL_RTVFSFSSTREAM;
2386 if (RT_SUCCESS(vrc))
2387 vrc = RTZipTarFsStreamToIoStream(hVfsIosGzip, RTZIPTARFORMAT_GNU, RTZIPTAR_C_SPARSE, &hVfsFssTar);
2388 RTVfsIoStrmRelease(hVfsIosGzip);
2389 if (RT_SUCCESS(vrc))
2390 {
2391 RTZipTarFsStreamSetFileMode(hVfsFssTar, 0660, 0440);
2392 RTZipTarFsStreamSetOwner(hVfsFssTar, VBOX_VERSION_MAJOR, "vboxopc10");
2393 RTZipTarFsStreamSetGroup(hVfsFssTar, VBOX_VERSION_MINOR,
2394 "vbox_v" RT_XSTR(VBOX_VERSION_MAJOR) "." RT_XSTR(VBOX_VERSION_MINOR) "."
2395 RT_XSTR(VBOX_VERSION_BUILD) "r" RT_XSTR(VBOX_SVN_REV));
2396
2397 /*
2398 * Let the Medium code do the heavy work.
2399 *
2400 * The exporting requests a lock on the media tree. So temporarily
2401 * leave the appliance lock.
2402 */
2403 multiLock.release();
2404
2405 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%Rbn'"), strTarballPath.c_str()).raw(),
2406 pDiskEntry->ulSizeMB); // operation's weight, as set up
2407 // with the IProgress originally
2408 hrc = ptrSourceDisk->i_addRawToFss(strInsideName.c_str(), m->m_pSecretKeyStore, hVfsFssTar,
2409 pTask->pProgress, true /*fSparse*/);
2410
2411 multiLock.acquire();
2412 if (SUCCEEDED(hrc))
2413 {
2414 /*
2415 * Complete and close the tarball.
2416 */
2417 vrc = RTVfsFsStrmEnd(hVfsFssTar);
2418 RTVfsFsStrmRelease(hVfsFssTar);
2419 hVfsFssTar = NIL_RTVFSFSSTREAM;
2420 if (RT_SUCCESS(vrc))
2421 {
2422 /* Remember the tarball name for cleanup. */
2423 try
2424 {
2425 lstTarballs.push_back(strTarballPath.c_str());
2426 strTarballPath.setNull();
2427 }
2428 catch (std::bad_alloc &)
2429 { hrc = E_OUTOFMEMORY; }
2430 }
2431 else
2432 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc,
2433 tr("Error completing TAR file '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2434 }
2435 }
2436 else
2437 hrc = setErrorVrc(vrc, tr("Failed to TAR creator instance for '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2438
2439 if (FAILED(hrc) && strTarballPath.isNotEmpty())
2440 RTFileDelete(strTarballPath.c_str());
2441 }
2442 else
2443 hrc = setErrorVrc(vrc, tr("Failed to create '%s' (%Rrc)"), strTarballPath.c_str(), vrc);
2444 if (FAILED(hrc))
2445 break;
2446 }
2447
2448 /*
2449 * Delete output files on failure.
2450 */
2451 if (FAILED(hrc))
2452 for (list<Utf8Str>::const_iterator it = lstTarballs.begin(); it != lstTarballs.end(); ++it)
2453 RTFileDelete(it->c_str());
2454
2455 // reset the state so others can call methods again
2456 m->state = Data::ApplianceIdle;
2457
2458 LogFlowFuncLeave();
2459 return hrc;
2460
2461}
2462
2463HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase &writeLock, RTVFSFSSTREAM hVfsFssDst)
2464{
2465 LogFlowFuncEnter();
2466
2467 HRESULT rc = S_OK;
2468 int vrc;
2469 try
2470 {
2471 // the XML stack contains two maps for disks and networks, which allows us to
2472 // a) have a list of unique disk names (to make sure the same disk name is only added once)
2473 // and b) keep a list of all networks
2474 XMLStack stack;
2475 // Scope this to free the memory as soon as this is finished
2476 {
2477 /* Construct the OVF name. */
2478 Utf8Str strOvfFile(pTask->locInfo.strPath);
2479 strOvfFile.stripPath().stripSuffix().append(".ovf");
2480
2481 /* Render a valid ovf document into a memory buffer. The unknown
2482 version upgrade relates to the OPC hack up in Appliance::write(). */
2483 xml::Document doc;
2484 i_buildXML(writeLock, doc, stack, pTask->locInfo.strPath,
2485 pTask->enFormat != ovf::OVFVersion_unknown ? pTask->enFormat : ovf::OVFVersion_2_0);
2486
2487 void *pvBuf = NULL;
2488 size_t cbSize = 0;
2489 xml::XmlMemWriter writer;
2490 writer.write(doc, &pvBuf, &cbSize);
2491 if (RT_UNLIKELY(!pvBuf))
2492 throw setError(VBOX_E_FILE_ERROR, tr("Could not create OVF file '%s'"), strOvfFile.c_str());
2493
2494 /* Write the ovf file to "disk". */
2495 rc = i_writeBufferToFile(hVfsFssDst, strOvfFile.c_str(), pvBuf, cbSize);
2496 if (FAILED(rc))
2497 throw rc;
2498 }
2499
2500 // We need a proper format description
2501 ComObjPtr<MediumFormat> formatTemp;
2502
2503 ComObjPtr<MediumFormat> format;
2504 // Scope for the AutoReadLock
2505 {
2506 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2507 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2508 // We are always exporting to VMDK stream optimized for now
2509 formatTemp = pSysProps->i_mediumFormatFromExtension("iso");
2510
2511 format = pSysProps->i_mediumFormat("VMDK");
2512 if (format.isNull())
2513 throw setError(VBOX_E_NOT_SUPPORTED,
2514 tr("Invalid medium storage format"));
2515 }
2516
2517 // Finally, write out the disks!
2518 //use the list stack.mapDiskSequence where the disks were put as the "VirtualSystem"s had been placed
2519 //in the OVF description file. I.e. we have one "VirtualSystem" in the OVF file, we extract all disks
2520 //attached to it. And these disks are stored in the stack.mapDiskSequence. Next we shift to the next
2521 //"VirtualSystem" and repeat the operation.
2522 //And here we go through the list and extract all disks in the same sequence
2523 for (list<Utf8Str>::const_iterator
2524 it = stack.mapDiskSequence.begin();
2525 it != stack.mapDiskSequence.end();
2526 ++it)
2527 {
2528 const Utf8Str &strDiskID = *it;
2529 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2530
2531 // source path: where the VBox image is
2532 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
2533
2534 //skip empty Medium. In common, It's may be empty CD/DVD
2535 if (strSrcFilePath.isEmpty() ||
2536 pDiskEntry->skipIt == true)
2537 continue;
2538
2539 // Do NOT check here whether the file exists. findHardDisk will
2540 // figure that out, and filesystem-based tests are simply wrong
2541 // in the general case (think of iSCSI).
2542
2543 // clone the disk:
2544 ComObjPtr<Medium> pSourceDisk;
2545
2546 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2547
2548 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2549 {
2550 rc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2551 if (FAILED(rc)) throw rc;
2552 }
2553 else//may be CD or DVD
2554 {
2555 rc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD,
2556 NULL,
2557 strSrcFilePath,
2558 true,
2559 &pSourceDisk);
2560 if (FAILED(rc)) throw rc;
2561 }
2562
2563 Bstr uuidSource;
2564 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2565 if (FAILED(rc)) throw rc;
2566 Guid guidSource(uuidSource);
2567
2568 // output filename
2569 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2570
2571 // target path needs to be composed from where the output OVF is
2572 const Utf8Str &strTargetFilePath = strTargetFileNameOnly;
2573
2574 // The exporting requests a lock on the media tree. So leave our lock temporary.
2575 writeLock.release();
2576 try
2577 {
2578 // advance to the next operation
2579 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"),
2580 RTPathFilename(strTargetFilePath.c_str())).raw(),
2581 pDiskEntry->ulSizeMB); // operation's weight, as set up
2582 // with the IProgress originally
2583
2584 // create a flat copy of the source disk image
2585 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2586 {
2587 /*
2588 * Export a disk image.
2589 */
2590 /* For compressed VMDK fun, we let i_exportFile produce the image bytes. */
2591 RTVFSIOSTREAM hVfsIosDst;
2592 vrc = RTVfsFsStrmPushFile(hVfsFssDst, strTargetFilePath.c_str(), UINT64_MAX,
2593 NULL /*paObjInfo*/, 0 /*cObjInfo*/, RTVFSFSSTRM_PUSH_F_STREAM, &hVfsIosDst);
2594 if (RT_FAILURE(vrc))
2595 throw setErrorVrc(vrc, tr("RTVfsFsStrmPushFile failed for '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2596 hVfsIosDst = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosDst, strTargetFilePath.c_str(),
2597 false /*fRead*/);
2598 if (hVfsIosDst == NIL_RTVFSIOSTREAM)
2599 throw setError(E_FAIL, "i_manifestSetupDigestCalculationForGivenIoStream(%s)", strTargetFilePath.c_str());
2600
2601 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2602 format,
2603 MediumVariant_VmdkStreamOptimized,
2604 m->m_pSecretKeyStore,
2605 hVfsIosDst,
2606 pTask->pProgress);
2607 RTVfsIoStrmRelease(hVfsIosDst);
2608 }
2609 else
2610 {
2611 /*
2612 * Copy CD/DVD/floppy image.
2613 */
2614 Assert(pDiskEntry->type == VirtualSystemDescriptionType_CDROM);
2615 rc = pSourceDisk->i_addRawToFss(strTargetFilePath.c_str(), m->m_pSecretKeyStore, hVfsFssDst,
2616 pTask->pProgress, false /*fSparse*/);
2617 }
2618 if (FAILED(rc)) throw rc;
2619 }
2620 catch (HRESULT rc3)
2621 {
2622 writeLock.acquire();
2623 /// @todo file deletion on error? If not, we can remove that whole try/catch block.
2624 throw rc3;
2625 }
2626 // Finished, lock again (so nobody mess around with the medium tree
2627 // in the meantime)
2628 writeLock.acquire();
2629 }
2630
2631 if (m->fManifest)
2632 {
2633 // Create & write the manifest file
2634 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
2635 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2636 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2637 m->ulWeightForManifestOperation); // operation's weight, as set up
2638 // with the IProgress originally);
2639 /* Create a memory I/O stream and write the manifest to it. */
2640 RTVFSIOSTREAM hVfsIosManifest;
2641 vrc = RTVfsMemIoStrmCreate(NIL_RTVFSIOSTREAM, _1K, &hVfsIosManifest);
2642 if (RT_FAILURE(vrc))
2643 throw setErrorVrc(vrc, tr("RTVfsMemIoStrmCreate failed (%Rrc)"), vrc);
2644 if (m->hOurManifest != NIL_RTMANIFEST) /* In case it's empty. */
2645 vrc = RTManifestWriteStandard(m->hOurManifest, hVfsIosManifest);
2646 if (RT_SUCCESS(vrc))
2647 {
2648 /* Rewind the stream and add it to the output. */
2649 size_t cbIgnored;
2650 vrc = RTVfsIoStrmReadAt(hVfsIosManifest, 0 /*offset*/, &cbIgnored, 0, true /*fBlocking*/, &cbIgnored);
2651 if (RT_SUCCESS(vrc))
2652 {
2653 RTVFSOBJ hVfsObjManifest = RTVfsObjFromIoStream(hVfsIosManifest);
2654 vrc = RTVfsFsStrmAdd(hVfsFssDst, strMfFileName.c_str(), hVfsObjManifest, 0 /*fFlags*/);
2655 if (RT_SUCCESS(vrc))
2656 rc = S_OK;
2657 else
2658 rc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for the manifest (%Rrc)"), vrc);
2659 }
2660 else
2661 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2662 }
2663 else
2664 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2665 RTVfsIoStrmRelease(hVfsIosManifest);
2666 if (FAILED(rc))
2667 throw rc;
2668 }
2669 }
2670 catch (RTCError &x) // includes all XML exceptions
2671 {
2672 rc = setError(VBOX_E_FILE_ERROR,
2673 x.what());
2674 }
2675 catch (HRESULT aRC)
2676 {
2677 rc = aRC;
2678 }
2679
2680 LogFlowFunc(("rc=%Rhrc\n", rc));
2681 LogFlowFuncLeave();
2682
2683 return rc;
2684}
2685
2686
2687/**
2688 * Writes a memory buffer to a file in the output file system stream.
2689 *
2690 * @returns COM status code.
2691 * @param hVfsFssDst The file system stream to add the file to.
2692 * @param pszFilename The file name (w/ path if desired).
2693 * @param pvContent Pointer to buffer containing the file content.
2694 * @param cbContent Size of the content.
2695 */
2696HRESULT Appliance::i_writeBufferToFile(RTVFSFSSTREAM hVfsFssDst, const char *pszFilename, const void *pvContent, size_t cbContent)
2697{
2698 /*
2699 * Create a VFS file around the memory, converting it to a base VFS object handle.
2700 */
2701 HRESULT hrc;
2702 RTVFSIOSTREAM hVfsIosSrc;
2703 int vrc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pvContent, cbContent, &hVfsIosSrc);
2704 if (RT_SUCCESS(vrc))
2705 {
2706 hVfsIosSrc = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosSrc, pszFilename);
2707 AssertReturn(hVfsIosSrc != NIL_RTVFSIOSTREAM,
2708 setErrorVrc(vrc, "i_manifestSetupDigestCalculationForGivenIoStream"));
2709
2710 RTVFSOBJ hVfsObj = RTVfsObjFromIoStream(hVfsIosSrc);
2711 RTVfsIoStrmRelease(hVfsIosSrc);
2712 AssertReturn(hVfsObj != NIL_RTVFSOBJ, E_FAIL);
2713
2714 /*
2715 * Add it to the stream.
2716 */
2717 vrc = RTVfsFsStrmAdd(hVfsFssDst, pszFilename, hVfsObj, 0);
2718 RTVfsObjRelease(hVfsObj);
2719 if (RT_SUCCESS(vrc))
2720 hrc = S_OK;
2721 else
2722 hrc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for '%s' (%Rrc)"), pszFilename, vrc);
2723 }
2724 else
2725 hrc = setErrorVrc(vrc, "RTVfsIoStrmFromBuffer");
2726 return hrc;
2727}
2728
Note: See TracBrowser for help on using the repository browser.

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