MediumImpl.cpp revision 13d7da5a8024cf0b129e07b522d434287013a0d9
/* $Id$ */
/** @file
*
* VirtualBox COM class implementation
*/
/*
* Copyright (C) 2008-2009 Sun Microsystems, Inc.
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
#include "MediumImpl.h"
#include "ProgressImpl.h"
#include "SystemPropertiesImpl.h"
#include "VirtualBoxImpl.h"
#include "Logging.h"
#include <VBox/settings.h>
#include <algorithm>
////////////////////////////////////////////////////////////////////////////////
//
// Medium data definition
//
////////////////////////////////////////////////////////////////////////////////
/** Describes how a machine refers to this image. */
struct BackRef
{
/** Equality predicate for stdc++. */
{
bool operator()(const argument_type &aThat) const
{
}
};
: machineId(aMachineId),
{
if (!aSnapshotId.isEmpty())
}
bool fInCurState : 1;
};
{
Data()
size(0),
readers(0),
queryInfoRunning(false),
logicalSize(0),
autoReset(false),
setImageId(false),
setParentId(false),
implicit(false),
{}
bool queryInfoRunning : 1;
/** the following members are invalid after changing UUID on open */
bool implicit : 1;
};
////////////////////////////////////////////////////////////////////////////////
//
// Globals
//
////////////////////////////////////////////////////////////////////////////////
/**
* Asynchronous task thread parameter bucket.
*
* Note that instances of this class must be created using new() because the
* task thread function will delete them when the task is complete!
*
* @note The constructor of this class adds a caller on the managed Medium
* object which is automatically released upon destruction.
*/
{
enum Operation { CreateBase,
};
/** Where to save the result when executed using #runNow(). */
{}
~Task();
{
}
{
d.parentDisk = aParent;
if (aParent)
{
}
}
{
}
{
}
{
}
struct Data
{
/* CreateBase */
/* CreateBase, CreateDiff, Clone */
/* CreateDiff, Clone */
/* Clone */
/** Media to open, in {parent,child} order */
/** Media which are parent of target, in {parent,child} order */
/** The to-be parent medium object */
/* Merge */
/** Media to merge, in {parent,child} order */
/* Compact */
/** Media to open, in {parent,child} order */
}
d;
protected:
// SupportErrorInfoBase interface
};
{
/* remove callers added by setData() */
d.target->releaseCaller();
}
/**
* Starts a new thread driven by the Medium::taskThread() function and passes
* this Task instance as an argument.
*
* Note that if this method returns success, this Task object becomes an ownee
* of the started thread and will be automatically deleted when the thread
* terminates.
*
* @note When the task is executed by this method, IProgress::notifyComplete()
* is automatically called for the progress object associated with this
* task when the task is finished to signal the operation completion for
* other threads asynchronously waiting for it.
*/
{
"Medium::Task");
("Could not create Medium::Task thread (%Rrc)\n", vrc),
E_FAIL);
return S_OK;
}
/**
* Runs Medium::taskThread() by passing it this Task instance as an argument
* on the current thread instead of creating a new one.
*
* This call implies that it is made on another temporary thread created for
* some asynchronous task. Avoid calling it from a normal thread since the task
* operatinos are potentially lengthy and will block the calling thread in this
* case.
*
* Note that this Task object will be deleted by taskThread() when this method
* returns!
*
* @note When the task is executed by this method, IProgress::notifyComplete()
* is not called for the progress object associated with this task when
* the task is finished. Instead, the result of the operation is returned
* by this method directly and it's the caller's responsibility to
* complete the progress object in this case.
*/
{
/* NIL_RTTHREAD indicates synchronous call. */
return m_rc;
}
////////////////////////////////////////////////////////////////////////////////
//
// Merge chain class
//
////////////////////////////////////////////////////////////////////////////////
/**
* Helper class for merge operations.
*
* @note It is assumed that when modifying methods of this class are called,
* Medium::getTreeLock() is held in read mode.
*/
public com::SupportErrorInfoBase
{
public:
~MergeChain()
{
{
(*it)->releaseCaller();
}
{
else
(*it)->releaseCaller();
}
mParent->releaseCaller();
}
{
if (mForward)
{
{
aMedium->releaseCaller();
return rc;
}
}
/* We have to fetch the state with the COM method, cause it's possible
that the medium isn't fully initialized yet. */
/* go to Deleting */
switch (m)
{
case MediumState_Created:
break;
default:
aMedium->releaseCaller();
return aMedium->setStateError();
}
if (mForward)
{
/* we will need parent to reparent target */
{
}
}
else
{
/* we will need to reparent children */
++it)
{
{
pMedium->releaseCaller();
return rc;
}
}
}
return S_OK;
}
{
if (!mForward)
{
{
aMedium->releaseCaller();
return rc;
}
}
/* go to LockedWrite */
{
aMedium->releaseCaller();
return rc;
}
return S_OK;
}
{
{
aMedium->releaseCaller();
return rc;
}
/* go to Deleting */
{
case MediumState_Created:
break;
default:
aMedium->releaseCaller();
return aMedium->setStateError();
}
return S_OK;
}
protected:
// SupportErrorInfoBase interface
private:
bool aImmutable)
{
if (aChildren)
{
/* not going to multi-merge as it's too expensive */
{
tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
}
}
if (aAttachments && !mIgnoreAttachments)
{
tr("Medium '%s' is attached to %d virtual machines"),
}
if (aImmutable)
{
tr("Medium '%s' is immutable"),
}
return S_OK;
}
/** true if forward merge, false if backward */
bool mForward : 1;
/** true to not perform attachment checks */
bool mIgnoreAttachments : 1;
/** Parent of the source when forward merge (if any) */
/** Children of the source when backward merge (if any) */
};
////////////////////////////////////////////////////////////////////////////////
//
// ImageChain class
//
////////////////////////////////////////////////////////////////////////////////
/**
* Helper class for image operations involving the entire parent chain.
*
* @note It is assumed that when modifying methods of this class are called,
* Medium::getTreeLock() is held in read mode.
*/
public com::SupportErrorInfoBase
{
public:
ImageChain() {}
~ImageChain()
{
/* empty? */
{
last--;
{
{
}
else
{
}
(*it)->releaseCaller();
}
}
}
{
return S_OK;
}
{
/* Lock all disks in the chain in {parent, child} order,
* and make sure they are accessible. */
/// @todo code duplication with SessionMachine::lockMedia, see below
{
/* accessibility check must be first, otherwise locking
* interferes with getting the medium state. */
if (mediumState == MediumState_Inaccessible)
{
if (mediumState == MediumState_Inaccessible)
{
/* collect multiple errors */
/* be in sync with Medium::setStateError() */
tr("Medium '%ls' is not accessible. %ls"),
}
}
}
return S_OK;
}
{
/* Lock all disks in the chain in {parent, child} order,
* and make sure they are accessible. */
/// @todo code duplication with SessionMachine::lockMedia, see below
last--;
{
/* accessibility check must be first, otherwise locking
* interferes with getting the medium state. */
if (mediumState == MediumState_Inaccessible)
{
if (mediumState == MediumState_Inaccessible)
{
/* collect multiple errors */
/* be in sync with Medium::setStateError() */
tr("Medium '%ls' is not accessible. %ls"),
}
}
else
}
return S_OK;
}
protected:
// SupportErrorInfoBase interface
private:
};
////////////////////////////////////////////////////////////////////////////////
//
// Medium constructor / destructor
//
////////////////////////////////////////////////////////////////////////////////
{
m = new Data;
/* Initialize the callbacks of the VD error interface */
/* Initialize the callbacks of the VD config interface */
/* Initialize the callbacks of the VD TCP interface (we always use the host
* IP stack for now) */
/* Initialize the per-disk interface chain */
int vrc;
"Medium::vdInterfaceError",
&m->vdIfCallsError, this, &m->vdDiskIfaces);
"Medium::vdInterfaceConfig",
&m->vdIfCallsConfig, this, &m->vdDiskIfaces);
"Medium::vdInterfaceTcpNet",
&m->vdIfCallsTcpNet, this, &m->vdDiskIfaces);
return S_OK;
}
void Medium::FinalRelease()
{
uninit();
delete m;
}
/**
* Initializes the hard disk object without creating or opening an associated
* storage unit.
*
* For hard disks that don't have the VD_CAP_CREATE_FIXED or
* VD_CAP_CREATE_DYNAMIC capability (and therefore cannot be created or deleted
* with the means of VirtualBox) the associated storage unit is assumed to be
* ready for use so the state of the hard disk object will be set to Created.
*
* @param aVirtualBox VirtualBox object.
* @param aLocation Storage unit location.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* share VirtualBox weakly (parent remains NULL so far) */
/* register with VirtualBox early, since uninit() will
* unconditionally unregister on failure */
aVirtualBox->addDependentChild(this);
/* no storage yet */
m->state = MediumState_NotCreated;
/* cannot be a host drive */
/* No storage unit is created yet, no need to queryInfo() */
{
}
else
{
/// @todo later we may want to use a pfnComposeLocation backend info
/// callback to generate a well-formed location value (based on the hard
/// disk properties we have) rather than allowing each caller to invent
/// its own (pseudo-)location.
}
if (!(m->formatObj->capabilities() &
{
/* storage for hard disks of this format can neither be explicitly
* created by VirtualBox nor deleted, so we place the hard disk to
* Created state here and also add it to the registry */
m->state = MediumState_Created;
/// @todo later we may want to use a pfnIsConfigSufficient backend info
/// callback that would tell us when we have enough properties to work
/// with the hard disk and this information could be used to actually
/// move such hard disks from NotCreated to Created state. Instead of
/// pfnIsConfigSufficient we can use MediumFormat property
/// descriptions to see which properties are mandatory
}
/* Confirm a successful initialization when it's the case */
return rc;
}
/**
* Initializes the medium object by opening the storage unit at the specified
* location. The enOpenMode parameter defines whether the image will be opened
*
* Note that the UUID, format and the parent of this medium will be
* determined when reading the medium storage unit, unless new values are
* specified by the parameters. If the detected or set parent is
* not known to VirtualBox, then this method will fail.
*
* @param aVirtualBox VirtualBox object.
* @param aLocation Storage unit location.
* @param aDeviceType Device type of medium.
* @param aSetImageId Whether to set the image UUID or not.
* @param aImageId New image UUID if @aSetId is true. Empty string means
* create a new UUID, and a zero UUID is invalid.
* @param aSetParentId Whether to set the parent UUID or not.
* @param aParentId New parent UUID if @aSetParentId is true. Empty string
* means create a new UUID, and a zero UUID is valid.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* share VirtualBox weakly (parent remains NULL so far) */
/* register with VirtualBox early, since uninit() will
* unconditionally unregister on failure */
aVirtualBox->addDependentChild(this);
/* there must be a storage unit */
m->state = MediumState_Created;
/* remember device type for correct unregistering later */
m->devType = aDeviceType;
/* cannot be a host drive */
/* remember the open mode (defaults to ReadWrite) */
m->hddOpenMode = enOpenMode;
if (aDeviceType == DeviceType_HardDisk)
else
/* save the new uuid values, will be used by queryInfo() */
m->setImageId = aSetImageId;
m->setParentId = aSetParentId;
/* get all the information about the medium from the storage unit */
{
/* if the storage unit is not accessible, it's not acceptable for the
* newly opened media so convert this into an error */
if (m->state == MediumState_Inaccessible)
{
}
else
{
/* storage format must be detected by queryInfo() if the medium is accessible */
}
}
/* Confirm a successful initialization when it's the case */
return rc;
}
/**
* Initializes the medium object by loading its data from the given settings
*
* @param aVirtualBox VirtualBox object.
* @param aParent Parent medium disk or NULL for a root (base) medium.
* @param aDeviceType Device type of the medium.
* @param aNode Configuration settings.
*
* @note Locks VirtualBox lock for writing, getTreeLock() for writing.
*/
{
using namespace settings;
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* share VirtualBox and parent weakly */
/* register with VirtualBox/parent early, since uninit() will
* unconditionally unregister on failure */
aVirtualBox->addDependentChild(this);
else
{
/* we set mParent */
aParent->addDependentChild(this);
}
/* see below why we don't call queryInfo() (and therefore treat the medium
* as inaccessible for now */
/* required */
/* assume not a host drive */
/* optional */
/* required */
if (aDeviceType == DeviceType_HardDisk)
{
}
else
{
/// @todo handle host drive settings here as well?
else
}
/* optional, only for diffs, default is false;
* we can only auto-reset diff images, so they
* must not have a parent */
else
m->autoReset = false;
/* properties (after setting the format as it populates the map). Note that
* if some properties are not supported but preseint in the settings file,
* they will still be read and accessible (for possible backward
* compatibility; we can also clean them up from the XML upon next
* XML format version change if we wish) */
{
}
/* required */
if (aDeviceType == DeviceType_HardDisk)
{
/* type is only for base hard disks */
}
else
m->type = MediumType_Writethrough;
/* remember device type for correct unregistering later */
m->devType = aDeviceType;
LogFlowThisFunc(("m->locationFull='%s', m->format=%s, m->id={%RTuuid}\n",
/* Don't call queryInfo() for registered media to prevent the calling
* thread (i.e. the VirtualBox server startup thread) from an unexpected
* freeze but mark it as initially inaccessible instead. The vital UUID,
* location and format properties are read from the registry file above; to
* get the actual state and the rest of the data, the user will have to call
* COMGETTER(State). */
/* load all children */
++it)
{
pHD.createObject();
this, // parent
med); // child data
}
/* Confirm a successful initialization when it's the case */
return rc;
}
/**
* Initializes the medium object by providing the host drive information.
*
* @todo optimize all callers to avoid reconstructing objects with the same
* information over and over again - in the typical case each VM referring to
* a particular host drive has its own instance.
*
* @param aVirtualBox VirtualBox object.
* @param aDeviceType Device type of the medium.
* @param aLocation Location of the host drive.
* @param aDescription Comment for this host drive.
*
* @note Locks VirtualBox lock for writing, getTreeLock() for writing.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* share VirtualBox weakly (parent remains NULL so far) */
aVirtualBox->addDependentChild(this);
/* fake up a UUID which is unique, but also reproducible */
RTUuidClear(&uuid);
if (aDeviceType == DeviceType_DVD)
else
/* use device name, adjusted to the end of uuid, shortened if necessary */
if (cbLocation > 12)
else
m->type = MediumType_Writethrough;
m->devType = aDeviceType;
m->state = MediumState_Created;
m->hostDrive = true;
m->strDescription = aDescription;
/// @todo generate uuid (similarly to host network interface uuid) from location and device type
return S_OK;
}
/**
* Uninitializes the instance.
*
* Called either from FinalRelease() or by the parent when it gets destroyed.
*
* @note All children of this hard disk get uninitialized by calling their
* uninit() methods.
*
* @note Locks getTreeLock() for writing, VirtualBox for writing.
*/
{
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
{
/* remove the caller reference we added in setFormat() */
m->formatObj->releaseCaller();
}
if (m->state == MediumState_Deleting)
{
/* we are being uninitialized after've been deleted by merge.
* Reparenting has already been done so don't touch it here (we are
* now orphans and remoeDependentChild() will assert) */
}
else
{
/* we uninit children and reset mParent
* and VirtualBox::removeDependentChild() needs a write lock */
{
mParent->removeDependentChild(this);
}
else
mVirtualBox->removeDependentChild(this);
}
}
////////////////////////////////////////////////////////////////////////////////
//
// IMedium public methods
//
////////////////////////////////////////////////////////////////////////////////
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
if (m->strDescription.isEmpty())
else
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
/// @todo update m->description and save the global registry (and local
/// registries of portable VMs referring to this medium), this will also
/// require to add the mRegistered flag to data
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
/// @todo NEWMEDIA for file names, add the default extension if no extension
/// is present (using the information from the VD backend which also implies
/// that one more parameter should be passed to setLocation() requesting
/// that functionality since it is only allwed when called from this method
/// @todo NEWMEDIA rename the file and set m->location on success, then save
/// the global registry (and local registries of portable VMs referring to
/// this medium), this will also require to add the mRegistered flag to data
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
*aDeviceType = m->devType;
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
*aHostDrive = m->hostDrive;
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
return E_POINTER;
AutoCaller autoCaller(this);
/* no need to lock, m->format is const */
return S_OK;
}
{
return E_POINTER;
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
/* VirtualBox::saveSettings() needs a write lock */
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return setStateError();
}
{
/* Nothing to do */
return S_OK;
}
/* we access mParent & children() */
/* cannot change the type of a differencing hard disk */
tr("Hard disk '%s' is a differencing hard disk"),
m->strLocationFull.raw());
/* cannot change the type of a hard disk being in use */
tr("Hard disk '%s' is attached to %d virtual machines"),
switch (aType)
{
case MediumType_Normal:
case MediumType_Immutable:
{
/* normal can be easily converted to immutable and vice versa even
* if they have children as long as they are not attached to any
* machine themselves */
break;
}
case MediumType_Writethrough:
{
/* cannot change to writethrough if there are children */
if (getChildren().size() != 0)
tr("Cannot change type for hard disk '%s' since it has %d child hard disk(s)"),
break;
}
default:
}
return rc;
}
{
return E_POINTER;
AutoCaller autoCaller(this);
/* we access mParent */
return S_OK;
}
{
return E_POINTER;
AutoCaller autoCaller(this);
/* we access children */
return S_OK;
}
{
return E_POINTER;
return S_OK;
}
{
return E_POINTER;
AutoCaller autoCaller(this);
/* isRadOnly() will do locking */
*aReadOnly = isReadOnly();
return S_OK;
}
{
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
/* we access mParent */
{
*aLogicalSize = m->logicalSize;
return S_OK;
}
}
/* We assume that some backend may decide to return a meaningless value in
* response to VDGetSize() for differencing hard disks and therefore
* always ask the base hard disk ourselves. */
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
*aAutoReset = FALSE;
*aAutoReset = m->autoReset;
return S_OK;
}
{
AutoCaller autoCaller(this);
/* VirtualBox::saveSettings() needs a write lock */
return setError(VBOX_E_NOT_SUPPORTED,
tr("Hard disk '%s' is not differencing"),
m->strLocationFull.raw());
if (m->autoReset != aAutoReset)
{
m->autoReset = aAutoReset;
return mVirtualBox->saveSettings();
}
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
if (m->strLastAccessError.isEmpty())
else
return S_OK;
}
{
return E_POINTER;
AutoCaller autoCaller(this);
AutoReadLock alock(this);
{
size_t i = 0;
{
}
}
return S_OK;
}
{
AutoCaller autoCaller(this);
/* queryInfo() locks this for writing. */
AutoWriteLock alock(this);
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
case MediumState_LockedRead:
{
break;
}
default:
break;
}
return rc;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
{
{
/* if the medium is attached to the machine in the current state, we
* return its ID as the first element of the array */
if (it->fInCurState)
++size;
if (size > 0)
{
size_t j = 0;
if (it->fInCurState)
++jt, ++j)
{
}
}
break;
}
}
return S_OK;
}
/**
* @note @a aState may be NULL if the state value is not needed (only for
* in-process calls).
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
/* Wait for a concurrently running queryInfo() to complete */
while (m->queryInfoRunning)
{
}
/* return the current state before */
if (aState)
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
case MediumState_LockedRead:
{
++m->readers;
/* Remember pre-lock state */
if (m->state != MediumState_LockedRead)
m->preLockState = m->state;
m->state = MediumState_LockedRead;
break;
}
default:
{
rc = setStateError();
break;
}
}
return rc;
}
/**
* @note @a aState may be NULL if the state value is not needed (only for
* in-process calls).
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
switch (m->state)
{
case MediumState_LockedRead:
{
--m->readers;
/* Reset the state after the last reader */
if (m->readers == 0)
m->state = m->preLockState;
break;
}
default:
{
tr ("Medium '%s' is not locked for reading"),
m->strLocationFull.raw());
break;
}
}
/* return the current state after */
if (aState)
return rc;
}
/**
* @note @a aState may be NULL if the state value is not needed (only for
* in-process calls).
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
/* Wait for a concurrently running queryInfo() to complete */
while (m->queryInfoRunning)
{
}
/* return the current state before */
if (aState)
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
{
m->preLockState = m->state;
m->state = MediumState_LockedWrite;
break;
}
default:
{
rc = setStateError();
break;
}
}
return rc;
}
/**
* @note @a aState may be NULL if the state value is not needed (only for
* in-process calls).
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
switch (m->state)
{
case MediumState_LockedWrite:
{
m->state = m->preLockState;
break;
}
default:
{
tr ("Medium '%s' is not locked for writing"),
m->strLocationFull.raw());
break;
}
}
/* return the current state after */
if (aState)
return rc;
}
{
AutoMayUninitSpan mayUninitSpan(this);
if (mayUninitSpan.alreadyInProgress())
return S_OK;
/* unregisterWithVirtualBox() is assumed to always need a write mVirtualBox
* lock as it is intenede to modify its internal structires. Also, we want
* to unregister ourselves atomically after detecting that closure is
* possible to make sure that we don't do that after another thread has done
* VirtualBox::find*() but before it starts using us (provided that it holds
* a mVirtualBox lock of course). */
bool wasCreated = true;
switch (m->state)
{
case MediumState_NotCreated:
wasCreated = false;
break;
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return setStateError();
}
return setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' is attached to %d virtual machines"),
/* perform extra media-dependent close checks */
if (wasCreated)
{
/* remove from the list of known media before performing actual
* uninitialization (to keep the media registry consistent on
* failure to do so) */
}
/* cause uninit() to happen on success */
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return setError(VBOX_E_OBJECT_NOT_FOUND,
else
return S_OK;
}
{
AutoCaller autoCaller(this);
/* VirtualBox::saveSettings() needs a write lock */
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return setStateError();
}
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Property '%ls' does not exist"),
aName);
else
return rc;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
/// @todo make use of aNames according to the documentation
size_t i = 0;
++it)
{
else
++ i;
}
return S_OK;
}
{
AutoCaller autoCaller(this);
/* VirtualBox::saveSettings() needs a write lock */
/* first pass: validate names */
for (size_t i = 0;
++i)
{
return setError(VBOX_E_OBJECT_NOT_FOUND,
}
/* second pass: assign */
for (size_t i = 0;
++i)
{
else
}
return rc;
}
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
if ( !(aVariant & MediumVariant_Fixed)
return setError(VBOX_E_NOT_SUPPORTED,
tr("Hard disk format '%s' does not support dynamic storage creation"),
if ( (aVariant & MediumVariant_Fixed)
return setError(VBOX_E_NOT_SUPPORTED,
tr("Hard disk format '%s' does not support fixed storage creation"),
switch (m->state)
{
case MediumState_NotCreated:
break;
default:
return setStateError();
}
TRUE /* aCancelable */);
/* setup task object and thread to carry out the operation
* asynchronously */
/* go to Creating state on success */
m->state = MediumState_Creating;
/* task is now owned by taskThread() so release it */
/* return progress to the caller */
return S_OK;
}
{
AutoCaller autoCaller(this);
{
/* return progress to the caller */
}
return rc;
}
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
if (m->type == MediumType_Writethrough)
tr("Hard disk '%s' is Writethrough"),
m->strLocationFull.raw());
/* We want to be locked for reading as long as our diff child is being
* created */
{
/* Note: on success, taskThread() will unlock this */
}
else
{
/* return progress to the caller */
}
return rc;
}
{
AutoCaller autoCaller(this);
}
{
AutoCaller autoCaller(this);
if (aParent)
{
}
try
{
throw target->setStateError();
* SessionMachine::lockMedia and use it from here too.
* logically this belongs into Medium functionality. */
/* Build the source chain and lock images in the proper order. */
/* we walk the source tree */
{
}
/* Build the parent chain and lock images in the proper order. */
/* we walk the future parent tree */
if (parent)
{
}
{
/* If we're cloning to an existing image the parent chain also
* contains the target image, and it gets locked for writing. */
}
else
{
}
TRUE /* aCancelable */);
/* setup task object and thread to carry out the operation
* asynchronously */
{
/* go to Creating state before leaving the lock */
}
/* task is now owned (or already deleted) by taskThread() so release it */
}
{
}
{
/* return progress to the caller */
}
return rc;
}
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
try
{
* SessionMachine::lockMedia and use it from here too.
* logically this belongs into Medium functionality. */
/* Build the image chain and lock images in the proper order. */
/* we walk the image tree */
{
}
TRUE /* aCancelable */);
/* setup task object and thread to carry out the operation
* asynchronously */
/* task is now owned (or already deleted) by taskThread() so release it */
}
{
}
{
/* return progress to the caller */
}
return rc;
}
{
AutoCaller autoCaller(this);
}
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
return setError(VBOX_E_NOT_SUPPORTED,
tr ("Hard disk '%s' is not differencing"),
m->strLocationFull.raw());
try
{
m->strLocationFull.raw()),
FALSE /* aCancelable */);
/* setup task object and thread to carry out the operation
* asynchronously */
/* task is now owned (or already deleted) by taskThread() so release it */
}
{
}
{
/* Note: on success, taskThread() will unlock this */
}
else
{
/* return progress to the caller */
}
return rc;
}
////////////////////////////////////////////////////////////////////////////////
//
// Medium internal methods
//
////////////////////////////////////////////////////////////////////////////////
/**
* Checks if the given change of \a aOldPath to \a aNewPath affects the location
* of this media and updates it if necessary to reflect the new location.
*
* @param aOldPath Old path (full).
* @param aNewPath New path (full).
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
{
}
return S_OK;
}
/**
* Adds the given machine and optionally the snapshot to the list of the objects
* this image is attached to.
*
* @param aMachineId Machine ID.
* @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
*/
{
LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
case MediumState_LockedRead:
case MediumState_LockedWrite:
break;
default:
return setStateError();
}
if (m->numCreateDiffTasks > 0)
tr("Cannot attach hard disk '%s' {%RTuuid}: %u differencing child hard disk(s) are being created"),
m->strLocationFull.raw(),
m->numCreateDiffTasks);
{
return S_OK;
}
// if the caller has not supplied a snapshot ID, then we're attaching
// to a machine a medium which represents the machine's current state,
// so set the flag
if (aSnapshotId.isEmpty())
{
/* sanity: no duplicate attachments */
it->fInCurState = true;
return S_OK;
}
// otherwise: a snapshot medium is being attached
/* sanity: no duplicate attachments */
++jt)
{
if (idOldSnapshot == aSnapshotId)
tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by snapshot '%RTuuid'"),
m->strLocationFull.raw(),
aSnapshotId.raw(),
idOldSnapshot.raw());
}
it->fInCurState = false;
return S_OK;
}
/**
* Removes the given machine and optionally the snapshot from the list of the
* objects this image is attached to.
*
* @param aMachineId Machine ID.
* @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
* attachment.
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
if (aSnapshotId.isEmpty())
{
/* remove the current state attachment */
it->fInCurState = false;
}
else
{
/* remove the snapshot attachment */
}
/* if the backref becomes empty, remove it */
return S_OK;
}
#ifdef DEBUG
/**
* Debugging helper that gets called after VirtualBox initialization that writes all
* machine backreferences to the debug log.
*/
void Medium::dumpBackRefs()
{
AutoCaller autoCaller(this);
AutoReadLock(this);
++it2)
{
LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
++jt2)
{
}
}
}
#endif
/**
* Internal method to return the medium's GUID. Must have caller + locking!
* @return
*/
{
return m->id;
}
/**
* Internal method to return the medium's GUID. Must have caller + locking!
* @return
*/
{
return m->state;
}
/**
* Internal method to return the medium's location. Must have caller + locking!
* @return
*/
{
return m->strLocation;
}
/**
* Internal method to return the medium's full location. Must have caller + locking!
* @return
*/
{
return m->strLocationFull;
}
/**
* Internal method to return the medium's size. Must have caller + locking!
* @return
*/
{
return m->size;
}
/**
* Internal method to return the medium's list of backrefs. Must have caller + locking!
* @return
*/
{
return NULL;
}
{
return NULL;
return NULL;
}
/**
* Checks if the given change of \a aOldPath to \a aNewPath affects the location
* of this hard disk or any its child and updates the paths if necessary to
* reflect the new location.
*
* @param aOldPath Old path (full).
* @param aNewPath New path (full).
*
* @note Locks getTreeLock() for reading, this object and all children for writing.
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
/* we access children() */
/* update paths of all children */
++ it)
{
}
}
/**
* Returns the base hard disk of the hard disk chain this hard disk is part of.
*
* The base hard disk is found by walking up the parent-child relationship axis.
* If the hard disk doesn't have a parent (i.e. it's a base hard disk), it
* returns itself in response to this method.
*
* @param aLevel Where to store the number of ancestors of this hard disk
* (zero for the base), may be @c NULL.
*
* @note Locks getTreeLock() for reading.
*/
{
AutoCaller autoCaller(this);
/* we access mParent */
pBase = this;
level = 0;
{
for (;;)
{
break;
++level;
}
}
return pBase;
}
/**
* Returns @c true if this hard disk cannot be modified because it has
* dependants (children) or is part of the snapshot. Related to the hard disk
* type and posterity, not to the current media state.
*
* @note Locks this object and getTreeLock() for reading.
*/
bool Medium::isReadOnly()
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
/* we access children */
switch (m->type)
{
case MediumType_Normal:
{
if (getChildren().size() != 0)
return true;
return true;
return false;
}
case MediumType_Immutable:
{
return true;
}
case MediumType_Writethrough:
{
return false;
}
default:
break;
}
AssertFailedReturn(false);
}
/**
* Saves hard disk data by appending a new <HardDisk> child node to the given
* parent node which can be either <HardDisks> or <HardDisk>.
*
* @param data Settings struct to be updated.
*
* @note Locks this object, getTreeLock() and children for reading.
*/
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
/* we access mParent */
/* optional, only for diffs, default is false */
else
data.fAutoReset = false;
/* optional */
/* optional properties */
++it)
{
/* only save properties that have non-default values */
{
}
}
/* only for base hard disks */
/* save all children */
++it)
{
}
return S_OK;
}
/**
* Compares the location of this hard disk to the given location.
*
* The comparison takes the location details into account. For example, if the
* location is a file in the host's filesystem, a case insensitive comparison
* will be performed for case insensitive filesystems.
*
* @param aLocation Location to compare to (as is).
* @param aResult Where to store the result of comparison: 0 if locations
* are equal, 1 if this object's location is greater than
* the specified location, and -1 otherwise.
*/
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
/// @todo NEWMEDIA delegate the comparison to the backend?
{
/* For locations represented by files, append the default path if
* only the name is given, and then get the full path. */
if (!RTPathHavePath(aLocation))
{
}
if (RT_FAILURE(vrc))
tr("Invalid hard disk storage file location '%s' (%Rrc)"),
vrc);
}
else
return S_OK;
}
/**
* Checks that this hard disk may be discarded and performs necessary state
* changes.
*
* This method is to be called prior to calling the #discard() to perform
* necessary consistency checks and place involved hard disks to appropriate
* states. If #discard() is not called or fails, the state modifications
* performed by this method must be undone by #cancelDiscard().
*
* See #discard() for more info about discarding hard disks.
*
* @param aChain Where to store the created merge chain (may return NULL
* if no real merge is necessary).
*
* @note Locks getTreeLock() for reading. Locks this object, aTarget and all
* intermediate hard disks for writing.
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
/* we access mParent & children() */
if (getChildren().size() == 0)
{
/* special treatment of the last hard disk in the chain: */
{
/* lock only, to prevent any usage; discard() will unlock */
}
/* the differencing hard disk w/o children will be deleted, protect it
* from attaching to other VMs (this is why Deleting) */
switch (m->state)
{
case MediumState_Created:
m->state = MediumState_Deleting;
break;
default:
return setStateError();
}
/* aChain is intentionally NULL here */
return S_OK;
}
/* not going multi-merge as it's too expensive */
tr ("Hard disk '%s' has more than one child hard disk (%d)"),
/* this is a read-only hard disk with children; it must be associated with
* exactly one snapshot (when the snapshot is being taken, none of the
* current VM's hard disks may be attached to other VMs). Note that by the
* time when discard() is called, there must be no any attachments at all
* (the code calling prepareDiscard() should detach). */
/* we keep this locked, so lock the affected child to make sure the lock
* order is correct when calling prepareMergeTo() */
/* delegate the rest to the profi */
{
/* base hard disk, backward merge */
{
/* backward merge is too tricky, we'll just detach on discard, so
* lock only, to prevent any usage; discard() will only unlock
* (since we return NULL in aChain) */
}
}
else
{
/* forward merge */
}
}
/**
* Discards this hard disk.
*
* Discarding the hard disk is merging its contents to its differencing child
* hard disk (forward merge) or contents of its child hard disk to itself
* (backward merge) if this hard disk is a base hard disk. If this hard disk is
* a differencing hard disk w/o children, then it will be simply deleted.
* Calling this method on a base hard disk w/o children will do nothing and
* silently succeed. If this hard disk has more than one child, the method will
* currently return an error (since merging in this case would be too expensive
* and result in data duplication).
*
* When the backward merge takes place (i.e. this hard disk is a target) then,
* on success, this hard disk will automatically replace the differencing child
* hard disk used as a source (which will then be deleted) in the attachment
* this child hard disk is associated with. This will happen only if both hard
* disks belong to the same machine because otherwise such a replace would be
* too tricky and could be not expected by the other machine. Same relates to a
* case when the child hard disk is not associated with any machine at all. When
* the backward merge is not applied, the method behaves as if the base hard
* disk were not attached at all -- i.e. simply detaches it from the machine but
* leaves the hard disk chain intact.
*
* This method is basically a wrapper around #mergeTo() that selects the correct
* merge direction and performs additional actions as described above and.
*
* Note that this method will not return until the merge operation is complete
* (which may be quite time consuming depending on the size of the merged hard
* disks).
*
* Note that #prepareDiscard() must be called before calling this method. If
* this method returns a failure, the caller must call #cancelDiscard(). On
* success, #cancelDiscard() must not be called (this method will perform all
* necessary steps such as resetting states of all involved hard disks and
* deleting @a aChain).
*
* @param aChain Merge chain created by #prepareDiscard() (may be NULL if
* no real merge takes place).
*
* @note Locks the hard disks from the chain for writing. Locks the machine
* object when the backward merge takes place. Locks getTreeLock() lock for
* reading or writing.
*/
{
{
AutoCaller autoCaller(this);
ulWeight); // weight
{
AutoWriteLock alock(this);
/* we access mParent & children() */
/* special treatment of the last hard disk in the chain: */
{
return rc;
}
/* delete the differencing hard disk w/o children */
/* go back to Created since deleteStorage() expects this state */
m->state = MediumState_Created;
hdFrom = this;
// deleteStorageAndWait calls unregisterWithVirtualBox which gets
// a write tree lock, so don't deadlock
}
else
{
}
}
{
/* mergeToAndWait() cannot uninitialize the initiator because of
* possible AutoCallers on the current thread, deleteStorageAndWait()
* doesn't do it either; do it ourselves */
}
return rc;
}
/**
* Undoes what #prepareDiscard() did. Must be called if #discard() is not called
* or fails. Frees memory occupied by @a aChain.
*
* @param aChain Merge chain created by #prepareDiscard() (may be NULL if
* no real merge takes place).
*
* @note Locks the hard disks from the chain for writing. Locks getTreeLock() for
* reading.
*/
{
AutoCaller autoCaller(this);
{
AutoWriteLock alock(this);
/* we access mParent & children() */
/* special treatment of the last hard disk in the chain: */
{
return;
}
/* the differencing hard disk w/o children will be deleted, protect it
* from attaching to other VMs (this is why Deleting) */
m->state = MediumState_Created;
return;
}
/* delegate the rest to the profi */
}
/**
* Returns a preferred format for differencing hard disks.
*/
{
AutoCaller autoCaller(this);
/* m->format is const, no need to lock */
/* check that our own format supports diffs */
{
/* use the default format if not */
}
return strFormat;
}
/**
* Returns the medium type. Must have caller + locking!
* @return
*/
{
return m->type;
}
/**
* Returns VirtualBox::hardDiskTreeHandle(), for convenience. Don't forget
* to follow these locking rules:
*
* 1. The write lock on this handle must be either held alone on the thread
* or requested *after* the VirtualBox object lock. Mixing with other
* locks is prohibited.
*
* 2. The read lock on this handle may be intermixed with any other lock
* with the exception that it must be requested *after* the VirtualBox
* object lock.
*/
{
return &mVirtualBox->hardDiskTreeLockHandle();
}
// private methods
////////////////////////////////////////////////////////////////////////////////
/**
* Returns a short version of the location attribute.
*
* @note Must be called from under this object's read or write lock.
*/
{
return name;
}
/**
* Sets the value of m->strLocation and calculates the value of m->strLocationFull.
*
* Treats non-FS-path locations specially, and prepends the default hard disk
* folder if the given location string does not contain any path information
* at all.
*
* Also, if the specified location is a file path that ends with '/' then the
* file name part will be generated by this method automatically in the format
* '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
* and assign to this medium, and <ext> is the default extension for this
* medium's storage format. Note that this procedure requires the media state to
* be NotCreated and will return a failure otherwise.
*
* @param aLocation Location of the storage unit. If the location is a FS-path,
* then it can be relative to the VirtualBox home directory.
* @param aFormat Optional fallback format if it is an import and the format
* cannot be determined.
*
* @note Must be called from under this object's write lock.
*/
{
AutoCaller autoCaller(this);
/* formatObj may be null only when initializing from an existing path and
* no format is known yet */
&& m->state != MediumState_NotCreated
E_FAIL);
/* are we dealing with a new medium constructed using the existing
* location? */
if ( isImport
&& !m->hostDrive))
{
if (m->state == MediumState_NotCreated)
{
/* must be a file (formatObj must be already known) */
{
/* no file name is given (either an empty string or ends with a
* slash), generate a new UUID + file name if the state allows
* this */
("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
E_FAIL);
("Default extension must not be empty\n"),
E_FAIL);
}
}
/* append the default folder if no path is given */
/* get the full file name */
if (RT_FAILURE(vrc))
return setError(VBOX_E_FILE_ERROR,
tr("Invalid medium storage file location '%s' (%Rrc)"),
/* detect the backend from the storage unit if importing */
if (isImport)
{
char *backendName = NULL;
/* is it a file? */
{
if (RT_SUCCESS(vrc))
}
if (RT_SUCCESS(vrc))
{
}
{
/* assume it's not a file, restore the original location */
}
if (RT_FAILURE(vrc))
{
return setError(VBOX_E_FILE_ERROR,
tr("Could not find file for the medium '%s' (%Rrc)"),
return setError(VBOX_E_IPRT_ERROR,
tr("Could not get the storage format of the medium '%s' (%Rrc)"),
else
{
/* setFormat() must not fail since we've just used the backend so
* the format object must be there */
}
}
else
{
/* setFormat() must not fail since we've just used the backend so
* the format object must be there */
}
}
/* is it still a file? */
{
m->strLocation = location;
m->strLocationFull = locationFull;
if (m->state == MediumState_NotCreated)
{
/* assign a new UUID (this UUID will be used when calling
* VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
* also do that if we didn't generate it to make sure it is
* either generated by us or reset to null */
}
}
else
{
m->strLocation = locationFull;
m->strLocationFull = locationFull;
}
}
else
{
m->strLocation = aLocation;
m->strLocationFull = aLocation;
}
return S_OK;
}
/**
* Queries information from the image file.
*
* As a result of this call, the accessibility state and data members such as
* size and description will be updated with the current information.
*
* @note This method may block during a system I/O call that checks storage
* accessibility.
*
* @note Locks getTreeLock() for reading and writing (for new diff media checked
* for the first time). Locks mParent for reading. Locks this object for
* writing.
*/
{
AutoWriteLock alock(this);
if ( m->state != MediumState_Created
&& m->state != MediumState_Inaccessible
&& m->state != MediumState_LockedRead)
return E_FAIL;
int vrc = VINF_SUCCESS;
/* check if a blocking queryInfo() call is in progress on some other thread,
* and wait for it to finish if so instead of querying data ourselves */
if (m->queryInfoRunning)
{
|| m->state == MediumState_LockedWrite);
return S_OK;
}
bool success = false;
/* are we dealing with a new medium constructed using the existing
* location? */
unsigned flags = VD_OPEN_FLAGS_INFO;
/* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
* media because that would prevent necessary modifications
* when opening media of some third-party formats for the first
* time in VirtualBox (such as VMDK for which VDOpen() needs to
* generate an UUID if it is missing) */
if ( (m->hddOpenMode == OpenReadOnly)
|| !isImport
)
/* Lock the medium, which makes the behavior much more consistent */
if (flags & VD_OPEN_FLAGS_READONLY)
else
/* Copies of the input state fields which are not read-only,
* as we're dropping the lock. CAUTION: be extremely careful what
* you do with the contents of this medium object, as you will
* create races if there are concurrent changes. */
/* "Output" values which can't be set because the lock isn't held
* at the time the values are determined. */
uint64_t mediumSize = 0;
/* leave the lock before a lengthy operation */
m->queryInfoRunning = true;
try
{
/* skip accessibility checks for host drives */
if (m->hostDrive)
{
success = true;
throw S_OK;
}
try
{
/** @todo This kind of opening of images is assuming that diff
* images can be opened as base images. Should be fixed ASAP. */
m->vdDiskIfaces);
if (RT_FAILURE(vrc))
{
throw S_OK;
}
{
/* Modify the UUIDs if necessary. The associated fields are
* not modified by other code, so no need to copy. */
if (m->setImageId)
{
}
if (m->setParentId)
{
}
/* zap the information, these are no long-term members */
m->setImageId = false;
m->setParentId = false;
/* check the UUID */
if (isImport)
{
// only when importing a VDMK that has no UUID, create one in memory
}
else
{
{
tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
&uuid,
throw S_OK;
}
}
}
else
{
/* the backend does not support storing UUIDs within the
* underlying storage so use what we store in XML */
/* generate an UUID for an imported UUID-less medium */
if (isImport)
{
if (m->setImageId)
else
}
}
/* check the type */
unsigned uImageFlags;
if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
{
if (isImport)
{
/* the parent must be known to us. Note that we freely
* call locking methods of mVirtualBox and parent from the
* write lock (breaking the {parent,child} lock order)
* because there may be no concurrent access to the just
* opened hard disk on ther threads yet (and init() will
* fail if this method reporst MediumState_Inaccessible) */
false /* aSetError */,
&parent);
{
tr("Parent hard disk with UUID {%RTuuid} of the hard disk '%s' is not found in the media registry ('%s')"),
throw S_OK;
}
/* deassociate from VirtualBox, associate with parent */
mVirtualBox->removeDependentChild(this);
/* we set mParent & children() */
mParent->addDependentChild(this);
}
else
{
/* we access mParent */
/* check that parent UUIDs match. Note that there's no need
* for the parent's AutoCaller (our lifetime is bound to
* it) */
{
tr("Hard disk '%s' is differencing but it is not associated with any parent hard disk in the media registry ('%s')"),
throw S_OK;
}
{
tr ("Parent UUID {%RTuuid} of the hard disk '%s' does not match UUID {%RTuuid} of its parent hard disk stored in the media registry ('%s')"),
throw S_OK;
}
/// @todo NEWMEDIA what to do if the parent is not
/// accessible while the diff is? Probably, nothing. The
/// real code will detect the mismatch anyway.
}
}
success = true;
}
{
}
}
{
}
if (isImport)
if (success)
{
m->size = mediumSize;
m->logicalSize = mediumLogicalSize;
m->strLastAccessError.setNull();
}
else
{
LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
}
/* inform other callers if there are any */
m->queryInfoRunning = false;
/* Set the proper state according to the result of the check */
if (success)
else
if (flags & VD_OPEN_FLAGS_READONLY)
else
return rc;
}
/**
* Sets the extended error info according to the current media state.
*
* @note Must be called from under this object's write or read lock.
*/
{
switch (m->state)
{
case MediumState_NotCreated:
{
tr("Storage for the medium '%s' is not created"),
m->strLocationFull.raw());
break;
}
case MediumState_Created:
{
tr("Storage for the medium '%s' is already created"),
m->strLocationFull.raw());
break;
}
case MediumState_LockedRead:
{
tr("Medium '%s' is locked for reading by another task"),
m->strLocationFull.raw());
break;
}
case MediumState_LockedWrite:
{
tr("Medium '%s' is locked for writing by another task"),
m->strLocationFull.raw());
break;
}
case MediumState_Inaccessible:
{
/* be in sync with Console::powerUpThread() */
if (!m->strLastAccessError.isEmpty())
tr("Medium '%s' is not accessible. %s"),
else
tr("Medium '%s' is not accessible"),
m->strLocationFull.raw());
break;
}
case MediumState_Creating:
{
tr("Storage for the medium '%s' is being created"),
m->strLocationFull.raw());
break;
}
case MediumState_Deleting:
{
tr("Storage for the medium '%s' is being deleted"),
m->strLocationFull.raw());
break;
}
default:
{
AssertFailed();
break;
}
}
return rc;
}
/**
* Deletes the hard disk storage unit.
*
* If @a aProgress is not NULL but the object it points to is @c null then a new
* progress object will be created and assigned to @a *aProgress on success,
* otherwise the existing progress object is used. If Progress is NULL, then no
*
* When @a aWait is @c false, this method will create a thread to perform the
* delete operation asynchronously and will return immediately. Otherwise, it
* will perform the operation on the calling thread and will not return to the
* caller until the operation is completed. Note that @a aProgress cannot be
* NULL when @a aWait is @c false (this method will assert in this case).
*
* completion.
* @param aWait @c true if this method should block instead of creating
* an asynchronous thread.
*
* @note Locks mVirtualBox and this object for writing. Locks getTreeLock() for
* writing.
*/
{
/* unregisterWithVirtualBox() needs a write lock. We want to unregister
* ourselves atomically after detecting that deletion is possible to make
* sure that we don't do that after another thread has done
* VirtualBox::findHardDisk() but before it starts using us (provided that
* it holds a mVirtualBox lock too of course). */
return setError(VBOX_E_NOT_SUPPORTED,
tr("Hard disk format '%s' does not support storage deletion"),
/* Note that we are fine with Inaccessible state too: a) for symmetry with
* create calls and b) because it doesn't really harm to try, if it is
* really inaccessible, the delete operation will fail anyway. Accepting
* Inaccessible state is especially important because all registered hard
* disks are initially Inaccessible upon VBoxSVC startup until
* COMGETTER(State) is called. */
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return setStateError();
}
{
++it)
{
if (strMachines.length())
}
#ifdef DEBUG
dumpBackRefs();
#endif
return setError(VBOX_E_OBJECT_IN_USE,
tr("Cannot delete storage: hard disk '%s' is still attached to the following %d virtual machine(s): %s"),
m->strLocationFull.c_str(),
strMachines.c_str());
}
/* go to Deleting state before leaving the lock */
m->state = MediumState_Deleting;
/* we need to leave this object's write lock now because of
* unregisterWithVirtualBox() that locks getTreeLock() for writing */
/* try to remove from the list of known hard disks before performing actual
* deletion (we favor the consistency of the media registry in the first
* place which would have been broken if unregisterWithVirtualBox() failed
* after we successfully deleted the storage) */
/* restore the state because we may fail below; we will set it later again*/
m->state = MediumState_Created;
{
/* use the existing progress object... */
/* ...but create a new one if it is null */
{
m->strLocationFull.raw()),
FALSE /* aCancelable */);
}
}
if (aWait)
{
/* go to Deleting state before starting the task */
m->state = MediumState_Deleting;
}
else
{
/* go to Deleting state before leaving the lock */
m->state = MediumState_Deleting;
}
/* task is now owned (or already deleted) by taskThread() so release it */
{
/* return progress to the caller */
}
return rc;
}
/**
* Creates a new differencing storage unit using the given target hard disk's
* format and the location. Note that @c aTarget must be NotCreated.
*
* As opposed to the CreateDiffStorage() method, this method doesn't try to lock
* this hard disk for reading assuming that the caller has already done so. This
* is used when taking an online snaopshot (where all original hard disks are
* locked for writing and must remain such). Note however that if @a aWait is
* @c false and this method returns a success then the thread started by
* this method will unlock the hard disk (unless it is in
* MediumState_LockedWrite state) so make sure the hard disk is either in
* MediumState_LockedWrite or call #LockRead() before calling this method! If @a
* aWait is @c true then this method neither locks nor unlocks the hard disk, so
* make sure you do it yourself as needed.
*
* If @a aProgress is not NULL but the object it points to is @c null then a new
* progress object will be created and assigned to @a *aProgress on success,
* otherwise the existing progress object is used. If @a aProgress is NULL, then no
*
* When @a aWait is @c false, this method will create a thread to perform the
* create operation asynchronously and will return immediately. Otherwise, it
* will perform the operation on the calling thread and will not return to the
* caller until the operation is completed. Note that @a aProgress cannot be
* NULL when @a aWait is @c false (this method will assert in this case).
*
* @param aTarget Target hard disk.
* @param aVariant Precise image variant to create.
* completion.
* @param aWait @c true if this method should block instead of creating
* an asynchronous thread.
*
* @note Locks this object and @a aTarget for writing.
*/
bool aWait)
{
AutoCaller autoCaller(this);
/* Note: MediumState_LockedWrite is ok when taking an online snapshot */
return aTarget->setStateError();
/* check that the hard disk is not attached to any VM in the current state*/
{
if (it->fInCurState)
{
/* Note: when a VM snapshot is being taken, all normal hard disks
* attached to the VM in the current state will be, as an exception,
* also associated with the snapshot which is about to create (see
* SnapshotMachine::init()) before deassociating them from the
* current state (which takes place only on success in
* Machine::fixupHardDisks()), so that the size of snapshotIds
* will be 1 in this case. The given condition is used to filter out
* this legal situatinon and do not report an error. */
{
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Hard disk '%s' is attached to a virtual machine with UUID {%RTuuid}. No differencing hard disks based on it may be created until it is detached"),
}
}
}
{
/* use the existing progress object... */
/* ...but create a new one if it is null */
{
TRUE /* aCancelable */);
}
}
/* setup task object and thread to carry out the operation
* asynchronously */
/* register a task (it will deregister itself when done) */
++m->numCreateDiffTasks;
if (aWait)
{
/* go to Creating state before starting the task */
}
else
{
/* go to Creating state before leaving the lock */
}
/* task is now owned (or already deleted) by taskThread() so release it */
{
/* return progress to the caller */
}
return rc;
}
/**
* Prepares this (source) hard disk, target hard disk and all intermediate hard
* disks for the merge operation.
*
* This method is to be called prior to calling the #mergeTo() to perform
* necessary consistency checks and place involved hard disks to appropriate
* states. If #mergeTo() is not called or fails, the state modifications
* performed by this method must be undone by #cancelMergeTo().
*
* Note that when @a aIgnoreAttachments is @c true then it's the caller's
* responsibility to detach the source and all intermediate hard disks before
* calling #mergeTo() (which will fail otherwise).
*
* See #mergeTo() for more information about merging.
*
* @param aTarget Target hard disk.
* @param aChain Where to store the created merge chain.
* @param aIgnoreAttachments Don't check if the source or any intermediate
* hard disk is attached to any VM.
*
* @note Locks getTreeLock() for reading. Locks this object, aTarget and all
* intermediate hard disks for writing.
*/
MergeChain * &aChain,
bool aIgnoreAttachments /*= false*/)
{
AutoCaller autoCaller(this);
/* we walk the tree */
/* detect the merge direction */
bool forward;
{
forward = false;
else
{
if (parent == this)
forward = true;
else
{
{
AutoReadLock alock(this);
}
AutoReadLock alock(this);
tr("Hard disks '%s' and '%s' are unrelated"),
}
}
}
/* build the chain (will do necessary checks and state changes) */
{
for (;;)
{
else if (last == this)
else
break;
}
}
return S_OK;
}
/**
* Merges this hard disk to the specified hard disk which must be either its
* direct ancestor or descendant.
*
* Given this hard disk is SOURCE and the specified hard disk is TARGET, we will
* get two varians of the merge operation:
*
* forward merge
* ------------------------->
* [Extra] <- SOURCE <- Intermediate <- TARGET
* Any Del Del LockWr
*
*
* backward merge
* <-------------------------
* TARGET <- Intermediate <- SOURCE <- [Extra]
* LockWr Del Del LockWr
*
* Each scheme shows the involved hard disks on the hard disk chain where
* SOURCE and TARGET belong. Under each hard disk there is a state value which
* the hard disk must have at a time of the mergeTo() call.
*
* The hard disks in the square braces may be absent (e.g. when the forward
* operation takes place and SOURCE is the base hard disk, or when the backward
* merge operation takes place and TARGET is the last child in the chain) but if
* they present they are involved too as shown.
*
* Nor the source hard disk neither intermediate hard disks may be attached to
* any VM directly or in the snapshot, otherwise this method will assert.
*
* The #prepareMergeTo() method must be called prior to this method to place all
* involved to necessary states and perform other consistency checks.
*
* If @a aWait is @c true then this method will perform the operation on the
* calling thread and will not return to the caller until the operation is
* completed. When this method succeeds, all intermediate hard disk objects in
* the chain will be uninitialized, the state of the target hard disk (and all
* involved extra hard disks) will be restored and @a aChain will be deleted.
* Note that this (source) hard disk is not uninitialized because of possible
* AutoCaller instances held by the caller of this method on the current thread.
* It's therefore the responsibility of the caller to call Medium::uninit()
* after releasing all callers in this case!
*
* If @a aWait is @c false then this method will crea,te a thread to perform the
* create operation asynchronously and will return immediately. If the operation
* succeeds, the thread will uninitialize the source hard disk object and all
* intermediate hard disk objects in the chain, reset the state of the target
* hard disk (and all involved extra hard disks) and delete @a aChain. If the
* operation fails, the thread will only reset the states of all involved hard
* disks and delete @a aChain.
*
* When this method fails (regardless of the @a aWait mode), it is a caller's
* responsiblity to undo state changes and delete @a aChain using
* #cancelMergeTo().
*
* If @a aProgress is not NULL but the object it points to is @c null then a new
* progress object will be created and assigned to @a *aProgress on success,
* otherwise the existing progress object is used. If Progress is NULL, then no
* NULL when @a aWait is @c false (this method will assert in this case).
*
* @param aChain Merge chain created by #prepareMergeTo().
* completion.
* @param aWait @c true if this method should block instead of creating
* an asynchronous thread.
*
* @note Locks the branch lock for writing. Locks the hard disks from the chain
* for writing.
*/
bool aWait)
{
AutoCaller autoCaller(this);
{
/* use the existing progress object... */
/* ...but create a new one if it is null */
{
AutoReadLock alock(this);
TRUE /* aCancelable */);
}
}
/* setup task object and thread to carry out the operation
* asynchronously */
/* Note: task owns aChain (will delete it when not needed) in all cases
* except when @a aWait is @c true and runNow() fails -- in this case
* aChain will be left away because cancelMergeTo() will be applied by the
* caller on it as it is required in the documentation above */
if (aWait)
{
}
else
{
}
/* task is now owned (or already deleted) by taskThread() so release it */
{
/* return progress to the caller */
}
return rc;
}
/**
* Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not called
* or fails. Frees memory occupied by @a aChain.
*
* @param aChain Merge chain created by #prepareMergeTo().
*
* @note Locks the hard disks from the chain for writing.
*/
{
AutoCaller autoCaller(this);
/* the destructor will do the thing */
delete aChain;
}
/**
* Checks that the format ID is valid and sets it on success.
*
* Note that this method will caller-reference the format object on success!
* This reference must be released somewhere to let the MediumFormat object be
* uninitialized.
*
* @note Must be called from under this object's write lock.
*/
{
/* get the format object first */
{
return setError(E_INVALIDARG,
/* reference the format permanently to prevent its unexpected
* uninitialization */
/* get properties (preinsert them as keys in the map). Note that the
* map doesn't grow over the object life time since the set of
* properties is meant to be constant. */
++ it)
{
}
}
return S_OK;
}
/**
* @note Called from this object's AutoMayUninitSpan and from under mVirtualBox
* write lock.
*
* @note Also reused by Medium::Reset().
*
* @note Locks getTreeLock() for reading.
*/
{
/* we access children */
if (getChildren().size() != 0)
tr("Cannot close medium '%s' because it has %d child hard disk(s)"),
return S_OK;
}
/**
* @note Called from within this object's AutoMayUninitSpan (or AutoCaller) and
* from under mVirtualBox write lock.
*
* @note Locks getTreeLock() for writing.
*/
{
/* Note that we need to de-associate ourselves from the parent to let
* unregisterHardDisk() properly save the registry */
/* we modify mParent and access children */
{
/* deassociate from the parent, associate with VirtualBox */
mVirtualBox->addDependentChild(this);
mParent->removeDependentChild(this);
}
switch (m->devType)
{
case DeviceType_DVD:
break;
case DeviceType_Floppy:
break;
case DeviceType_HardDisk:
break;
default:
break;
}
{
{
/* re-associate with the parent as we are still relatives in the
* registry */
mParent->addDependentChild(this);
mVirtualBox->removeDependentChild(this);
}
}
return rc;
}
/**
* Returns the last error message collected by the vdErrorCall callback and
* resets it.
*
* The error message is returned prepended with a dot and a space, like this:
* <code>
* ". <error_text> (%Rrc)"
* </code>
* to make it easily appendable to a more general error message. The @c %Rrc
* format string is given @a aVRC as an argument.
*
* If there is no last error message collected by vdErrorCall or if it is a
* null or empty string, then this function returns the following text:
* <code>
* " (%Rrc)"
* </code>
*
* @note Doesn't do any object locking; it is assumed that the caller makes sure
* the callback isn't called by more than one thread at a time.
*
* @param aVRC VBox error code to use when no error message is provided.
*/
{
else
return error;
}
/**
* Error message callback.
*
* Puts the reported error message to the m->vdError field.
*
* @note Doesn't do any object locking; it is assumed that the caller makes sure
* the callback isn't called by more than one thread at a time.
*
* @param pvUser The opaque data passed on container creation.
* @param rc The VBox error code.
* @param RT_SRC_POS_DECL Use RT_SRC_POS.
* @param pszFormat Error message format string.
* @param va Error message arguments.
*/
/*static*/
{
else
}
/**
* PFNVMPROGRESS callback handler for Task operations.
*
* @param uPercent Completetion precentage (0-100).
* @param pvUser Pointer to the Progress instance.
*/
/*static*/
void *pvUser)
{
{
/* update the progress object, capping it at 99% as the final percent
* is used for additional operations like setting the UUIDs and similar. */
{
return VERR_CANCELLED;
else
return VERR_INVALID_STATE;
}
}
return VINF_SUCCESS;
}
/* static */
const char * /* pszzValid */)
{
/* we always return true since the only keys we have are those found in
* VDBACKENDINFO */
return true;
}
/* static */
{
return VERR_CFGM_VALUE_NOT_FOUND;
/* we interpret null values as "no value" in Medium */
return VERR_CFGM_VALUE_NOT_FOUND;
return VINF_SUCCESS;
}
/* static */
{
return VERR_CFGM_VALUE_NOT_FOUND;
return VERR_CFGM_NOT_ENOUGH_SPACE;
/* we interpret null values as "no value" in Medium */
return VERR_CFGM_VALUE_NOT_FOUND;
return VINF_SUCCESS;
}
/**
* Thread function for time-consuming tasks.
*
* The Task structure passed to @a pvUser must be allocated using new and will
* be freed by this method before it returns.
*
* @param pvUser Pointer to the Task instance.
*/
/* static */
{
/* Set up a per-operation progress interface, can be used freely (for
* binary operations you can use it either on the source or target). */
"Medium::vdInterfaceProgress",
/// @todo ugly hack, fix ComAssert... later
/* Note: no need in AutoCaller because Task does that */
switch (task->m_operation)
{
////////////////////////////////////////////////////////////////////////
case Task::CreateBase:
{
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the job */
/* these parameters we need after creation */
/* The object may request a specific UUID (through a special form of
* the setLocation() argument). Otherwise we have to generate it */
if (generateUuid)
{
/* VirtualBox::registerHardDisk() will need UUID */
}
try
{
/* unlock before the potentially lengthy operation */
try
{
/* ensure the directory exists */
if (RT_FAILURE(vrc))
{
tr("Could not create the hard disk storage unit '%s'%s"),
}
}
}
{
/* register with mVirtualBox as the last step and move to
* Created state only on success (leaving an orphan file is
* better than breaking media registry consistency) */
}
{
}
else
{
/* back to NotCreated on failure */
/* reset UUID to prevent it from being reused next time */
if (generateUuid)
}
break;
}
////////////////////////////////////////////////////////////////////////
case Task::CreateDiff:
{
/* Lock both in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job*/
/* The object may request a specific UUID (through a special form of
* the setLocation() argument). Otherwise we have to generate it */
if (generateUuid)
{
/* VirtualBox::registerHardDisk() will need UUID */
}
try
{
/* Note: MediumState_LockedWrite is ok when taking an online
* snapshot */
/* unlock before the potentially lengthy operation */
try
{
that->m->vdDiskIfaces);
if (RT_FAILURE(vrc))
{
tr("Could not open the hard disk storage unit '%s'%s"),
}
/* ensure the target directory exists */
/** @todo add VD_IMAGE_FLAGS_DIFF to the image flags, to
* be on the safe side. */
target->m->vdDiskIfaces,
if (RT_FAILURE(vrc))
{
tr("Could not create the differencing hard disk storage unit '%s'%s"),
}
}
}
{
/* we set mParent & children() (note that thatLock is released
* here), but lock VirtualBox first to follow the rule */
that->getTreeLock());
/* associate the child with the parent and deassociate from
* VirtualBox */
/** @todo r=klaus neither target nor that->base() are locked,
* potential race! */
/* diffs for immutable hard disks are auto-reset by default */
/* register with mVirtualBox as the last step and move to
* Created state only on success (leaving an orphan file is
* better than breaking media registry consistency) */
{
/* break the parent association on failure to register */
}
}
{
}
else
{
/* back to NotCreated on failure */
/* reset UUID to prevent it from being reused next time */
if (generateUuid)
}
if (isAsync)
{
/* unlock ourselves when done (unless in MediumState_LockedWrite
* state because of taking the online snapshot*/
{
}
}
/* deregister the task registered in createDiffStorage() */
--that->m->numCreateDiffTasks;
/* Note that in sync mode, it's the caller's responsibility to
* unlock the hard disk */
break;
}
////////////////////////////////////////////////////////////////////////
{
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the
* job. We don't actually need the lock for anything else since the
* object is protected by MediumState_Deleting and we don't modify
* its sensitive fields below */
{
}
#if 0
#endif
try
{
try
{
/* Open all hard disks in the chain (they are in the
* {parent,child} order in there. Note that we don't lock
* objects in this chain since they must be in states
* (Deleting and LockedWrite) that prevent from changing
* their format and location fields from outside. */
{
/* complex sanity (sane complexity) */
/* open the first image with VDOPEN_FLAGS_INFO because
* it's not necessarily the base one */
VD_OPEN_FLAGS_INFO : 0,
(*it)->m->vdDiskIfaces);
if (RT_FAILURE(vrc))
throw vrc;
#if 0
#endif
}
#if 0
#endif
if (RT_FAILURE(vrc))
throw vrc;
/* update parent UUIDs */
/// @todo VDMerge should be taught to do so, including the
/// multiple children case
{
/* target's UUID needs to be updated (note that target
* is the only image in the container on success) */
if (RT_FAILURE(vrc))
throw vrc;
}
else
{
/* we need to update UUIDs of all source's children
* which cannot be part of the container at once so
* add each one in there individually */
{
{
/* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
(*it)->m->vdDiskIfaces);
if (RT_FAILURE(vrc))
throw vrc;
if (RT_FAILURE(vrc))
throw vrc;
if (RT_FAILURE(vrc))
throw vrc;
}
}
}
}
catch (int aVRC)
{
tr("Could not merge the hard disk '%s' to '%s'%s"),
}
}
bool saveSettingsFailed = false;
{
/* all hard disks but the target were successfully deleted by
* VDMerge; reparent the last one and uninitialize deleted */
/* we set mParent & children() (note that thatLock is released
* here), but lock VirtualBox first to follow the rule */
that->getTreeLock());
{
/* first, unregister the target since it may become a base
* hard disk which needs re-registration */
/* then, reparent it and disconnect the deleted branch at
* both ends (chain->parent() is source's parent) */
{
}
else
{
}
/* then, register again */
}
else
{
/* disconnect the deleted branch at the elder end */
/* reparent source's chidren and disconnect the deleted
* branch at the younger end m*/
{
/* obey {parent,child} lock order */
{
}
}
}
/* try to save the hard disk registry */
{
/* unregister and uninitialize all hard disks in the chain
* but the target */
{
{
++ it;
continue;
}
/* now, uninitialize the deleted hard disk (note that
* due to the Deleting state, uninit() will not touch
* the parent-child relationship so we need to
* uninitialize each disk individually) */
/* note that the operation initiator hard disk (which is
* normally also the source hard disk) is a special case
* -- there is one more caller added by Task to it which
* we must release. Also, if we are in sync mode, the
* caller may still hold an AutoCaller instance for it
* and therefore we cannot uninit() it (it's therefore
* the caller's responsibility) */
/* release the caller added by MergeChain before
* uninit() */
(*it)->releaseCaller();
/* delete (to prevent uninitialization in MergeChain
* dtor) and advance to the next item */
}
/* Note that states of all other hard disks (target, parent,
* children) will be restored by the MergeChain dtor */
}
else
{
/* too bad if we fail, but we'll need to rollback everything
* we did above to at least keep the HD tree in sync with
* the current registry on disk */
saveSettingsFailed = true;
/// @todo NEWMEDIA implement a proper undo
AssertFailed();
}
}
{
/* Here we come if either VDMerge() failed (in which case we
* assume that it tried to do everything to make a further
* retry possible -- e.g. not deleted intermediate hard disks
* and so on) or VirtualBox::saveSettings() failed (where we
* should have the original tree but with intermediate storage
* units deleted by VDMerge()). We have to only restore states
* (through the MergeChain dtor) unless we are run synchronously
* in which case it's the responsibility of the caller as stated
* in the mergeTo() docs. The latter also implies that we
* don't own the merge chain, so release it in this case. */
if (!isAsync)
}
break;
}
////////////////////////////////////////////////////////////////////////
{
/* Lock all in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job. */
/* The object may request a specific UUID (through a special form of
* the setLocation() argument). Otherwise we have to generate it */
if (generateUuid)
{
/* VirtualBox::registerHardDisk() will need UUID */
}
try
{
try
{
/* Open all hard disk images in the source chain. */
{
/* sanity check */
/** Open all images in read-only mode. */
(*it)->m->vdDiskIfaces);
if (RT_FAILURE(vrc))
{
tr("Could not open the hard disk storage unit '%s'%s"),
}
}
/* unlock before the potentially lengthy operation */
/* ensure the target directory exists */
try
{
/* Open all hard disk images in the parent chain. */
{
/** @todo r=klaus (*it) is not locked, lots of
* race opportunities below */
/* sanity check */
/* Open all images in appropriate mode. */
(*it)->m->vdDiskIfaces);
if (RT_FAILURE(vrc))
{
tr("Could not open the hard disk storage unit '%s'%s"),
}
}
/** @todo r=klaus target isn't locked, race getting the state */
false, 0,
target->m->vdDiskIfaces,
if (RT_FAILURE(vrc))
{
tr("Could not create the clone hard disk '%s'%s"),
}
}
}
}
/* Only do the parent changes for newly created images. */
{
{
/* we set mParent & children() (note that thatLock is released
* here), but lock VirtualBox first to follow the rule */
that->getTreeLock());
if (parent)
{
/* associate the clone with the parent and deassociate
* from VirtualBox */
/* register with mVirtualBox as the last step and move to
* Created state only on success (leaving an orphan file is
* better than breaking media registry consistency) */
{
/* break parent association on failure to register */
}
}
else
{
/* just register */
}
}
}
{
{
}
else
{
/* back to NotCreated on failure */
/* reset UUID to prevent it from being reused next time */
if (generateUuid)
}
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the source chain. */
/* Make sure the source chain is released early. It could happen
* that we get a deadlock in Appliance::Import when Medium::Close
* is called & the source chain is released at the same time. */
break;
}
////////////////////////////////////////////////////////////////////////
{
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the job */
try
{
/* unlock before the potentially lengthy operation */
try
{
that->m->vdDiskIfaces);
if (RT_SUCCESS(vrc))
if (RT_FAILURE(vrc))
{
tr("Could not delete the hard disk storage unit '%s'%s"),
}
}
}
/* go to the NotCreated state even on failure since the storage
* may have been already partially deleted and cannot be used any
* more. One will be able to manually re-open the storage if really
* needed to re-register it. */
/* Reset UUID to prevent Create* from reusing it again */
break;
}
{
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the job */
/// the diff contents but the most efficient way will of course be
/// to add a VDResetDiff() API call
try
{
/* unlock before the potentially lengthy operation */
try
{
/* first, delete the storage unit */
that->m->vdDiskIfaces);
if (RT_SUCCESS(vrc))
if (RT_FAILURE(vrc))
{
tr("Could not delete the hard disk storage unit '%s'%s"),
}
/* next, create it again */
that->m->vdDiskIfaces);
if (RT_FAILURE(vrc))
{
tr("Could not open the hard disk storage unit '%s'%s"),
}
/// @todo use the same image variant as before
that->m->vdDiskIfaces,
if (RT_FAILURE(vrc))
{
tr("Could not create the differencing hard disk storage unit '%s'%s"),
}
}
}
if (isAsync)
{
/* unlock ourselves when done */
}
/* Note that in sync mode, it's the caller's responsibility to
* unlock the hard disk */
break;
}
////////////////////////////////////////////////////////////////////////
{
/* Lock all in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job. */
try
{
try
{
/* Open all hard disk images in the chain. */
last--;
{
/* sanity check */
else
/** Open all images but last in read-only mode. */
(*it)->m->vdDiskIfaces);
if (RT_FAILURE(vrc))
{
tr("Could not open the hard disk storage unit '%s'%s"),
}
}
/* unlock before the potentially lengthy operation */
if (RT_FAILURE(vrc))
{
if (vrc == VERR_NOT_SUPPORTED)
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Compacting is not yet supported for hard disk '%s'"),
else if (vrc == VERR_NOT_IMPLEMENTED)
tr("Compacting is not implemented, hard disk '%s'"),
else
tr("Could not compact hard disk '%s'%s"),
}
}
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the image chain. */
break;
}
default:
}
/* complete the progress if run asynchronously */
if (isAsync)
{
}
else
{
}
return VINF_SUCCESS;
/// @todo ugly hack, fix ComAssert... later
}
/* vi: set tabstop=4 shiftwidth=4 expandtab: */