VirtualBox

source: vbox/trunk/src/VBox/Main/SnapshotImpl.cpp@ 24865

Last change on this file since 24865 was 24572, checked in by vboxsync, 15 years ago

Main: gcc warning

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 76.5 KB
Line 
1/** @file
2 *
3 * COM class implementation for Snapshot and SnapshotMachine.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22#include "SnapshotImpl.h"
23
24#include "MachineImpl.h"
25#include "Global.h"
26
27// @todo these three includes are required for about one or two lines, try
28// to remove them and put that code in shared code in MachineImplcpp
29#include "SharedFolderImpl.h"
30#include "USBControllerImpl.h"
31#include "VirtualBoxImpl.h"
32
33#include "Logging.h"
34
35#include <iprt/path.h>
36#include <VBox/param.h>
37#include <VBox/err.h>
38
39#include <VBox/settings.h>
40
41////////////////////////////////////////////////////////////////////////////////
42//
43// Globals
44//
45////////////////////////////////////////////////////////////////////////////////
46
47/**
48 * Progress callback handler for lengthy operations
49 * (corresponds to the FNRTPROGRESS typedef).
50 *
51 * @param uPercentage Completetion precentage (0-100).
52 * @param pvUser Pointer to the Progress instance.
53 */
54static DECLCALLBACK(int) progressCallback(unsigned uPercentage, void *pvUser)
55{
56 IProgress *progress = static_cast<IProgress*>(pvUser);
57
58 /* update the progress object */
59 if (progress)
60 progress->SetCurrentOperationProgress(uPercentage);
61
62 return VINF_SUCCESS;
63}
64
65////////////////////////////////////////////////////////////////////////////////
66//
67// Snapshot private data definition
68//
69////////////////////////////////////////////////////////////////////////////////
70
71typedef std::list< ComObjPtr<Snapshot> > SnapshotsList;
72
73struct Snapshot::Data
74{
75 Data()
76 {
77 RTTimeSpecSetMilli(&timeStamp, 0);
78 };
79
80 ~Data()
81 {}
82
83 Guid uuid;
84 Utf8Str strName;
85 Utf8Str strDescription;
86 RTTIMESPEC timeStamp;
87 ComObjPtr<SnapshotMachine> pMachine;
88
89 SnapshotsList llChildren; // protected by VirtualBox::snapshotTreeLockHandle()
90};
91
92////////////////////////////////////////////////////////////////////////////////
93//
94// Constructor / destructor
95//
96////////////////////////////////////////////////////////////////////////////////
97
98HRESULT Snapshot::FinalConstruct()
99{
100 LogFlowMember (("Snapshot::FinalConstruct()\n"));
101 return S_OK;
102}
103
104void Snapshot::FinalRelease()
105{
106 LogFlowMember (("Snapshot::FinalRelease()\n"));
107 uninit();
108}
109
110/**
111 * Initializes the instance
112 *
113 * @param aId id of the snapshot
114 * @param aName name of the snapshot
115 * @param aDescription name of the snapshot (NULL if no description)
116 * @param aTimeStamp timestamp of the snapshot, in ms since 1970-01-01 UTC
117 * @param aMachine machine associated with this snapshot
118 * @param aParent parent snapshot (NULL if no parent)
119 */
120HRESULT Snapshot::init(VirtualBox *aVirtualBox,
121 const Guid &aId,
122 const Utf8Str &aName,
123 const Utf8Str &aDescription,
124 const RTTIMESPEC &aTimeStamp,
125 SnapshotMachine *aMachine,
126 Snapshot *aParent)
127{
128 LogFlowMember(("Snapshot::init(uuid: %s, aParent->uuid=%s)\n", aId.toString().c_str(), (aParent) ? aParent->m->uuid.toString().c_str() : ""));
129
130 ComAssertRet (!aId.isEmpty() && !aName.isEmpty() && aMachine, E_INVALIDARG);
131
132 /* Enclose the state transition NotReady->InInit->Ready */
133 AutoInitSpan autoInitSpan(this);
134 AssertReturn(autoInitSpan.isOk(), E_FAIL);
135
136 m = new Data;
137
138 /* share parent weakly */
139 unconst(mVirtualBox) = aVirtualBox;
140
141 mParent = aParent;
142
143 m->uuid = aId;
144 m->strName = aName;
145 m->strDescription = aDescription;
146 m->timeStamp = aTimeStamp;
147 m->pMachine = aMachine;
148
149 if (aParent)
150 aParent->m->llChildren.push_back(this);
151
152 /* Confirm a successful initialization when it's the case */
153 autoInitSpan.setSucceeded();
154
155 return S_OK;
156}
157
158/**
159 * Uninitializes the instance and sets the ready flag to FALSE.
160 * Called either from FinalRelease(), by the parent when it gets destroyed,
161 * or by a third party when it decides this object is no more valid.
162 */
163void Snapshot::uninit()
164{
165 LogFlowMember (("Snapshot::uninit()\n"));
166
167 /* Enclose the state transition Ready->InUninit->NotReady */
168 AutoUninitSpan autoUninitSpan(this);
169 if (autoUninitSpan.uninitDone())
170 return;
171
172 // uninit all children
173 SnapshotsList::iterator it;
174 for (it = m->llChildren.begin();
175 it != m->llChildren.end();
176 ++it)
177 {
178 Snapshot *pChild = *it;
179 pChild->mParent.setNull();
180 pChild->uninit();
181 }
182 m->llChildren.clear(); // this unsets all the ComPtrs and probably calls delete
183
184 if (mParent)
185 {
186 SnapshotsList &llParent = mParent->m->llChildren;
187 for (it = llParent.begin();
188 it != llParent.end();
189 ++it)
190 {
191 Snapshot *pParentsChild = *it;
192 if (this == pParentsChild)
193 {
194 llParent.erase(it);
195 break;
196 }
197 }
198
199 mParent.setNull();
200 }
201
202 if (m->pMachine)
203 {
204 m->pMachine->uninit();
205 m->pMachine.setNull();
206 }
207
208 delete m;
209 m = NULL;
210}
211
212/**
213 * Discards the current snapshot by removing it from the tree of snapshots
214 * and reparenting its children.
215 *
216 * After this, the caller must call uninit() on the snapshot. We can't call
217 * that from here because if we do, the AutoUninitSpan waits forever for
218 * the number of callers to become 0 (it is 1 because of the AutoCaller in here).
219 *
220 * NOTE: this does NOT lock the snapshot, it is assumed that the caller has
221 * locked a) the machine and b) the snapshots tree in write mode!
222 */
223void Snapshot::beginDiscard()
224{
225 AutoCaller autoCaller(this);
226 if (FAILED(autoCaller.rc()))
227 return;
228
229 /* for now, the snapshot must have only one child when discarded,
230 * or no children at all */
231 AssertReturnVoid(m->llChildren.size() <= 1);
232
233 ComObjPtr<Snapshot> parentSnapshot = parent();
234
235 /// @todo (dmik):
236 // when we introduce clones later, discarding the snapshot
237 // will affect the current and first snapshots of clones, if they are
238 // direct children of this snapshot. So we will need to lock machines
239 // associated with child snapshots as well and update mCurrentSnapshot
240 // and/or mFirstSnapshot fields.
241
242 if (this == m->pMachine->mData->mCurrentSnapshot)
243 {
244 m->pMachine->mData->mCurrentSnapshot = parentSnapshot;
245
246 /* we've changed the base of the current state so mark it as
247 * modified as it no longer guaranteed to be its copy */
248 m->pMachine->mData->mCurrentStateModified = TRUE;
249 }
250
251 if (this == m->pMachine->mData->mFirstSnapshot)
252 {
253 if (m->llChildren.size() == 1)
254 {
255 ComObjPtr<Snapshot> childSnapshot = m->llChildren.front();
256 m->pMachine->mData->mFirstSnapshot = childSnapshot;
257 }
258 else
259 m->pMachine->mData->mFirstSnapshot.setNull();
260 }
261
262 // reparent our children
263 for (SnapshotsList::const_iterator it = m->llChildren.begin();
264 it != m->llChildren.end();
265 ++it)
266 {
267 ComObjPtr<Snapshot> child = *it;
268 AutoWriteLock childLock(child);
269
270 child->mParent = mParent;
271 if (mParent)
272 mParent->m->llChildren.push_back(child);
273 }
274
275 // clear our own children list (since we reparented the children)
276 m->llChildren.clear();
277}
278
279////////////////////////////////////////////////////////////////////////////////
280//
281// ISnapshot public methods
282//
283////////////////////////////////////////////////////////////////////////////////
284
285STDMETHODIMP Snapshot::COMGETTER(Id) (BSTR *aId)
286{
287 CheckComArgOutPointerValid(aId);
288
289 AutoCaller autoCaller(this);
290 CheckComRCReturnRC(autoCaller.rc());
291
292 AutoReadLock alock(this);
293
294 m->uuid.toUtf16().cloneTo(aId);
295 return S_OK;
296}
297
298STDMETHODIMP Snapshot::COMGETTER(Name) (BSTR *aName)
299{
300 CheckComArgOutPointerValid(aName);
301
302 AutoCaller autoCaller(this);
303 CheckComRCReturnRC(autoCaller.rc());
304
305 AutoReadLock alock(this);
306
307 m->strName.cloneTo(aName);
308 return S_OK;
309}
310
311/**
312 * @note Locks this object for writing, then calls Machine::onSnapshotChange()
313 * (see its lock requirements).
314 */
315STDMETHODIMP Snapshot::COMSETTER(Name)(IN_BSTR aName)
316{
317 CheckComArgNotNull(aName);
318
319 AutoCaller autoCaller(this);
320 CheckComRCReturnRC(autoCaller.rc());
321
322 Utf8Str strName(aName);
323
324 AutoWriteLock alock(this);
325
326 if (m->strName != strName)
327 {
328 m->strName = strName;
329
330 alock.leave(); /* Important! (child->parent locks are forbidden) */
331
332 return m->pMachine->onSnapshotChange(this);
333 }
334
335 return S_OK;
336}
337
338STDMETHODIMP Snapshot::COMGETTER(Description) (BSTR *aDescription)
339{
340 CheckComArgOutPointerValid(aDescription);
341
342 AutoCaller autoCaller(this);
343 CheckComRCReturnRC(autoCaller.rc());
344
345 AutoReadLock alock(this);
346
347 m->strDescription.cloneTo(aDescription);
348 return S_OK;
349}
350
351STDMETHODIMP Snapshot::COMSETTER(Description) (IN_BSTR aDescription)
352{
353 CheckComArgNotNull(aDescription);
354
355 AutoCaller autoCaller(this);
356 CheckComRCReturnRC(autoCaller.rc());
357
358 Utf8Str strDescription(aDescription);
359
360 AutoWriteLock alock(this);
361
362 if (m->strDescription != strDescription)
363 {
364 m->strDescription = strDescription;
365
366 alock.leave(); /* Important! (child->parent locks are forbidden) */
367
368 return m->pMachine->onSnapshotChange(this);
369 }
370
371 return S_OK;
372}
373
374STDMETHODIMP Snapshot::COMGETTER(TimeStamp) (LONG64 *aTimeStamp)
375{
376 CheckComArgOutPointerValid(aTimeStamp);
377
378 AutoCaller autoCaller(this);
379 CheckComRCReturnRC(autoCaller.rc());
380
381 AutoReadLock alock(this);
382
383 *aTimeStamp = RTTimeSpecGetMilli(&m->timeStamp);
384 return S_OK;
385}
386
387STDMETHODIMP Snapshot::COMGETTER(Online)(BOOL *aOnline)
388{
389 CheckComArgOutPointerValid(aOnline);
390
391 AutoCaller autoCaller(this);
392 CheckComRCReturnRC(autoCaller.rc());
393
394 AutoReadLock alock(this);
395
396 *aOnline = !stateFilePath().isEmpty();
397 return S_OK;
398}
399
400STDMETHODIMP Snapshot::COMGETTER(Machine) (IMachine **aMachine)
401{
402 CheckComArgOutPointerValid(aMachine);
403
404 AutoCaller autoCaller(this);
405 CheckComRCReturnRC(autoCaller.rc());
406
407 AutoReadLock alock(this);
408
409 m->pMachine.queryInterfaceTo(aMachine);
410 return S_OK;
411}
412
413STDMETHODIMP Snapshot::COMGETTER(Parent) (ISnapshot **aParent)
414{
415 CheckComArgOutPointerValid(aParent);
416
417 AutoCaller autoCaller(this);
418 CheckComRCReturnRC(autoCaller.rc());
419
420 AutoReadLock alock(this);
421
422 mParent.queryInterfaceTo(aParent);
423 return S_OK;
424}
425
426STDMETHODIMP Snapshot::COMGETTER(Children) (ComSafeArrayOut(ISnapshot *, aChildren))
427{
428 CheckComArgOutSafeArrayPointerValid(aChildren);
429
430 AutoCaller autoCaller(this);
431 CheckComRCReturnRC(autoCaller.rc());
432
433 AutoReadLock alock(m->pMachine->snapshotsTreeLockHandle());
434 AutoReadLock block(this->lockHandle());
435
436 SafeIfaceArray<ISnapshot> collection(m->llChildren);
437 collection.detachTo(ComSafeArrayOutArg(aChildren));
438
439 return S_OK;
440}
441
442////////////////////////////////////////////////////////////////////////////////
443//
444// Snapshot public internal methods
445//
446////////////////////////////////////////////////////////////////////////////////
447
448/**
449 * @note
450 * Must be called from under the object's lock!
451 */
452const Utf8Str& Snapshot::stateFilePath() const
453{
454 return m->pMachine->mSSData->mStateFilePath;
455}
456
457/**
458 * Returns the number of direct child snapshots, without grandchildren.
459 * Does not recurse.
460 * @return
461 */
462ULONG Snapshot::getChildrenCount()
463{
464 AutoCaller autoCaller(this);
465 AssertComRC(autoCaller.rc());
466
467 AutoReadLock treeLock(m->pMachine->snapshotsTreeLockHandle());
468 return (ULONG)m->llChildren.size();
469}
470
471/**
472 * Implementation method for getAllChildrenCount() so we request the
473 * tree lock only once before recursing. Don't call directly.
474 * @return
475 */
476ULONG Snapshot::getAllChildrenCountImpl()
477{
478 AutoCaller autoCaller(this);
479 AssertComRC(autoCaller.rc());
480
481 ULONG count = (ULONG)m->llChildren.size();
482 for (SnapshotsList::const_iterator it = m->llChildren.begin();
483 it != m->llChildren.end();
484 ++it)
485 {
486 count += (*it)->getAllChildrenCountImpl();
487 }
488
489 return count;
490}
491
492/**
493 * Returns the number of child snapshots including all grandchildren.
494 * Recurses into the snapshots tree.
495 * @return
496 */
497ULONG Snapshot::getAllChildrenCount()
498{
499 AutoCaller autoCaller(this);
500 AssertComRC(autoCaller.rc());
501
502 AutoReadLock treeLock(m->pMachine->snapshotsTreeLockHandle());
503 return getAllChildrenCountImpl();
504}
505
506/**
507 * Returns the SnapshotMachine that this snapshot belongs to.
508 * Caller must hold the snapshot's object lock!
509 * @return
510 */
511ComPtr<SnapshotMachine> Snapshot::getSnapshotMachine()
512{
513 return (SnapshotMachine*)m->pMachine;
514}
515
516/**
517 * Returns the UUID of this snapshot.
518 * Caller must hold the snapshot's object lock!
519 * @return
520 */
521Guid Snapshot::getId() const
522{
523 return m->uuid;
524}
525
526/**
527 * Returns the name of this snapshot.
528 * Caller must hold the snapshot's object lock!
529 * @return
530 */
531const Utf8Str& Snapshot::getName() const
532{
533 return m->strName;
534}
535
536/**
537 * Returns the time stamp of this snapshot.
538 * Caller must hold the snapshot's object lock!
539 * @return
540 */
541RTTIMESPEC Snapshot::getTimeStamp() const
542{
543 return m->timeStamp;
544}
545
546/**
547 * Searches for a snapshot with the given ID among children, grand-children,
548 * etc. of this snapshot. This snapshot itself is also included in the search.
549 * Caller must hold the snapshots tree lock!
550 */
551ComObjPtr<Snapshot> Snapshot::findChildOrSelf(IN_GUID aId)
552{
553 ComObjPtr<Snapshot> child;
554
555 AutoCaller autoCaller(this);
556 AssertComRC(autoCaller.rc());
557
558 AutoReadLock alock(this);
559
560 if (m->uuid == aId)
561 child = this;
562 else
563 {
564 alock.unlock();
565 for (SnapshotsList::const_iterator it = m->llChildren.begin();
566 it != m->llChildren.end();
567 ++it)
568 {
569 if ((child = (*it)->findChildOrSelf(aId)))
570 break;
571 }
572 }
573
574 return child;
575}
576
577/**
578 * Searches for a first snapshot with the given name among children,
579 * grand-children, etc. of this snapshot. This snapshot itself is also included
580 * in the search.
581 * Caller must hold the snapshots tree lock!
582 */
583ComObjPtr<Snapshot> Snapshot::findChildOrSelf(const Utf8Str &aName)
584{
585 ComObjPtr<Snapshot> child;
586 AssertReturn(!aName.isEmpty(), child);
587
588 AutoCaller autoCaller(this);
589 AssertComRC(autoCaller.rc());
590
591 AutoReadLock alock (this);
592
593 if (m->strName == aName)
594 child = this;
595 else
596 {
597 alock.unlock();
598 for (SnapshotsList::const_iterator it = m->llChildren.begin();
599 it != m->llChildren.end();
600 ++it)
601 {
602 if ((child = (*it)->findChildOrSelf(aName)))
603 break;
604 }
605 }
606
607 return child;
608}
609
610/**
611 * Internal implementation for Snapshot::updateSavedStatePaths (below).
612 * @param aOldPath
613 * @param aNewPath
614 */
615void Snapshot::updateSavedStatePathsImpl(const char *aOldPath, const char *aNewPath)
616{
617 AutoWriteLock alock(this);
618
619 const Utf8Str &path = m->pMachine->mSSData->mStateFilePath;
620 LogFlowThisFunc(("Snap[%s].statePath={%s}\n", m->strName.c_str(), path.c_str()));
621
622 /* state file may be NULL (for offline snapshots) */
623 if ( path.length()
624 && RTPathStartsWith(path.c_str(), aOldPath)
625 )
626 {
627 m->pMachine->mSSData->mStateFilePath = Utf8StrFmt("%s%s", aNewPath, path.raw() + strlen(aOldPath));
628
629 LogFlowThisFunc(("-> updated: {%s}\n", path.raw()));
630 }
631
632 for (SnapshotsList::const_iterator it = m->llChildren.begin();
633 it != m->llChildren.end();
634 ++it)
635 {
636 Snapshot *pChild = *it;
637 pChild->updateSavedStatePathsImpl(aOldPath, aNewPath);
638 }
639}
640
641/**
642 * Checks if the specified path change affects the saved state file path of
643 * this snapshot or any of its (grand-)children and updates it accordingly.
644 *
645 * Intended to be called by Machine::openConfigLoader() only.
646 *
647 * @param aOldPath old path (full)
648 * @param aNewPath new path (full)
649 *
650 * @note Locks this object + children for writing.
651 */
652void Snapshot::updateSavedStatePaths(const char *aOldPath, const char *aNewPath)
653{
654 LogFlowThisFunc(("aOldPath={%s} aNewPath={%s}\n", aOldPath, aNewPath));
655
656 AssertReturnVoid(aOldPath);
657 AssertReturnVoid(aNewPath);
658
659 AutoCaller autoCaller(this);
660 AssertComRC(autoCaller.rc());
661
662 AutoWriteLock chLock(m->pMachine->snapshotsTreeLockHandle());
663 // call the implementation under the tree lock
664 updateSavedStatePathsImpl(aOldPath, aNewPath);
665}
666
667/**
668 * Internal implementation for Snapshot::saveSnapshot (below).
669 * @param aNode
670 * @param aAttrsOnly
671 * @return
672 */
673HRESULT Snapshot::saveSnapshotImpl(settings::Snapshot &data, bool aAttrsOnly)
674{
675 AutoReadLock alock(this);
676
677 data.uuid = m->uuid;
678 data.strName = m->strName;
679 data.timestamp = m->timeStamp;
680 data.strDescription = m->strDescription;
681
682 if (aAttrsOnly)
683 return S_OK;
684
685 /* stateFile (optional) */
686 if (!stateFilePath().isEmpty())
687 /* try to make the file name relative to the settings file dir */
688 m->pMachine->calculateRelativePath(stateFilePath(), data.strStateFile);
689 else
690 data.strStateFile.setNull();
691
692 HRESULT rc = m->pMachine->saveHardware(data.hardware);
693 CheckComRCReturnRC (rc);
694
695 rc = m->pMachine->saveStorageControllers(data.storage);
696 CheckComRCReturnRC (rc);
697
698 alock.unlock();
699
700 data.llChildSnapshots.clear();
701
702 if (m->llChildren.size())
703 {
704 for (SnapshotsList::const_iterator it = m->llChildren.begin();
705 it != m->llChildren.end();
706 ++it)
707 {
708 settings::Snapshot snap;
709 rc = (*it)->saveSnapshotImpl(snap, aAttrsOnly);
710 CheckComRCReturnRC (rc);
711
712 data.llChildSnapshots.push_back(snap);
713 }
714 }
715
716 return S_OK;
717}
718
719/**
720 * Saves the given snapshot and all its children (unless \a aAttrsOnly is true).
721 * It is assumed that the given node is empty (unless \a aAttrsOnly is true).
722 *
723 * @param aNode <Snapshot> node to save the snapshot to.
724 * @param aSnapshot Snapshot to save.
725 * @param aAttrsOnly If true, only updatge user-changeable attrs.
726 */
727HRESULT Snapshot::saveSnapshot(settings::Snapshot &data, bool aAttrsOnly)
728{
729 AutoWriteLock listLock(m->pMachine->snapshotsTreeLockHandle());
730
731 return saveSnapshotImpl(data, aAttrsOnly);
732}
733
734////////////////////////////////////////////////////////////////////////////////
735//
736// SnapshotMachine implementation
737//
738////////////////////////////////////////////////////////////////////////////////
739
740DEFINE_EMPTY_CTOR_DTOR (SnapshotMachine)
741
742HRESULT SnapshotMachine::FinalConstruct()
743{
744 LogFlowThisFunc(("\n"));
745
746 /* set the proper type to indicate we're the SnapshotMachine instance */
747 unconst(mType) = IsSnapshotMachine;
748
749 return S_OK;
750}
751
752void SnapshotMachine::FinalRelease()
753{
754 LogFlowThisFunc(("\n"));
755
756 uninit();
757}
758
759/**
760 * Initializes the SnapshotMachine object when taking a snapshot.
761 *
762 * @param aSessionMachine machine to take a snapshot from
763 * @param aSnapshotId snapshot ID of this snapshot machine
764 * @param aStateFilePath file where the execution state will be later saved
765 * (or NULL for the offline snapshot)
766 *
767 * @note The aSessionMachine must be locked for writing.
768 */
769HRESULT SnapshotMachine::init(SessionMachine *aSessionMachine,
770 IN_GUID aSnapshotId,
771 const Utf8Str &aStateFilePath)
772{
773 LogFlowThisFuncEnter();
774 LogFlowThisFunc(("mName={%ls}\n", aSessionMachine->mUserData->mName.raw()));
775
776 AssertReturn(aSessionMachine && !Guid (aSnapshotId).isEmpty(), E_INVALIDARG);
777
778 /* Enclose the state transition NotReady->InInit->Ready */
779 AutoInitSpan autoInitSpan(this);
780 AssertReturn(autoInitSpan.isOk(), E_FAIL);
781
782 AssertReturn(aSessionMachine->isWriteLockOnCurrentThread(), E_FAIL);
783
784 mSnapshotId = aSnapshotId;
785
786 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
787 unconst(mPeer) = aSessionMachine->mPeer;
788 /* share the parent pointer */
789 unconst(mParent) = mPeer->mParent;
790
791 /* take the pointer to Data to share */
792 mData.share (mPeer->mData);
793
794 /* take the pointer to UserData to share (our UserData must always be the
795 * same as Machine's data) */
796 mUserData.share (mPeer->mUserData);
797 /* make a private copy of all other data (recent changes from SessionMachine) */
798 mHWData.attachCopy (aSessionMachine->mHWData);
799 mMediaData.attachCopy(aSessionMachine->mMediaData);
800
801 /* SSData is always unique for SnapshotMachine */
802 mSSData.allocate();
803 mSSData->mStateFilePath = aStateFilePath;
804
805 HRESULT rc = S_OK;
806
807 /* create copies of all shared folders (mHWData after attiching a copy
808 * contains just references to original objects) */
809 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
810 it != mHWData->mSharedFolders.end();
811 ++it)
812 {
813 ComObjPtr<SharedFolder> folder;
814 folder.createObject();
815 rc = folder->initCopy (this, *it);
816 CheckComRCReturnRC(rc);
817 *it = folder;
818 }
819
820 /* associate hard disks with the snapshot
821 * (Machine::uninitDataAndChildObjects() will deassociate at destruction) */
822 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
823 it != mMediaData->mAttachments.end();
824 ++it)
825 {
826 MediumAttachment *pAtt = *it;
827 Medium *pMedium = pAtt->medium();
828 if (pMedium) // can be NULL for non-harddisk
829 {
830 rc = pMedium->attachTo(mData->mUuid, mSnapshotId);
831 AssertComRC(rc);
832 }
833 }
834
835 /* create copies of all storage controllers (mStorageControllerData
836 * after attaching a copy contains just references to original objects) */
837 mStorageControllers.allocate();
838 for (StorageControllerList::const_iterator
839 it = aSessionMachine->mStorageControllers->begin();
840 it != aSessionMachine->mStorageControllers->end();
841 ++it)
842 {
843 ComObjPtr<StorageController> ctrl;
844 ctrl.createObject();
845 ctrl->initCopy (this, *it);
846 mStorageControllers->push_back(ctrl);
847 }
848
849 /* create all other child objects that will be immutable private copies */
850
851 unconst(mBIOSSettings).createObject();
852 mBIOSSettings->initCopy (this, mPeer->mBIOSSettings);
853
854#ifdef VBOX_WITH_VRDP
855 unconst(mVRDPServer).createObject();
856 mVRDPServer->initCopy (this, mPeer->mVRDPServer);
857#endif
858
859 unconst(mAudioAdapter).createObject();
860 mAudioAdapter->initCopy (this, mPeer->mAudioAdapter);
861
862 unconst(mUSBController).createObject();
863 mUSBController->initCopy (this, mPeer->mUSBController);
864
865 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
866 {
867 unconst(mNetworkAdapters [slot]).createObject();
868 mNetworkAdapters [slot]->initCopy (this, mPeer->mNetworkAdapters [slot]);
869 }
870
871 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
872 {
873 unconst(mSerialPorts [slot]).createObject();
874 mSerialPorts [slot]->initCopy (this, mPeer->mSerialPorts [slot]);
875 }
876
877 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
878 {
879 unconst(mParallelPorts [slot]).createObject();
880 mParallelPorts [slot]->initCopy (this, mPeer->mParallelPorts [slot]);
881 }
882
883 /* Confirm a successful initialization when it's the case */
884 autoInitSpan.setSucceeded();
885
886 LogFlowThisFuncLeave();
887 return S_OK;
888}
889
890/**
891 * Initializes the SnapshotMachine object when loading from the settings file.
892 *
893 * @param aMachine machine the snapshot belngs to
894 * @param aHWNode <Hardware> node
895 * @param aHDAsNode <HardDiskAttachments> node
896 * @param aSnapshotId snapshot ID of this snapshot machine
897 * @param aStateFilePath file where the execution state is saved
898 * (or NULL for the offline snapshot)
899 *
900 * @note Doesn't lock anything.
901 */
902HRESULT SnapshotMachine::init(Machine *aMachine,
903 const settings::Hardware &hardware,
904 const settings::Storage &storage,
905 IN_GUID aSnapshotId,
906 const Utf8Str &aStateFilePath)
907{
908 LogFlowThisFuncEnter();
909 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
910
911 AssertReturn(aMachine && !Guid(aSnapshotId).isEmpty(), E_INVALIDARG);
912
913 /* Enclose the state transition NotReady->InInit->Ready */
914 AutoInitSpan autoInitSpan(this);
915 AssertReturn(autoInitSpan.isOk(), E_FAIL);
916
917 /* Don't need to lock aMachine when VirtualBox is starting up */
918
919 mSnapshotId = aSnapshotId;
920
921 /* memorize the primary Machine instance */
922 unconst(mPeer) = aMachine;
923 /* share the parent pointer */
924 unconst(mParent) = mPeer->mParent;
925
926 /* take the pointer to Data to share */
927 mData.share (mPeer->mData);
928 /*
929 * take the pointer to UserData to share
930 * (our UserData must always be the same as Machine's data)
931 */
932 mUserData.share (mPeer->mUserData);
933 /* allocate private copies of all other data (will be loaded from settings) */
934 mHWData.allocate();
935 mMediaData.allocate();
936 mStorageControllers.allocate();
937
938 /* SSData is always unique for SnapshotMachine */
939 mSSData.allocate();
940 mSSData->mStateFilePath = aStateFilePath;
941
942 /* create all other child objects that will be immutable private copies */
943
944 unconst(mBIOSSettings).createObject();
945 mBIOSSettings->init (this);
946
947#ifdef VBOX_WITH_VRDP
948 unconst(mVRDPServer).createObject();
949 mVRDPServer->init (this);
950#endif
951
952 unconst(mAudioAdapter).createObject();
953 mAudioAdapter->init (this);
954
955 unconst(mUSBController).createObject();
956 mUSBController->init (this);
957
958 for (ULONG slot = 0; slot < RT_ELEMENTS (mNetworkAdapters); slot ++)
959 {
960 unconst(mNetworkAdapters [slot]).createObject();
961 mNetworkAdapters [slot]->init (this, slot);
962 }
963
964 for (ULONG slot = 0; slot < RT_ELEMENTS (mSerialPorts); slot ++)
965 {
966 unconst(mSerialPorts [slot]).createObject();
967 mSerialPorts [slot]->init (this, slot);
968 }
969
970 for (ULONG slot = 0; slot < RT_ELEMENTS (mParallelPorts); slot ++)
971 {
972 unconst(mParallelPorts [slot]).createObject();
973 mParallelPorts [slot]->init (this, slot);
974 }
975
976 /* load hardware and harddisk settings */
977
978 HRESULT rc = loadHardware(hardware);
979 if (SUCCEEDED(rc))
980 rc = loadStorageControllers(storage, true /* aRegistered */, &mSnapshotId);
981
982 if (SUCCEEDED(rc))
983 /* commit all changes made during the initialization */
984 commit();
985
986 /* Confirm a successful initialization when it's the case */
987 if (SUCCEEDED(rc))
988 autoInitSpan.setSucceeded();
989
990 LogFlowThisFuncLeave();
991 return rc;
992}
993
994/**
995 * Uninitializes this SnapshotMachine object.
996 */
997void SnapshotMachine::uninit()
998{
999 LogFlowThisFuncEnter();
1000
1001 /* Enclose the state transition Ready->InUninit->NotReady */
1002 AutoUninitSpan autoUninitSpan(this);
1003 if (autoUninitSpan.uninitDone())
1004 return;
1005
1006 uninitDataAndChildObjects();
1007
1008 /* free the essential data structure last */
1009 mData.free();
1010
1011 unconst(mParent).setNull();
1012 unconst(mPeer).setNull();
1013
1014 LogFlowThisFuncLeave();
1015}
1016
1017/**
1018 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
1019 * with the primary Machine instance (mPeer).
1020 */
1021RWLockHandle *SnapshotMachine::lockHandle() const
1022{
1023 AssertReturn(!mPeer.isNull(), NULL);
1024 return mPeer->lockHandle();
1025}
1026
1027////////////////////////////////////////////////////////////////////////////////
1028//
1029// SnapshotMachine public internal methods
1030//
1031////////////////////////////////////////////////////////////////////////////////
1032
1033/**
1034 * Called by the snapshot object associated with this SnapshotMachine when
1035 * snapshot data such as name or description is changed.
1036 *
1037 * @note Locks this object for writing.
1038 */
1039HRESULT SnapshotMachine::onSnapshotChange (Snapshot *aSnapshot)
1040{
1041 AutoWriteLock alock(this);
1042
1043 // mPeer->saveAllSnapshots(); @todo
1044
1045 /* inform callbacks */
1046 mParent->onSnapshotChange(mData->mUuid, aSnapshot->getId());
1047
1048 return S_OK;
1049}
1050
1051////////////////////////////////////////////////////////////////////////////////
1052//
1053// SessionMachine task records
1054//
1055////////////////////////////////////////////////////////////////////////////////
1056
1057/**
1058 * Abstract base class for SessionMachine::RestoreSnapshotTask and
1059 * SessionMachine::DeleteSnapshotTask. This is necessary since
1060 * RTThreadCreate cannot call a method as its thread function, so
1061 * instead we have it call the static SessionMachine::taskHandler,
1062 * which can then call the handler() method in here (implemented
1063 * by the children).
1064 */
1065struct SessionMachine::SnapshotTask
1066{
1067 SnapshotTask(SessionMachine *m,
1068 Progress *p,
1069 Snapshot *s)
1070 : pMachine(m),
1071 pProgress(p),
1072 machineStateBackup(m->mData->mMachineState), // save the current machine state
1073 pSnapshot(s)
1074 {}
1075
1076 void modifyBackedUpState(MachineState_T s)
1077 {
1078 *const_cast<MachineState_T*>(&machineStateBackup) = s;
1079 }
1080
1081 virtual void handler() = 0;
1082
1083 ComObjPtr<SessionMachine> pMachine;
1084 ComObjPtr<Progress> pProgress;
1085 const MachineState_T machineStateBackup;
1086 ComObjPtr<Snapshot> pSnapshot;
1087};
1088
1089/** Restore snapshot state task */
1090struct SessionMachine::RestoreSnapshotTask
1091 : public SessionMachine::SnapshotTask
1092{
1093 RestoreSnapshotTask(SessionMachine *m,
1094 Progress *p,
1095 Snapshot *s,
1096 ULONG ulStateFileSizeMB)
1097 : SnapshotTask(m, p, s),
1098 m_ulStateFileSizeMB(ulStateFileSizeMB)
1099 {}
1100
1101 void handler()
1102 {
1103 pMachine->restoreSnapshotHandler(*this);
1104 }
1105
1106 ULONG m_ulStateFileSizeMB;
1107};
1108
1109/** Discard snapshot task */
1110struct SessionMachine::DeleteSnapshotTask
1111 : public SessionMachine::SnapshotTask
1112{
1113 DeleteSnapshotTask(SessionMachine *m,
1114 Progress *p,
1115 Snapshot *s)
1116 : SnapshotTask(m, p, s)
1117 {}
1118
1119 void handler()
1120 {
1121 pMachine->deleteSnapshotHandler(*this);
1122 }
1123
1124private:
1125 DeleteSnapshotTask(const SnapshotTask &task)
1126 : SnapshotTask(task)
1127 {}
1128};
1129
1130/**
1131 * Static SessionMachine method that can get passed to RTThreadCreate to
1132 * have a thread started for a SnapshotTask. See SnapshotTask above.
1133 *
1134 * This calls either RestoreSnapshotTask::handler() or DeleteSnapshotTask::handler().
1135 */
1136
1137/* static */ DECLCALLBACK(int) SessionMachine::taskHandler(RTTHREAD /* thread */, void *pvUser)
1138{
1139 AssertReturn(pvUser, VERR_INVALID_POINTER);
1140
1141 SnapshotTask *task = static_cast<SnapshotTask*>(pvUser);
1142 task->handler();
1143
1144 // it's our responsibility to delete the task
1145 delete task;
1146
1147 return 0;
1148}
1149
1150////////////////////////////////////////////////////////////////////////////////
1151//
1152// TakeSnapshot methods (SessionMachine and related tasks)
1153//
1154////////////////////////////////////////////////////////////////////////////////
1155
1156/**
1157 * Implementation for IInternalMachineControl::beginTakingSnapshot().
1158 *
1159 * Gets called indirectly from Console::TakeSnapshot, which creates a
1160 * progress object in the client and then starts a thread
1161 * (Console::fntTakeSnapshotWorker) which then calls this.
1162 *
1163 * In other words, the asynchronous work for taking snapshots takes place
1164 * on the _client_ (in the Console). This is different from restoring
1165 * or deleting snapshots, which start threads on the server.
1166 *
1167 * This does the server-side work of taking a snapshot: it creates diffencing
1168 * images for all hard disks attached to the machine and then creates a
1169 * Snapshot object with a corresponding SnapshotMachine to save the VM settings.
1170 *
1171 * The client's fntTakeSnapshotWorker() blocks while this takes place.
1172 * After this returns successfully, fntTakeSnapshotWorker() will begin
1173 * saving the machine state to the snapshot object and reconfigure the
1174 * hard disks.
1175 *
1176 * When the console is done, it calls SessionMachine::EndTakingSnapshot().
1177 *
1178 * @note Locks mParent + this object for writing.
1179 *
1180 * @param aInitiator in: The console on which Console::TakeSnapshot was called.
1181 * @param aName in: The name for the new snapshot.
1182 * @param aDescription in: A description for the new snapshot.
1183 * @param aConsoleProgress in: The console's (client's) progress object.
1184 * @param fTakingSnapshotOnline in: True if an online snapshot is being taken (i.e. machine is running).
1185 * @param aStateFilePath out: name of file in snapshots folder to which the console should write the VM state.
1186 * @return
1187 */
1188STDMETHODIMP SessionMachine::BeginTakingSnapshot(IConsole *aInitiator,
1189 IN_BSTR aName,
1190 IN_BSTR aDescription,
1191 IProgress *aConsoleProgress,
1192 BOOL fTakingSnapshotOnline,
1193 BSTR *aStateFilePath)
1194{
1195 LogFlowThisFuncEnter();
1196
1197 AssertReturn(aInitiator && aName, E_INVALIDARG);
1198 AssertReturn(aStateFilePath, E_POINTER);
1199
1200 LogFlowThisFunc(("aName='%ls'\n", aName));
1201
1202 AutoCaller autoCaller(this);
1203 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
1204
1205 /* saveSettings() needs mParent lock */
1206 AutoMultiWriteLock2 alock(mParent, this);
1207
1208 AssertReturn( !Global::IsOnlineOrTransient(mData->mMachineState)
1209 || mData->mMachineState == MachineState_Running
1210 || mData->mMachineState == MachineState_Paused, E_FAIL);
1211 AssertReturn(mSnapshotData.mLastState == MachineState_Null, E_FAIL);
1212 AssertReturn(mSnapshotData.mSnapshot.isNull(), E_FAIL);
1213
1214 if ( !fTakingSnapshotOnline
1215 && mData->mMachineState != MachineState_Saved
1216 )
1217 {
1218 /* save all current settings to ensure current changes are committed and
1219 * hard disks are fixed up */
1220 HRESULT rc = saveSettings();
1221 CheckComRCReturnRC(rc);
1222 }
1223
1224 /* create an ID for the snapshot */
1225 Guid snapshotId;
1226 snapshotId.create();
1227
1228 Utf8Str strStateFilePath;
1229 /* stateFilePath is null when the machine is not online nor saved */
1230 if ( fTakingSnapshotOnline
1231 || mData->mMachineState == MachineState_Saved)
1232 {
1233 strStateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
1234 mUserData->mSnapshotFolderFull.raw(),
1235 RTPATH_DELIMITER,
1236 snapshotId.ptr());
1237 /* ensure the directory for the saved state file exists */
1238 HRESULT rc = VirtualBox::ensureFilePathExists(strStateFilePath);
1239 CheckComRCReturnRC(rc);
1240 }
1241
1242 /* create a snapshot machine object */
1243 ComObjPtr<SnapshotMachine> snapshotMachine;
1244 snapshotMachine.createObject();
1245 HRESULT rc = snapshotMachine->init(this, snapshotId, strStateFilePath);
1246 AssertComRCReturn(rc, rc);
1247
1248 /* create a snapshot object */
1249 RTTIMESPEC time;
1250 ComObjPtr<Snapshot> pSnapshot;
1251 pSnapshot.createObject();
1252 rc = pSnapshot->init(mParent,
1253 snapshotId,
1254 aName,
1255 aDescription,
1256 *RTTimeNow(&time),
1257 snapshotMachine,
1258 mData->mCurrentSnapshot);
1259 AssertComRCReturnRC(rc);
1260
1261 /* fill in the snapshot data */
1262 mSnapshotData.mLastState = mData->mMachineState;
1263 mSnapshotData.mSnapshot = pSnapshot;
1264
1265 try
1266 {
1267 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
1268 fTakingSnapshotOnline));
1269
1270 // backup the media data so we can recover if things goes wrong along the day;
1271 // the matching commit() is in fixupMedia() during endSnapshot()
1272 mMediaData.backup();
1273
1274 /* Console::fntTakeSnapshotWorker and friends expects this. */
1275 if (mSnapshotData.mLastState == MachineState_Running)
1276 setMachineState(MachineState_LiveSnapshotting);
1277 else
1278 setMachineState(MachineState_Saving); /** @todo Confusing! Saving is used for both online and offline snapshots. */
1279
1280 /* create new differencing hard disks and attach them to this machine */
1281 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
1282 aConsoleProgress,
1283 1, // operation weight; must be the same as in Console::TakeSnapshot()
1284 !!fTakingSnapshotOnline);
1285
1286 if (SUCCEEDED(rc) && mSnapshotData.mLastState == MachineState_Saved)
1287 {
1288 Utf8Str stateFrom = mSSData->mStateFilePath;
1289 Utf8Str stateTo = mSnapshotData.mSnapshot->stateFilePath();
1290
1291 LogFlowThisFunc(("Copying the execution state from '%s' to '%s'...\n",
1292 stateFrom.raw(), stateTo.raw()));
1293
1294 aConsoleProgress->SetNextOperation(Bstr(tr("Copying the execution state")),
1295 1); // weight
1296
1297 /* Leave the lock before a lengthy operation (mMachineState is
1298 * MachineState_Saving here) */
1299 alock.leave();
1300
1301 /* copy the state file */
1302 int vrc = RTFileCopyEx(stateFrom.c_str(),
1303 stateTo.c_str(),
1304 0,
1305 progressCallback,
1306 aConsoleProgress);
1307 alock.enter();
1308
1309 if (RT_FAILURE(vrc))
1310 throw setError(E_FAIL,
1311 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1312 stateFrom.raw(),
1313 stateTo.raw(),
1314 vrc);
1315 }
1316 }
1317 catch (HRESULT hrc)
1318 {
1319 pSnapshot->uninit();
1320 pSnapshot.setNull();
1321 rc = hrc;
1322 }
1323
1324 if (fTakingSnapshotOnline)
1325 strStateFilePath.cloneTo(aStateFilePath);
1326 else
1327 *aStateFilePath = NULL;
1328
1329 LogFlowThisFuncLeave();
1330 return rc;
1331}
1332
1333/**
1334 * Implementation for IInternalMachineControl::beginTakingSnapshot().
1335 *
1336 * Called by the Console when it's done saving the VM state into the snapshot
1337 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
1338 *
1339 * This also gets called if the console part of snapshotting failed after the
1340 * BeginTakingSnapshot() call, to clean up the server side.
1341 *
1342 * @note Locks this object for writing.
1343 *
1344 * @param aSuccess Whether Console was successful with the client-side snapshot things.
1345 * @return
1346 */
1347STDMETHODIMP SessionMachine::EndTakingSnapshot(BOOL aSuccess)
1348{
1349 LogFlowThisFunc(("\n"));
1350
1351 AutoCaller autoCaller(this);
1352 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1353
1354 AutoWriteLock alock(this);
1355
1356 AssertReturn( !aSuccess
1357 || ( ( mData->mMachineState == MachineState_Saving
1358 || mData->mMachineState == MachineState_LiveSnapshotting)
1359 && mSnapshotData.mLastState != MachineState_Null
1360 && !mSnapshotData.mSnapshot.isNull()
1361 )
1362 , E_FAIL);
1363
1364 /*
1365 * Restore the state we had when BeginTakingSnapshot() was called,
1366 * Console::fntTakeSnapshotWorker restores its local copy when we return.
1367 * If the state was Running, then let Console::fntTakeSnapshotWorker it
1368 * all via Console::Resume().
1369 */
1370 if ( mData->mMachineState != mSnapshotData.mLastState
1371 && mSnapshotData.mLastState != MachineState_Running)
1372 setMachineState(mSnapshotData.mLastState);
1373
1374 return endTakingSnapshot(aSuccess);
1375}
1376
1377/**
1378 * Internal helper method to finalize taking a snapshot. Gets called from
1379 * SessionMachine::EndTakingSnapshot() to finalize the server-side
1380 * parts of snapshotting.
1381 *
1382 * This also gets called from SessionMachine::uninit() if an untaken
1383 * snapshot needs cleaning up.
1384 *
1385 * Expected to be called after completing *all* the tasks related to
1386 * taking the snapshot, either successfully or unsuccessfilly.
1387 *
1388 * @param aSuccess TRUE if the snapshot has been taken successfully.
1389 *
1390 * @note Locks this objects for writing.
1391 */
1392HRESULT SessionMachine::endTakingSnapshot(BOOL aSuccess)
1393{
1394 LogFlowThisFuncEnter();
1395
1396 AutoCaller autoCaller(this);
1397 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1398
1399 AutoMultiWriteLock2 alock(mParent, this);
1400 // saveSettings needs VirtualBox lock
1401
1402 AssertReturn(!mSnapshotData.mSnapshot.isNull(), E_FAIL);
1403
1404 MultiResult rc(S_OK);
1405
1406 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
1407 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
1408
1409 bool fOnline = Global::IsOnline(mSnapshotData.mLastState);
1410
1411 if (aSuccess)
1412 {
1413 // new snapshot becomes the current one
1414 mData->mCurrentSnapshot = mSnapshotData.mSnapshot;
1415
1416 /* memorize the first snapshot if necessary */
1417 if (!mData->mFirstSnapshot)
1418 mData->mFirstSnapshot = mData->mCurrentSnapshot;
1419
1420 if (!fOnline)
1421 /* the machine was powered off or saved when taking a snapshot, so
1422 * reset the mCurrentStateModified flag */
1423 mData->mCurrentStateModified = FALSE;
1424
1425 rc = saveSettings();
1426 }
1427
1428 if (aSuccess && SUCCEEDED(rc))
1429 {
1430 /* associate old hard disks with the snapshot and do locking/unlocking*/
1431 fixupMedia(true /* aCommit */, fOnline);
1432
1433 /* inform callbacks */
1434 mParent->onSnapshotTaken(mData->mUuid,
1435 mSnapshotData.mSnapshot->getId());
1436 }
1437 else
1438 {
1439 /* delete all differencing hard disks created (this will also attach
1440 * their parents back by rolling back mMediaData) */
1441 fixupMedia(false /* aCommit */);
1442
1443 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
1444 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
1445
1446 /* delete the saved state file (it might have been already created) */
1447 if (mSnapshotData.mSnapshot->stateFilePath().length())
1448 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
1449
1450 mSnapshotData.mSnapshot->uninit();
1451 }
1452
1453 /* clear out the snapshot data */
1454 mSnapshotData.mLastState = MachineState_Null;
1455 mSnapshotData.mSnapshot.setNull();
1456
1457 LogFlowThisFuncLeave();
1458 return rc;
1459}
1460
1461////////////////////////////////////////////////////////////////////////////////
1462//
1463// RestoreSnapshot methods (SessionMachine and related tasks)
1464//
1465////////////////////////////////////////////////////////////////////////////////
1466
1467/**
1468 * Implementation for IInternalMachineControl::restoreSnapshot().
1469 *
1470 * Gets called from Console::RestoreSnapshot(), and that's basically the
1471 * only thing Console does. Restoring a snapshot happens entirely on the
1472 * server side since the machine cannot be running.
1473 *
1474 * This creates a new thread that does the work and returns a progress
1475 * object to the client which is then returned to the caller of
1476 * Console::RestoreSnapshot().
1477 *
1478 * Actual work then takes place in RestoreSnapshotTask::handler().
1479 *
1480 * @note Locks this + children objects for writing!
1481 *
1482 * @param aInitiator in: rhe console on which Console::RestoreSnapshot was called.
1483 * @param aSnapshot in: the snapshot to restore.
1484 * @param aMachineState in: client-side machine state.
1485 * @param aProgress out: progress object to monitor restore thread.
1486 * @return
1487 */
1488STDMETHODIMP SessionMachine::RestoreSnapshot(IConsole *aInitiator,
1489 ISnapshot *aSnapshot,
1490 MachineState_T *aMachineState,
1491 IProgress **aProgress)
1492{
1493 LogFlowThisFuncEnter();
1494
1495 AssertReturn(aInitiator, E_INVALIDARG);
1496 AssertReturn(aSnapshot && aMachineState && aProgress, E_POINTER);
1497
1498 AutoCaller autoCaller(this);
1499 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1500
1501 AutoWriteLock alock(this);
1502
1503 // machine must not be running
1504 ComAssertRet(!Global::IsOnlineOrTransient(mData->mMachineState),
1505 E_FAIL);
1506
1507 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(aSnapshot));
1508 ComPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
1509
1510 // create a progress object. The number of operations is:
1511 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
1512 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
1513
1514 ULONG ulOpCount = 1; // one for preparations
1515 ULONG ulTotalWeight = 1; // one for preparations
1516 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
1517 it != pSnapMachine->mMediaData->mAttachments.end();
1518 ++it)
1519 {
1520 ComObjPtr<MediumAttachment> &pAttach = *it;
1521 AutoReadLock attachLock(pAttach);
1522 if (pAttach->type() == DeviceType_HardDisk)
1523 {
1524 ++ulOpCount;
1525 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
1526 Assert(pAttach->medium());
1527 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pAttach->medium()->name().c_str()));
1528 }
1529 }
1530
1531 ULONG ulStateFileSizeMB = 0;
1532 if (pSnapshot->stateFilePath().length())
1533 {
1534 ++ulOpCount; // one for the saved state
1535
1536 uint64_t ullSize;
1537 int irc = RTFileQuerySize(pSnapshot->stateFilePath().c_str(), &ullSize);
1538 if (!RT_SUCCESS(irc))
1539 // if we can't access the file here, then we'll be doomed later also, so fail right away
1540 setError(E_FAIL, tr("Cannot access state file '%s', runtime error, %Rra"), pSnapshot->stateFilePath().c_str(), irc);
1541 if (ullSize == 0) // avoid division by zero
1542 ullSize = _1M;
1543
1544 ulStateFileSizeMB = (ULONG)(ullSize / _1M);
1545 LogFlowThisFunc(("op %d: saved state file '%s' has %RI64 bytes (%d MB)\n",
1546 ulOpCount, pSnapshot->stateFilePath().raw(), ullSize, ulStateFileSizeMB));
1547
1548 ulTotalWeight += ulStateFileSizeMB;
1549 }
1550
1551 ComObjPtr<Progress> pProgress;
1552 pProgress.createObject();
1553 pProgress->init(mParent, aInitiator,
1554 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->getName().c_str()),
1555 FALSE /* aCancelable */,
1556 ulOpCount,
1557 ulTotalWeight,
1558 Bstr(tr("Restoring machine settings")),
1559 1);
1560
1561 /* create and start the task on a separate thread (note that it will not
1562 * start working until we release alock) */
1563 RestoreSnapshotTask *task = new RestoreSnapshotTask(this,
1564 pProgress,
1565 pSnapshot,
1566 ulStateFileSizeMB);
1567 int vrc = RTThreadCreate(NULL,
1568 taskHandler,
1569 (void*)task,
1570 0,
1571 RTTHREADTYPE_MAIN_WORKER,
1572 0,
1573 "RestoreSnap");
1574 if (RT_FAILURE(vrc))
1575 {
1576 delete task;
1577 ComAssertRCRet(vrc, E_FAIL);
1578 }
1579
1580 /* set the proper machine state (note: after creating a Task instance) */
1581 setMachineState(MachineState_RestoringSnapshot);
1582
1583 /* return the progress to the caller */
1584 pProgress.queryInterfaceTo(aProgress);
1585
1586 /* return the new state to the caller */
1587 *aMachineState = mData->mMachineState;
1588
1589 LogFlowThisFuncLeave();
1590
1591 return S_OK;
1592}
1593
1594/**
1595 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
1596 * This method gets called indirectly through SessionMachine::taskHandler() which then
1597 * calls RestoreSnapshotTask::handler().
1598 *
1599 * The RestoreSnapshotTask contains the progress object returned to the console by
1600 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
1601 *
1602 * @note Locks mParent + this object for writing.
1603 *
1604 * @param aTask Task data.
1605 */
1606void SessionMachine::restoreSnapshotHandler(RestoreSnapshotTask &aTask)
1607{
1608 LogFlowThisFuncEnter();
1609
1610 AutoCaller autoCaller(this);
1611
1612 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
1613 if (!autoCaller.isOk())
1614 {
1615 /* we might have been uninitialized because the session was accidentally
1616 * closed by the client, so don't assert */
1617 aTask.pProgress->notifyComplete(E_FAIL,
1618 COM_IIDOF(IMachine),
1619 getComponentName(),
1620 tr("The session has been accidentally closed"));
1621
1622 LogFlowThisFuncLeave();
1623 return;
1624 }
1625
1626 /* saveSettings() needs mParent lock */
1627 AutoWriteLock vboxLock(mParent);
1628
1629 /* @todo We don't need mParent lock so far so unlock() it. Better is to
1630 * provide an AutoWriteLock argument that lets create a non-locking
1631 * instance */
1632 vboxLock.unlock();
1633
1634 AutoWriteLock alock(this);
1635
1636 /* discard all current changes to mUserData (name, OSType etc.) (note that
1637 * the machine is powered off, so there is no need to inform the direct
1638 * session) */
1639 if (isModified())
1640 rollback(false /* aNotify */);
1641
1642 HRESULT rc = S_OK;
1643
1644 bool stateRestored = false;
1645
1646 try
1647 {
1648 /* discard the saved state file if the machine was Saved prior to this
1649 * operation */
1650 if (aTask.machineStateBackup == MachineState_Saved)
1651 {
1652 Assert(!mSSData->mStateFilePath.isEmpty());
1653 RTFileDelete(mSSData->mStateFilePath.c_str());
1654 mSSData->mStateFilePath.setNull();
1655 aTask.modifyBackedUpState(MachineState_PoweredOff);
1656 rc = saveStateSettings(SaveSTS_StateFilePath);
1657 CheckComRCThrowRC(rc);
1658 }
1659
1660 RTTIMESPEC snapshotTimeStamp;
1661 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
1662
1663 {
1664 AutoReadLock snapshotLock(aTask.pSnapshot);
1665
1666 /* remember the timestamp of the snapshot we're restoring from */
1667 snapshotTimeStamp = aTask.pSnapshot->getTimeStamp();
1668
1669 ComPtr<SnapshotMachine> pSnapshotMachine(aTask.pSnapshot->getSnapshotMachine());
1670
1671 /* copy all hardware data from the snapshot */
1672 copyFrom(pSnapshotMachine);
1673
1674 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
1675
1676 /* restore the attachments from the snapshot */
1677 mMediaData.backup();
1678 mMediaData->mAttachments = pSnapshotMachine->mMediaData->mAttachments;
1679
1680 /* leave the locks before the potentially lengthy operation */
1681 snapshotLock.unlock();
1682 alock.leave();
1683
1684 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
1685 aTask.pProgress,
1686 1,
1687 false /* aOnline */);
1688
1689 alock.enter();
1690 snapshotLock.lock();
1691
1692 CheckComRCThrowRC(rc);
1693
1694 /* Note: on success, current (old) hard disks will be
1695 * deassociated/deleted on #commit() called from #saveSettings() at
1696 * the end. On failure, newly created implicit diffs will be
1697 * deleted by #rollback() at the end. */
1698
1699 /* should not have a saved state file associated at this point */
1700 Assert(mSSData->mStateFilePath.isEmpty());
1701
1702 if (!aTask.pSnapshot->stateFilePath().isEmpty())
1703 {
1704 Utf8Str snapStateFilePath = aTask.pSnapshot->stateFilePath();
1705
1706 Utf8Str stateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
1707 mUserData->mSnapshotFolderFull.raw(),
1708 RTPATH_DELIMITER,
1709 mData->mUuid.raw());
1710
1711 LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
1712 snapStateFilePath.raw(), stateFilePath.raw()));
1713
1714 aTask.pProgress->SetNextOperation(Bstr(tr("Restoring the execution state")),
1715 aTask.m_ulStateFileSizeMB); // weight
1716
1717 /* leave the lock before the potentially lengthy operation */
1718 snapshotLock.unlock();
1719 alock.leave();
1720
1721 /* copy the state file */
1722 int vrc = RTFileCopyEx(snapStateFilePath.c_str(),
1723 stateFilePath.c_str(),
1724 0,
1725 progressCallback,
1726 static_cast<IProgress*>(aTask.pProgress));
1727
1728 alock.enter();
1729 snapshotLock.lock();
1730
1731 if (RT_SUCCESS(vrc))
1732 mSSData->mStateFilePath = stateFilePath;
1733 else
1734 throw setError(E_FAIL,
1735 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1736 snapStateFilePath.raw(),
1737 stateFilePath.raw(),
1738 vrc);
1739 }
1740
1741 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", aTask.pSnapshot->getId().raw()));
1742 /* make the snapshot we restored from the current snapshot */
1743 mData->mCurrentSnapshot = aTask.pSnapshot;
1744 }
1745
1746 /* grab differencing hard disks from the old attachments that will
1747 * become unused and need to be auto-deleted */
1748
1749 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
1750
1751 for (MediaData::AttachmentList::const_iterator it = mMediaData.backedUpData()->mAttachments.begin();
1752 it != mMediaData.backedUpData()->mAttachments.end();
1753 ++it)
1754 {
1755 ComObjPtr<MediumAttachment> pAttach = *it;
1756 ComObjPtr<Medium> pMedium = pAttach->medium();
1757
1758 /* while the hard disk is attached, the number of children or the
1759 * parent cannot change, so no lock */
1760 if ( !pMedium.isNull()
1761 && pAttach->type() == DeviceType_HardDisk
1762 && !pMedium->parent().isNull()
1763 && pMedium->children().size() == 0
1764 )
1765 {
1766 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->name().raw()));
1767
1768 llDiffAttachmentsToDelete.push_back(pAttach);
1769 }
1770 }
1771
1772 int saveFlags = 0;
1773
1774 /* @todo saveSettings() below needs a VirtualBox write lock and we need
1775 * to leave this object's lock to do this to follow the {parent-child}
1776 * locking rule. This is the last chance to do that while we are still
1777 * in a protective state which allows us to temporarily leave the lock*/
1778 alock.unlock();
1779 vboxLock.lock();
1780 alock.lock();
1781
1782 /* we have already discarded the current state, so set the execution
1783 * state accordingly no matter of the discard snapshot result */
1784 if (!mSSData->mStateFilePath.isEmpty())
1785 setMachineState(MachineState_Saved);
1786 else
1787 setMachineState(MachineState_PoweredOff);
1788
1789 updateMachineStateOnClient();
1790 stateRestored = true;
1791
1792 /* assign the timestamp from the snapshot */
1793 Assert(RTTimeSpecGetMilli (&snapshotTimeStamp) != 0);
1794 mData->mLastStateChange = snapshotTimeStamp;
1795
1796 // detach the current-state diffs that we detected above and build a list of
1797 // images to delete _after_ saveSettings()
1798
1799 std::list< ComObjPtr<Medium> > llDiffsToDelete;
1800
1801 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
1802 it != llDiffAttachmentsToDelete.end();
1803 ++it)
1804 {
1805 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
1806 ComObjPtr<Medium> pMedium = pAttach->medium();
1807
1808 AutoWriteLock mlock(pMedium);
1809
1810 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->name().raw()));
1811
1812 // Normally we "detach" the medium by removing the attachment object
1813 // from the current machine data; saveSettings() below would then
1814 // compare the current machine data with the one in the backup
1815 // and actually call Medium::detachFrom(). But that works only half
1816 // the time in our case so instead we force a detachment here:
1817 // remove from machine data
1818 mMediaData->mAttachments.remove(pAttach);
1819 // remove it from the backup or else saveSettings will try to detach
1820 // it again and assert
1821 mMediaData.backedUpData()->mAttachments.remove(pAttach);
1822 // then clean up backrefs
1823 pMedium->detachFrom(mData->mUuid);
1824
1825 llDiffsToDelete.push_back(pMedium);
1826 }
1827
1828 // save all settings, reset the modified flag and commit;
1829 rc = saveSettings(SaveS_ResetCurStateModified | saveFlags);
1830 CheckComRCThrowRC(rc);
1831 // from here on we cannot roll back on failure any more
1832
1833 for (std::list< ComObjPtr<Medium> >::iterator it = llDiffsToDelete.begin();
1834 it != llDiffsToDelete.end();
1835 ++it)
1836 {
1837 ComObjPtr<Medium> &pMedium = *it;
1838 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->name().raw()));
1839
1840 HRESULT rc2 = pMedium->deleteStorageAndWait();
1841 // ignore errors here because we cannot roll back after saveSettings() above
1842 if (SUCCEEDED(rc2))
1843 pMedium->uninit();
1844 }
1845 }
1846 catch (HRESULT aRC)
1847 {
1848 rc = aRC;
1849 }
1850
1851 if (FAILED(rc))
1852 {
1853 /* preserve existing error info */
1854 ErrorInfoKeeper eik;
1855
1856 /* undo all changes on failure */
1857 rollback(false /* aNotify */);
1858
1859 if (!stateRestored)
1860 {
1861 /* restore the machine state */
1862 setMachineState(aTask.machineStateBackup);
1863 updateMachineStateOnClient();
1864 }
1865 }
1866
1867 /* set the result (this will try to fetch current error info on failure) */
1868 aTask.pProgress->notifyComplete(rc);
1869
1870 if (SUCCEEDED(rc))
1871 mParent->onSnapshotDeleted(mData->mUuid, Guid());
1872
1873 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
1874
1875 LogFlowThisFuncLeave();
1876}
1877
1878////////////////////////////////////////////////////////////////////////////////
1879//
1880// DeleteSnapshot methods (SessionMachine and related tasks)
1881//
1882////////////////////////////////////////////////////////////////////////////////
1883
1884/**
1885 * Implementation for IInternalMachineControl::deleteSnapshot().
1886 *
1887 * Gets called from Console::DeleteSnapshot(), and that's basically the
1888 * only thing Console does. Deleting a snapshot happens entirely on the
1889 * server side since the machine cannot be running.
1890 *
1891 * This creates a new thread that does the work and returns a progress
1892 * object to the client which is then returned to the caller of
1893 * Console::DeleteSnapshot().
1894 *
1895 * Actual work then takes place in DeleteSnapshotTask::handler().
1896 *
1897 * @note Locks mParent + this + children objects for writing!
1898 */
1899STDMETHODIMP SessionMachine::DeleteSnapshot(IConsole *aInitiator,
1900 IN_BSTR aId,
1901 MachineState_T *aMachineState,
1902 IProgress **aProgress)
1903{
1904 LogFlowThisFuncEnter();
1905
1906 Guid id(aId);
1907 AssertReturn(aInitiator && !id.isEmpty(), E_INVALIDARG);
1908 AssertReturn(aMachineState && aProgress, E_POINTER);
1909
1910 AutoCaller autoCaller(this);
1911 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1912
1913 /* saveSettings() needs mParent lock */
1914 AutoMultiWriteLock2 alock(mParent, this);
1915
1916 // machine must not be running
1917 ComAssertRet(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
1918
1919 AutoWriteLock treeLock(snapshotsTreeLockHandle());
1920
1921 ComObjPtr<Snapshot> pSnapshot;
1922 HRESULT rc = findSnapshot(id, pSnapshot, true /* aSetError */);
1923 CheckComRCReturnRC(rc);
1924
1925 AutoWriteLock snapshotLock(pSnapshot);
1926
1927 size_t childrenCount = pSnapshot->getChildrenCount();
1928 if (childrenCount > 1)
1929 return setError(VBOX_E_INVALID_OBJECT_STATE,
1930 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"),
1931 pSnapshot->getName().c_str(),
1932 mUserData->mName.raw(),
1933 childrenCount);
1934
1935 /* If the snapshot being discarded is the current one, ensure current
1936 * settings are committed and saved.
1937 */
1938 if (pSnapshot == mData->mCurrentSnapshot)
1939 {
1940 if (isModified())
1941 {
1942 rc = saveSettings();
1943 CheckComRCReturnRC(rc);
1944 }
1945 }
1946
1947 ComPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
1948
1949 /* create a progress object. The number of operations is:
1950 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
1951 */
1952 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
1953
1954 ULONG ulOpCount = 1; // one for preparations
1955 ULONG ulTotalWeight = 1; // one for preparations
1956
1957 if (pSnapshot->stateFilePath().length())
1958 {
1959 ++ulOpCount;
1960 ++ulTotalWeight; // assume 1 MB for deleting the state file
1961 }
1962
1963 // count normal hard disks and add their sizes to the weight
1964 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
1965 it != pSnapMachine->mMediaData->mAttachments.end();
1966 ++it)
1967 {
1968 ComObjPtr<MediumAttachment> &pAttach = *it;
1969 AutoReadLock attachLock(pAttach);
1970 if (pAttach->type() == DeviceType_HardDisk)
1971 {
1972 Assert(pAttach->medium());
1973 ComObjPtr<Medium> pHD = pAttach->medium();
1974 AutoReadLock mlock(pHD);
1975 if (pHD->type() == MediumType_Normal)
1976 {
1977 ++ulOpCount;
1978 ulTotalWeight += pHD->size() / _1M;
1979 }
1980 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->name().c_str()));
1981 }
1982 }
1983
1984 ComObjPtr<Progress> pProgress;
1985 pProgress.createObject();
1986 pProgress->init(mParent, aInitiator,
1987 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->getName().c_str()),
1988 FALSE /* aCancelable */,
1989 ulOpCount,
1990 ulTotalWeight,
1991 Bstr(tr("Setting up")),
1992 1);
1993
1994 /* create and start the task on a separate thread */
1995 DeleteSnapshotTask *task = new DeleteSnapshotTask(this, pProgress, pSnapshot);
1996 int vrc = RTThreadCreate(NULL,
1997 taskHandler,
1998 (void*)task,
1999 0,
2000 RTTHREADTYPE_MAIN_WORKER,
2001 0,
2002 "DeleteSnapshot");
2003 if (RT_FAILURE(vrc))
2004 {
2005 delete task;
2006 return E_FAIL;
2007 }
2008
2009 /* set the proper machine state (note: after creating a Task instance) */
2010 setMachineState(MachineState_DeletingSnapshot);
2011
2012 /* return the progress to the caller */
2013 pProgress.queryInterfaceTo(aProgress);
2014
2015 /* return the new state to the caller */
2016 *aMachineState = mData->mMachineState;
2017
2018 LogFlowThisFuncLeave();
2019
2020 return S_OK;
2021}
2022
2023/**
2024 * Helper struct for SessionMachine::deleteSnapshotHandler().
2025 */
2026struct MediumDiscardRec
2027{
2028 MediumDiscardRec()
2029 : chain(NULL)
2030 {}
2031
2032 MediumDiscardRec(const ComObjPtr<Medium> &aHd,
2033 Medium::MergeChain *aChain = NULL)
2034 : hd(aHd),
2035 chain(aChain)
2036 {}
2037
2038 MediumDiscardRec(const ComObjPtr<Medium> &aHd,
2039 Medium::MergeChain *aChain,
2040 const ComObjPtr<Medium> &aReplaceHd,
2041 const ComObjPtr<MediumAttachment> &aReplaceHda,
2042 const Guid &aSnapshotId)
2043 : hd(aHd),
2044 chain(aChain),
2045 replaceHd(aReplaceHd),
2046 replaceHda(aReplaceHda),
2047 snapshotId(aSnapshotId)
2048 {}
2049
2050 ComObjPtr<Medium> hd;
2051 Medium::MergeChain *chain;
2052 /* these are for the replace hard disk case: */
2053 ComObjPtr<Medium> replaceHd;
2054 ComObjPtr<MediumAttachment> replaceHda;
2055 Guid snapshotId;
2056};
2057
2058typedef std::list <MediumDiscardRec> MediumDiscardRecList;
2059
2060/**
2061 * Worker method for the delete snapshot thread created by SessionMachine::DeleteSnapshot().
2062 * This method gets called indirectly through SessionMachine::taskHandler() which then
2063 * calls DeleteSnapshotTask::handler().
2064 *
2065 * The DeleteSnapshotTask contains the progress object returned to the console by
2066 * SessionMachine::DeleteSnapshot, through which progress and results are reported.
2067 *
2068 * @note Locks mParent + this + child objects for writing!
2069 *
2070 * @param aTask Task data.
2071 */
2072void SessionMachine::deleteSnapshotHandler(DeleteSnapshotTask &aTask)
2073{
2074 LogFlowThisFuncEnter();
2075
2076 AutoCaller autoCaller(this);
2077
2078 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
2079 if (!autoCaller.isOk())
2080 {
2081 /* we might have been uninitialized because the session was accidentally
2082 * closed by the client, so don't assert */
2083 aTask.pProgress->notifyComplete(E_FAIL,
2084 COM_IIDOF(IMachine),
2085 getComponentName(),
2086 tr("The session has been accidentally closed"));
2087 LogFlowThisFuncLeave();
2088 return;
2089 }
2090
2091 /* Locking order: */
2092 AutoMultiWriteLock3 alock(this->lockHandle(),
2093 this->snapshotsTreeLockHandle(),
2094 aTask.pSnapshot->lockHandle());
2095
2096 ComPtr<SnapshotMachine> pSnapMachine = aTask.pSnapshot->getSnapshotMachine();
2097 /* no need to lock the snapshot machine since it is const by definiton */
2098
2099 HRESULT rc = S_OK;
2100
2101 /* save the snapshot ID (for callbacks) */
2102 Guid snapshotId = aTask.pSnapshot->getId();
2103
2104 MediumDiscardRecList toDiscard;
2105
2106 bool settingsChanged = false;
2107
2108 try
2109 {
2110 /* first pass: */
2111 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2112
2113 // go thru the attachments of the snapshot machine
2114 // (the media in here point to the disk states _before_ the snapshot
2115 // was taken, i.e. the state we're restoring to; for each such
2116 // medium, we will need to merge it with its one and only child (the
2117 // diff image holding the changes written after the snapshot was taken)
2118 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2119 it != pSnapMachine->mMediaData->mAttachments.end();
2120 ++it)
2121 {
2122 ComObjPtr<MediumAttachment> &pAttach = *it;
2123 AutoReadLock attachLock(pAttach);
2124 if (pAttach->type() == DeviceType_HardDisk)
2125 {
2126 Assert(pAttach->medium());
2127 ComObjPtr<Medium> pHD = pAttach->medium();
2128 // do not lock, prepareDiscared() has a write lock which will hang otherwise
2129
2130#ifdef DEBUG
2131 pHD->dumpBackRefs();
2132#endif
2133
2134 Medium::MergeChain *chain = NULL;
2135
2136 // needs to be discarded (merged with the child if any), check prerequisites
2137 rc = pHD->prepareDiscard(chain);
2138 CheckComRCThrowRC(rc);
2139
2140 // for simplicity, we merge pHd onto its child (forward merge), not the
2141 // other way round, because that saves us from updating the attachments
2142 // for the machine that follows the snapshot (next snapshot or real machine),
2143 // unless it's a base image:
2144
2145 if ( pHD->parent().isNull()
2146 && chain != NULL
2147 )
2148 {
2149 // parent is null -> this disk is a base hard disk: we will
2150 // then do a backward merge, i.e. merge its only child onto
2151 // the base disk; prepareDiscard() does necessary checks.
2152 // So here we need then to update the attachment that refers
2153 // to the child and have it point to the parent instead
2154
2155 /* The below assert would be nice but I don't want to move
2156 * Medium::MergeChain to the header just for that
2157 * Assert (!chain->isForward()); */
2158
2159 // prepareDiscard() should have raised an error already
2160 // if there was more than one child
2161 Assert(pHD->children().size() == 1);
2162
2163 ComObjPtr<Medium> pReplaceHD = pHD->children().front();
2164
2165 const Guid *pReplaceMachineId = pReplaceHD->getFirstMachineBackrefId();
2166 NOREF(pReplaceMachineId);
2167 Assert(pReplaceMachineId);
2168 Assert(*pReplaceMachineId == mData->mUuid);
2169
2170 Guid snapshotId;
2171 const Guid *pSnapshotId = pReplaceHD->getFirstMachineBackrefSnapshotId();
2172 if (pSnapshotId)
2173 snapshotId = *pSnapshotId;
2174
2175 HRESULT rc2 = S_OK;
2176
2177 attachLock.unlock();
2178
2179 // First we must detach the child (otherwise mergeTo() called
2180 // by discard() will assert because it will be going to delete
2181 // the child), so adjust the backreferences:
2182 // 1) detach the first child hard disk
2183 rc2 = pReplaceHD->detachFrom(mData->mUuid, snapshotId);
2184 AssertComRC(rc2);
2185 // 2) attach to machine and snapshot
2186 rc2 = pHD->attachTo(mData->mUuid, snapshotId);
2187 AssertComRC(rc2);
2188
2189 /* replace the hard disk in the attachment object */
2190 if (snapshotId.isEmpty())
2191 {
2192 /* in current state */
2193 AssertBreak(pAttach = findAttachment(mMediaData->mAttachments, pReplaceHD));
2194 }
2195 else
2196 {
2197 /* in snapshot */
2198 ComObjPtr<Snapshot> snapshot;
2199 rc2 = findSnapshot(snapshotId, snapshot);
2200 AssertComRC(rc2);
2201
2202 /* don't lock the snapshot; cannot be modified outside */
2203 MediaData::AttachmentList &snapAtts = snapshot->getSnapshotMachine()->mMediaData->mAttachments;
2204 AssertBreak(pAttach = findAttachment(snapAtts, pReplaceHD));
2205 }
2206
2207 AutoWriteLock attLock(pAttach);
2208 pAttach->updateMedium(pHD, false /* aImplicit */);
2209
2210 toDiscard.push_back(MediumDiscardRec(pHD,
2211 chain,
2212 pReplaceHD,
2213 pAttach,
2214 snapshotId));
2215 continue;
2216 }
2217
2218 toDiscard.push_back(MediumDiscardRec(pHD, chain));
2219 }
2220 }
2221
2222 /* Now we checked that we can successfully merge all normal hard disks
2223 * (unless a runtime error like end-of-disc happens). Prior to
2224 * performing the actual merge, we want to discard the snapshot itself
2225 * and remove it from the XML file to make sure that a possible merge
2226 * ruintime error will not make this snapshot inconsistent because of
2227 * the partially merged or corrupted hard disks */
2228
2229 /* second pass: */
2230 LogFlowThisFunc(("2: Discarding snapshot...\n"));
2231
2232 {
2233 ComObjPtr<Snapshot> parentSnapshot = aTask.pSnapshot->parent();
2234 Utf8Str stateFilePath = aTask.pSnapshot->stateFilePath();
2235
2236 /* Note that discarding the snapshot will deassociate it from the
2237 * hard disks which will allow the merge+delete operation for them*/
2238 aTask.pSnapshot->beginDiscard();
2239 aTask.pSnapshot->uninit();
2240
2241 rc = saveAllSnapshots();
2242 CheckComRCThrowRC(rc);
2243
2244 /// @todo (dmik)
2245 // if we implement some warning mechanism later, we'll have
2246 // to return a warning if the state file path cannot be deleted
2247 if (!stateFilePath.isEmpty())
2248 {
2249 aTask.pProgress->SetNextOperation(Bstr(tr("Discarding the execution state")),
2250 1); // weight
2251
2252 RTFileDelete(stateFilePath.c_str());
2253 }
2254
2255 /// @todo NEWMEDIA to provide a good level of fauilt tolerance, we
2256 /// should restore the shapshot in the snapshot tree if
2257 /// saveSnapshotSettings fails. Actually, we may call
2258 /// #saveSnapshotSettings() with a special flag that will tell it to
2259 /// skip the given snapshot as if it would have been discarded and
2260 /// only actually discard it if the save operation succeeds.
2261 }
2262
2263 /* here we come when we've irrevesibly discarded the snapshot which
2264 * means that the VM settigns (our relevant changes to mData) need to be
2265 * saved too */
2266 /// @todo NEWMEDIA maybe save everything in one operation in place of
2267 /// saveSnapshotSettings() above
2268 settingsChanged = true;
2269
2270 /* third pass: */
2271 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
2272
2273 /* leave the locks before the potentially lengthy operation */
2274 alock.leave();
2275
2276 /// @todo NEWMEDIA turn the following errors into warnings because the
2277 /// snapshot itself has been already deleted (and interpret these
2278 /// warnings properly on the GUI side)
2279
2280 for (MediumDiscardRecList::iterator it = toDiscard.begin();
2281 it != toDiscard.end();)
2282 {
2283 rc = it->hd->discard(aTask.pProgress,
2284 it->hd->size() / _1M, // weight
2285 it->chain);
2286 CheckComRCBreakRC(rc);
2287
2288 /* prevent from calling cancelDiscard() */
2289 it = toDiscard.erase(it);
2290 }
2291
2292 LogFlowThisFunc(("Entering locks again...\n"));
2293 alock.enter();
2294 LogFlowThisFunc(("Entered locks OK\n"));
2295
2296 CheckComRCThrowRC(rc);
2297 }
2298 catch (HRESULT aRC) { rc = aRC; }
2299
2300 if (FAILED(rc))
2301 {
2302 HRESULT rc2 = S_OK;
2303
2304 /* un-prepare the remaining hard disks */
2305 for (MediumDiscardRecList::const_iterator it = toDiscard.begin();
2306 it != toDiscard.end(); ++it)
2307 {
2308 it->hd->cancelDiscard (it->chain);
2309
2310 if (!it->replaceHd.isNull())
2311 {
2312 /* undo hard disk replacement */
2313
2314 rc2 = it->replaceHd->attachTo (mData->mUuid, it->snapshotId);
2315 AssertComRC(rc2);
2316
2317 rc2 = it->hd->detachFrom (mData->mUuid, it->snapshotId);
2318 AssertComRC(rc2);
2319
2320 AutoWriteLock attLock (it->replaceHda);
2321 it->replaceHda->updateMedium(it->replaceHd, false /* aImplicit */);
2322 }
2323 }
2324 }
2325
2326 alock.unlock();
2327
2328 // whether we were successful or not, we need to set the machine
2329 // state and save the machine settings;
2330 {
2331 // preserve existing error info so that the result can
2332 // be properly reported to the progress object below
2333 ErrorInfoKeeper eik;
2334
2335 // restore the machine state that was saved when the
2336 // task was started
2337 setMachineState(aTask.machineStateBackup);
2338 updateMachineStateOnClient();
2339
2340 if (settingsChanged)
2341 {
2342 // saveSettings needs VirtualBox write lock in addition to our own
2343 // (parent -> child locking order!)
2344 AutoWriteLock vboxLock(mParent);
2345 alock.lock();
2346
2347 saveSettings(SaveS_InformCallbacksAnyway);
2348 }
2349 }
2350
2351 // report the result (this will try to fetch current error info on failure)
2352 aTask.pProgress->notifyComplete(rc);
2353
2354 if (SUCCEEDED(rc))
2355 mParent->onSnapshotDeleted(mData->mUuid, snapshotId);
2356
2357 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", rc));
2358 LogFlowThisFuncLeave();
2359}
2360
Note: See TracBrowser for help on using the repository browser.

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