SnapshotImpl.cpp revision e33ddd0969ec221fb65ee5e274d330cd5fb1504f
/** @file
*
* COM class implementation for Snapshot and SnapshotMachine.
*/
/*
* Copyright (C) 2006-2007 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 "SnapshotImpl.h"
#include "MachineImpl.h"
#include "Global.h"
// @todo these three includes are required for about one or two lines, try
// to remove them and put that code in shared code in MachineImplcpp
#include "SharedFolderImpl.h"
#include "USBControllerImpl.h"
#include "VirtualBoxImpl.h"
#include "Logging.h"
#include <VBox/settings.h>
////////////////////////////////////////////////////////////////////////////////
//
// Globals
//
////////////////////////////////////////////////////////////////////////////////
/**
* Progress callback handler for lengthy operations
* (corresponds to the FNRTPROGRESS typedef).
*
* @param uPercentage Completetion precentage (0-100).
* @param pvUser Pointer to the Progress instance.
*/
{
/* update the progress object */
if (progress)
return VINF_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
//
// Snapshot private data definition
//
////////////////////////////////////////////////////////////////////////////////
{
Data()
{
RTTimeSpecSetMilli(&timeStamp, 0);
};
~Data()
{}
};
////////////////////////////////////////////////////////////////////////////////
//
// Constructor / destructor
//
////////////////////////////////////////////////////////////////////////////////
{
LogFlowMember (("Snapshot::FinalConstruct()\n"));
return S_OK;
}
void Snapshot::FinalRelease()
{
LogFlowMember (("Snapshot::FinalRelease()\n"));
uninit();
}
/**
* Initializes the instance
*
* @param aId id of the snapshot
* @param aName name of the snapshot
* @param aDescription name of the snapshot (NULL if no description)
* @param aTimeStamp timestamp of the snapshot, in ms since 1970-01-01 UTC
* @param aMachine machine associated with this snapshot
* @param aParent parent snapshot (NULL if no parent)
*/
const Utf8Str &aDescription,
const RTTIMESPEC &aTimeStamp,
{
LogFlowMember(("Snapshot::init(uuid: %s, aParent->uuid=%s)\n", aId.toString().c_str(), (aParent) ? aParent->m->uuid.toString().c_str() : ""));
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
m = new Data;
/* share parent weakly */
m->strDescription = aDescription;
m->timeStamp = aTimeStamp;
if (aParent)
/* Confirm a successful initialization when it's the case */
return S_OK;
}
/**
* Uninitializes the instance and sets the ready flag to FALSE.
* Called either from FinalRelease(), by the parent when it gets destroyed,
* or by a third party when it decides this object is no more valid.
*/
{
LogFlowMember (("Snapshot::uninit()\n"));
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
// uninit all children
++it)
{
}
if (mParent)
{
++it)
{
if (this == pParentsChild)
{
break;
}
}
}
if (m->pMachine)
{
}
delete m;
m = NULL;
}
/**
* Discards the current snapshot by removing it from the tree of snapshots
* and reparenting its children.
*
* After this, the caller must call uninit() on the snapshot. We can't call
* that from here because if we do, the AutoUninitSpan waits forever for
* the number of callers to become 0 (it is 1 because of the AutoCaller in here).
*
* NOTE: this does NOT lock the snapshot, it is assumed that the caller has
* locked a) the machine and b) the snapshots tree in write mode!
*/
void Snapshot::beginDiscard()
{
AutoCaller autoCaller(this);
return;
/* for now, the snapshot must have only one child when discarded,
* or no children at all */
/// @todo (dmik):
// when we introduce clones later, discarding the snapshot
// will affect the current and first snapshots of clones, if they are
// direct children of this snapshot. So we will need to lock machines
// associated with child snapshots as well and update mCurrentSnapshot
{
/* we've changed the base of the current state so mark it as
* modified as it no longer guaranteed to be its copy */
}
{
{
}
else
}
// reparent our children
++it)
{
if (mParent)
}
// clear our own children list (since we reparented the children)
m->llChildren.clear();
}
////////////////////////////////////////////////////////////////////////////////
//
// ISnapshot public methods
//
////////////////////////////////////////////////////////////////////////////////
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
/**
* @note Locks this object for writing, then calls Machine::onSnapshotChange()
* (see its lock requirements).
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
{
return m->pMachine->onSnapshotChange(this);
}
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
if (m->strDescription != strDescription)
{
m->strDescription = strDescription;
return m->pMachine->onSnapshotChange(this);
}
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
return S_OK;
}
{
AutoCaller autoCaller(this);
return S_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// Snapshot public internal methods
//
////////////////////////////////////////////////////////////////////////////////
/**
* @note
* Must be called from under the object's lock!
*/
{
}
/**
* Returns the number of direct child snapshots, without grandchildren.
* Does not recurse.
* @return
*/
{
AutoCaller autoCaller(this);
}
/**
* Implementation method for getAllChildrenCount() so we request the
* tree lock only once before recursing. Don't call directly.
* @return
*/
{
AutoCaller autoCaller(this);
++it)
{
}
return count;
}
/**
* Returns the number of child snapshots including all grandchildren.
* Recurses into the snapshots tree.
* @return
*/
{
AutoCaller autoCaller(this);
return getAllChildrenCountImpl();
}
/**
* Returns the SnapshotMachine that this snapshot belongs to.
* Caller must hold the snapshot's object lock!
* @return
*/
{
return (SnapshotMachine*)m->pMachine;
}
/**
* Returns the UUID of this snapshot.
* Caller must hold the snapshot's object lock!
* @return
*/
{
return m->uuid;
}
/**
* Returns the name of this snapshot.
* Caller must hold the snapshot's object lock!
* @return
*/
{
return m->strName;
}
/**
* Returns the time stamp of this snapshot.
* Caller must hold the snapshot's object lock!
* @return
*/
{
return m->timeStamp;
}
/**
* Searches for a snapshot with the given ID among children, grand-children,
* etc. of this snapshot. This snapshot itself is also included in the search.
* Caller must hold the snapshots tree lock!
*/
{
AutoCaller autoCaller(this);
AutoReadLock alock(this);
child = this;
else
{
++it)
{
break;
}
}
return child;
}
/**
* Searches for a first snapshot with the given name among children,
* grand-children, etc. of this snapshot. This snapshot itself is also included
* in the search.
* Caller must hold the snapshots tree lock!
*/
{
AutoCaller autoCaller(this);
AutoReadLock alock (this);
child = this;
else
{
++it)
{
break;
}
}
return child;
}
/**
* Internal implementation for Snapshot::updateSavedStatePaths (below).
* @param aOldPath
* @param aNewPath
*/
{
AutoWriteLock alock(this);
/* state file may be NULL (for offline snapshots) */
)
{
}
++it)
{
}
}
/**
* Checks if the specified path change affects the saved state file path of
* this snapshot or any of its (grand-)children and updates it accordingly.
*
* Intended to be called by Machine::openConfigLoader() only.
*
* @param aOldPath old path (full)
* @param aNewPath new path (full)
*
* @note Locks this object + children for writing.
*/
{
AutoCaller autoCaller(this);
// call the implementation under the tree lock
}
/**
* Internal implementation for Snapshot::saveSnapshot (below).
* @param aNode
* @param aAttrsOnly
* @return
*/
{
AutoReadLock alock(this);
if (aAttrsOnly)
return S_OK;
/* stateFile (optional) */
if (!stateFilePath().isEmpty())
/* try to make the file name relative to the settings file dir */
else
if (m->llChildren.size())
{
++it)
{
}
}
return S_OK;
}
/**
* Saves the given snapshot and all its children (unless \a aAttrsOnly is true).
* It is assumed that the given node is empty (unless \a aAttrsOnly is true).
*
* @param aNode <Snapshot> node to save the snapshot to.
* @param aSnapshot Snapshot to save.
* @param aAttrsOnly If true, only updatge user-changeable attrs.
*/
{
}
////////////////////////////////////////////////////////////////////////////////
//
// SnapshotMachine implementation
//
////////////////////////////////////////////////////////////////////////////////
{
LogFlowThisFunc(("\n"));
/* set the proper type to indicate we're the SnapshotMachine instance */
return S_OK;
}
void SnapshotMachine::FinalRelease()
{
LogFlowThisFunc(("\n"));
uninit();
}
/**
* Initializes the SnapshotMachine object when taking a snapshot.
*
* @param aSessionMachine machine to take a snapshot from
* @param aSnapshotId snapshot ID of this snapshot machine
* @param aStateFilePath file where the execution state will be later saved
* (or NULL for the offline snapshot)
*
* @note The aSessionMachine must be locked for writing.
*/
const Utf8Str &aStateFilePath)
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* memorize the primary Machine instance (i.e. not SessionMachine!) */
/* share the parent pointer */
/* take the pointer to Data to share */
/* take the pointer to UserData to share (our UserData must always be the
* same as Machine's data) */
/* make a private copy of all other data (recent changes from SessionMachine) */
/* SSData is always unique for SnapshotMachine */
/* create copies of all shared folders (mHWData after attiching a copy
* contains just references to original objects) */
++it)
{
}
/* associate hard disks with the snapshot
* (Machine::uninitDataAndChildObjects() will deassociate at destruction) */
++it)
{
if (pMedium) // can be NULL for non-harddisk
{
}
}
/* create copies of all storage controllers (mStorageControllerData
* after attaching a copy contains just references to original objects) */
++it)
{
ctrl.createObject();
}
/* create all other child objects that will be immutable private copies */
#ifdef VBOX_WITH_VRDP
#endif
{
}
{
}
{
}
/* Confirm a successful initialization when it's the case */
return S_OK;
}
/**
* Initializes the SnapshotMachine object when loading from the settings file.
*
* @param aMachine machine the snapshot belngs to
* @param aHWNode <Hardware> node
* @param aHDAsNode <HardDiskAttachments> node
* @param aSnapshotId snapshot ID of this snapshot machine
* @param aStateFilePath file where the execution state is saved
* (or NULL for the offline snapshot)
*
* @note Doesn't lock anything.
*/
const Utf8Str &aStateFilePath)
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* Don't need to lock aMachine when VirtualBox is starting up */
/* memorize the primary Machine instance */
/* share the parent pointer */
/* take the pointer to Data to share */
/*
* take the pointer to UserData to share
* (our UserData must always be the same as Machine's data)
*/
/* allocate private copies of all other data (will be loaded from settings) */
/* SSData is always unique for SnapshotMachine */
/* create all other child objects that will be immutable private copies */
mBIOSSettings->init (this);
#ifdef VBOX_WITH_VRDP
mVRDPServer->init (this);
#endif
mAudioAdapter->init (this);
mUSBController->init (this);
{
}
{
}
{
}
/* load hardware and harddisk settings */
/* commit all changes made during the initialization */
commit();
/* Confirm a successful initialization when it's the case */
return rc;
}
/**
* Uninitializes this SnapshotMachine object.
*/
void SnapshotMachine::uninit()
{
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
/* free the essential data structure last */
}
/**
* Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
* with the primary Machine instance (mPeer).
*/
{
return mPeer->lockHandle();
}
////////////////////////////////////////////////////////////////////////////////
//
// SnapshotMachine public internal methods
//
////////////////////////////////////////////////////////////////////////////////
/**
* Called by the snapshot object associated with this SnapshotMachine when
* snapshot data such as name or description is changed.
*
* @note Locks this object for writing.
*/
{
AutoWriteLock alock(this);
// mPeer->saveAllSnapshots(); @todo
/* inform callbacks */
return S_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// SessionMachine task records
//
////////////////////////////////////////////////////////////////////////////////
/**
* Abstract base class for SessionMachine::RestoreSnapshotTask and
* SessionMachine::DeleteSnapshotTask. This is necessary since
* RTThreadCreate cannot call a method as its thread function, so
* instead we have it call the static SessionMachine::taskHandler,
* which can then call the handler() method in here (implemented
* by the children).
*/
struct SessionMachine::SnapshotTask
{
Progress *p,
Snapshot *s)
: pMachine(m),
pProgress(p),
pSnapshot(s)
{}
void modifyBackedUpState(MachineState_T s)
{
*const_cast<MachineState_T*>(&machineStateBackup) = s;
}
virtual void handler() = 0;
const MachineState_T machineStateBackup;
};
/** Restore snapshot state task */
struct SessionMachine::RestoreSnapshotTask
: public SessionMachine::SnapshotTask
{
Progress *p,
Snapshot *s,
: SnapshotTask(m, p, s),
{}
void handler()
{
pMachine->restoreSnapshotHandler(*this);
}
};
/** Discard snapshot task */
struct SessionMachine::DeleteSnapshotTask
: public SessionMachine::SnapshotTask
{
Progress *p,
Snapshot *s)
: SnapshotTask(m, p, s)
{}
void handler()
{
pMachine->deleteSnapshotHandler(*this);
}
private:
: SnapshotTask(task)
{}
};
/**
* Static SessionMachine method that can get passed to RTThreadCreate to
* have a thread started for a SnapshotTask. See SnapshotTask above.
*
* This calls either RestoreSnapshotTask::handler() or DeleteSnapshotTask::handler().
*/
{
// it's our responsibility to delete the task
delete task;
return 0;
}
////////////////////////////////////////////////////////////////////////////////
//
// TakeSnapshot methods (SessionMachine and related tasks)
//
////////////////////////////////////////////////////////////////////////////////
/**
* Implementation for IInternalMachineControl::beginTakingSnapshot().
*
* Gets called indirectly from Console::TakeSnapshot, which creates a
* progress object in the client and then starts a thread
* (Console::fntTakeSnapshotWorker) which then calls this.
*
* In other words, the asynchronous work for taking snapshots takes place
* on the _client_ (in the Console). This is different from restoring
* or deleting snapshots, which start threads on the server.
*
* This does the server-side work of taking a snapshot: it creates diffencing
* images for all hard disks attached to the machine and then creates a
* Snapshot object with a corresponding SnapshotMachine to save the VM settings.
*
* The client's fntTakeSnapshotWorker() blocks while this takes place.
* After this returns successfully, fntTakeSnapshotWorker() will begin
* saving the machine state to the snapshot object and reconfigure the
* hard disks.
*
* When the console is done, it calls SessionMachine::EndTakingSnapshot().
*
* @note Locks mParent + this object for writing.
*
* @param aInitiator in: The console on which Console::TakeSnapshot was called.
* @param aName in: The name for the new snapshot.
* @param aDescription in: A description for the new snapshot.
* @param aConsoleProgress in: The console's (client's) progress object.
* @param fTakingSnapshotOnline in: True if an online snapshot is being taken (i.e. machine is running).
* @param aStateFilePath out: name of file in snapshots folder to which the console should write the VM state.
* @return
*/
{
AutoCaller autoCaller(this);
/* saveSettings() needs mParent lock */
if ( !fTakingSnapshotOnline
)
{
/* save all current settings to ensure current changes are committed and
* hard disks are fixed up */
}
/* create an ID for the snapshot */
snapshotId.create();
/* stateFilePath is null when the machine is not online nor saved */
{
snapshotId.ptr());
/* ensure the directory for the saved state file exists */
}
/* create a snapshot machine object */
/* create a snapshot object */
/* fill in the snapshot data */
try
{
LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
// backup the media data so we can recover if things goes wrong along the day;
// the matching commit() is in fixupMedia() during endSnapshot()
mMediaData.backup();
/* set the state to Saving (this is expected by Console::TakeSnapshot()) */
/* create new differencing hard disks and attach them to this machine */
1, // operation weight; must be the same as in Console::TakeSnapshot()
{
LogFlowThisFunc(("Copying the execution state from '%s' to '%s'...\n",
1); // weight
/* Leave the lock before a lengthy operation (mMachineState is
* MachineState_Saving here) */
/* copy the state file */
0,
if (RT_FAILURE(vrc))
tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
vrc);
}
}
{
}
else
*aStateFilePath = NULL;
return rc;
}
/**
* Implementation for IInternalMachineControl::beginTakingSnapshot().
*
* Called by the Console when it's done saving the VM state into the snapshot
* (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
*
* This also gets called if the console part of snapshotting failed after the
* BeginTakingSnapshot() call, to clean up the server side.
*
* @note Locks this object for writing.
*
* @param aSuccess Whether Console was successful with the client-side snapshot things.
* @return
*/
{
LogFlowThisFunc(("\n"));
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
AssertReturn(!aSuccess ||
E_FAIL);
/*
* Restore the state we had when BeginTakingSnapshot() was called,
* Console::fntTakeSnapshotWorker restores its local copy when we return.
* If the state was Running, then let Console::fntTakeSnapshotWorker it
* all via Console::Resume().
*/
return endTakingSnapshot(aSuccess);
}
/**
* Internal helper method to finalize taking a snapshot. Gets called from
* SessionMachine::EndTakingSnapshot() to finalize the server-side
* parts of snapshotting.
*
* This also gets called from SessionMachine::uninit() if an untaken
* snapshot needs cleaning up.
*
* Expected to be called after completing *all* the tasks related to
* taking the snapshot, either successfully or unsuccessfilly.
*
* @param aSuccess TRUE if the snapshot has been taken successfully.
*
* @note Locks this objects for writing.
*/
{
AutoCaller autoCaller(this);
// saveSettings needs VirtualBox lock
if (aSuccess)
{
// new snapshot becomes the current one
/* memorize the first snapshot if necessary */
if (!mData->mFirstSnapshot)
if (!fOnline)
/* the machine was powered off or saved when taking a snapshot, so
* reset the mCurrentStateModified flag */
rc = saveSettings();
}
{
/* inform callbacks */
}
else
{
/* delete all differencing hard disks created (this will also attach
* their parents back by rolling back mMediaData) */
fixupMedia(false /* aCommit */);
/* delete the saved state file (it might have been already created) */
}
/* clear out the snapshot data */
return rc;
}
////////////////////////////////////////////////////////////////////////////////
//
// RestoreSnapshot methods (SessionMachine and related tasks)
//
////////////////////////////////////////////////////////////////////////////////
/**
* Implementation for IInternalMachineControl::restoreSnapshot().
*
* Gets called from Console::RestoreSnapshot(), and that's basically the
* only thing Console does. Restoring a snapshot happens entirely on the
* server side since the machine cannot be running.
*
* This creates a new thread that does the work and returns a progress
* object to the client which is then returned to the caller of
* Console::RestoreSnapshot().
*
* Actual work then takes place in RestoreSnapshotTask::handler().
*
* @note Locks this + children objects for writing!
*
* @param aInitiator in: rhe console on which Console::RestoreSnapshot was called.
* @param aSnapshot in: the snapshot to restore.
* @param aMachineState in: client-side machine state.
* @param aProgress out: progress object to monitor restore thread.
* @return
*/
{
AutoCaller autoCaller(this);
AutoWriteLock alock(this);
// machine must not be running
E_FAIL);
// create a progress object. The number of operations is:
// 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
for (MediaData::AttachmentList::iterator it = pSnapshot->getSnapshotMachine()->mMediaData->mAttachments.begin();
++it)
{
{
++ulOpCount;
++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pAttach->medium()->name().c_str()));
}
}
ULONG ulStateFileSizeMB = 0;
{
++ulOpCount; // one for the saved state
if (!RT_SUCCESS(irc))
// if we can't access the file here, then we'll be doomed later also, so fail right away
setError(E_FAIL, tr("Cannot access state file '%s', runtime error, %Rra"), pSnapshot->stateFilePath().c_str(), irc);
if (ullSize == 0) // avoid division by zero
LogFlowThisFunc(("op %d: saved state file '%s' has %RI64 bytes (%d MB)\n",
}
FALSE /* aCancelable */,
1);
/* create and start the task on a separate thread (note that it will not
* start working until we release alock) */
(void*)task,
0,
0,
"RestoreSnap");
if (RT_FAILURE(vrc))
{
delete task;
}
/* set the proper machine state (note: after creating a Task instance) */
/* return the progress to the caller */
/* return the new state to the caller */
return S_OK;
}
/**
* Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
* This method gets called indirectly through SessionMachine::taskHandler() which then
* calls RestoreSnapshotTask::handler().
*
* The RestoreSnapshotTask contains the progress object returned to the console by
* SessionMachine::RestoreSnapshot, through which progress and results are reported.
*
* @note Locks mParent + this object for writing.
*
* @param aTask Task data.
*/
{
AutoCaller autoCaller(this);
if (!autoCaller.isOk())
{
/* we might have been uninitialized because the session was accidentally
* closed by the client, so don't assert */
tr("The session has been accidentally closed"));
return;
}
/* saveSettings() needs mParent lock */
/* @todo We don't need mParent lock so far so unlock() it. Better is to
* provide an AutoWriteLock argument that lets create a non-locking
* instance */
AutoWriteLock alock(this);
/* discard all current changes to mUserData (name, OSType etc.) (note that
* the machine is powered off, so there is no need to inform the direct
* session) */
if (isModified())
rollback(false /* aNotify */);
bool stateRestored = false;
try
{
/* discard the saved state file if the machine was Saved prior to this
* operation */
{
}
{
/* remember the timestamp of the snapshot we're restoring from */
/* copy all hardware data from the snapshot */
LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
/* restore the attachments from the snapshot */
mMediaData.backup();
/* leave the locks before the potentially lengthy operation */
1,
false /* aOnline */);
snapshotLock.lock();
/* Note: on success, current (old) hard disks will be
* deassociated/deleted on #commit() called from #saveSettings() at
* the end. On failure, newly created implicit diffs will be
* deleted by #rollback() at the end. */
/* should not have a saved state file associated at this point */
{
LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
/* leave the lock before the potentially lengthy operation */
/* copy the state file */
0,
snapshotLock.lock();
if (RT_SUCCESS(vrc))
else
tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
stateFilePath.raw(),
vrc);
}
/* make the snapshot we restored from the current snapshot */
}
/* grab differencing hard disks from the old attachments that will
* become unused and need to be auto-deleted */
for (MediaData::AttachmentList::const_iterator it = mMediaData.backedUpData()->mAttachments.begin();
++it)
{
/* while the hard disk is attached, the number of children or the
* parent cannot change, so no lock */
)
{
}
}
int saveFlags = 0;
/* @todo saveSettings() below needs a VirtualBox write lock and we need
* to leave this object's lock to do this to follow the {parent-child}
* locking rule. This is the last chance to do that while we are still
* in a protective state which allows us to temporarily leave the lock*/
/* we have already discarded the current state, so set the execution
* state accordingly no matter of the discard snapshot result */
else
stateRestored = true;
/* assign the timestamp from the snapshot */
// detach the current-state diffs that we detected above and build a list of
// images to delete _after_ saveSettings()
++it)
{
ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->name().raw()));
}
// save all settings, reset the modified flag and commit;
// from here on we cannot roll back on failure any more
++it)
{
LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->name().raw()));
// ignore errors here because we cannot roll back after saveSettings() above
}
}
{
}
{
/* preserve existing error info */
/* undo all changes on failure */
rollback(false /* aNotify */);
if (!stateRestored)
{
/* restore the machine state */
}
}
/* set the result (this will try to fetch current error info on failure) */
}
////////////////////////////////////////////////////////////////////////////////
//
// DeleteSnapshot methods (SessionMachine and related tasks)
//
////////////////////////////////////////////////////////////////////////////////
/**
* Implementation for IInternalMachineControl::deleteSnapshot().
*
* Gets called from Console::DeleteSnapshot(), and that's basically the
* only thing Console does. Deleting a snapshot happens entirely on the
* server side since the machine cannot be running.
*
* This creates a new thread that does the work and returns a progress
* object to the client which is then returned to the caller of
* Console::DeleteSnapshot().
*
* Actual work then takes place in DeleteSnapshotTask::handler().
*
* @note Locks mParent + this + children objects for writing!
*/
{
AutoCaller autoCaller(this);
/* saveSettings() needs mParent lock */
// machine must not be running
if (childrenCount > 1)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Snapshot '%s' of the machine '%ls' cannot be deleted. because it has %d child snapshots, which is more than the one snapshot allowed for deletion"),
/* If the snapshot being discarded is the current one, ensure current
* settings are committed and saved.
*/
{
if (isModified())
{
rc = saveSettings();
}
}
/* create a progress object. The number of operations is:
* 1 (preparing) + # of hard disks + 1 if the snapshot is online
*/
FALSE /* aCancelable */,
/* create and start the task on a separate thread */
(void*)task,
0,
0,
"DeleteSnapshot");
if (RT_FAILURE(vrc))
{
delete task;
return E_FAIL;
}
/* set the proper machine state (note: after creating a Task instance) */
/* return the progress to the caller */
/* return the new state to the caller */
return S_OK;
}
/**
* Helper struct for SessionMachine::deleteSnapshotHandler().
*/
struct MediumDiscardRec
{
{}
{}
const Guid &aSnapshotId)
{}
/* these are for the replace hard disk case: */
};
/**
* Worker method for the delete snapshot thread created by SessionMachine::DeleteSnapshot().
* This method gets called indirectly through SessionMachine::taskHandler() which then
* calls DeleteSnapshotTask::handler().
*
* The DeleteSnapshotTask contains the progress object returned to the console by
* SessionMachine::DeleteSnapshot, through which progress and results are reported.
*
* @note Locks mParent + this + child objects for writing!
*
* @param aTask Task data.
*/
{
AutoCaller autoCaller(this);
if (!autoCaller.isOk())
{
/* we might have been uninitialized because the session was accidentally
* closed by the client, so don't assert */
tr("The session has been accidentally closed"));
return;
}
/* Locking order: */
this->snapshotsTreeLockHandle(),
/* no need to lock the snapshot machine since it is const by definiton */
/* save the snapshot ID (for callbacks) */
bool settingsChanged = false;
try
{
/* first pass: */
LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
++it)
{
// medium can be NULL only for non-hard-disk types
continue;
/* Medium::prepareDiscard() reqiuires a write lock */
{
/* skip writethrough hard disks */
1); // weight
continue;
}
/* needs to be discarded (merged with the child if any), check
* prerequisites */
{
/* it's a base hard disk so it will be a backward merge of its
* only child to it (prepareDiscard() does necessary checks). We
* need then to update the attachment that refers to the child
* to refer to the parent instead. Don't forget to detach the
* child (otherwise mergeTo() called by discard() will assert
* because it will be going to delete the child) */
/* The below assert would be nice but I don't want to move
* Medium::MergeChain to the header just for that
* Assert (!chain->isForward()); */
if (pSnapshotId)
/* adjust back references */
/* replace the hard disk in the attachment object */
if (snapshotId.isEmpty())
{
/* in current state */
}
else
{
/* in snapshot */
/* don't lock the snapshot; cannot be modified outside */
}
hda,
snapshotId));
continue;
}
}
/* Now we checked that we can successfully merge all normal hard disks
* (unless a runtime error like end-of-disc happens). Prior to
* performing the actual merge, we want to discard the snapshot itself
* and remove it from the XML file to make sure that a possible merge
* ruintime error will not make this snapshot inconsistent because of
* the partially merged or corrupted hard disks */
/* second pass: */
LogFlowThisFunc(("2: Discarding snapshot...\n"));
{
/* Note that discarding the snapshot will deassociate it from the
* hard disks which will allow the merge+delete operation for them*/
rc = saveAllSnapshots();
/// @todo (dmik)
// if we implement some warning mechanism later, we'll have
// to return a warning if the state file path cannot be deleted
if (!stateFilePath.isEmpty())
{
1); // weight
}
/// @todo NEWMEDIA to provide a good level of fauilt tolerance, we
/// should restore the shapshot in the snapshot tree if
/// saveSnapshotSettings fails. Actually, we may call
/// #saveSnapshotSettings() with a special flag that will tell it to
/// skip the given snapshot as if it would have been discarded and
/// only actually discard it if the save operation succeeds.
}
/* here we come when we've irrevesibly discarded the snapshot which
* means that the VM settigns (our relevant changes to mData) need to be
* saved too */
/// @todo NEWMEDIA maybe save everything in one operation in place of
/// saveSnapshotSettings() above
settingsChanged = true;
/* third pass: */
LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
/* leave the locks before the potentially lengthy operation */
/// @todo NEWMEDIA turn the following errors into warnings because the
/// snapshot itself has been already deleted (and interpret these
/// warnings properly on the GUI side)
{
/* prevent from calling cancelDiscard() */
}
}
{
/* un-prepare the remaining hard disks */
{
{
/* undo hard disk replacement */
}
}
}
{
/* saveSettings() below needs a VirtualBox write lock and we need to
* leave this object's lock to do this to follow the {parent-child}
* locking rule. This is the last chance to do that while we are
* still in a protective state which allows us to temporarily leave
* the lock */
/* preserve existing error info */
/* restore the machine state */
if (settingsChanged)
/* set the result (this will try to fetch current error info on failure) */
}
}