VirtualBox

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

Last change on this file since 24968 was 24920, checked in by vboxsync, 15 years ago

SnapshotImpl.cpp: BeginSnapshot error path (#4486).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 77.3 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' fTakingSnapshotOnline=%RTbool\n", aName, fTakingSnapshotOnline));
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 if (FAILED(rc))
1286 throw rc;
1287
1288 if (mSnapshotData.mLastState == MachineState_Saved)
1289 {
1290 Utf8Str stateFrom = mSSData->mStateFilePath;
1291 Utf8Str stateTo = mSnapshotData.mSnapshot->stateFilePath();
1292
1293 LogFlowThisFunc(("Copying the execution state from '%s' to '%s'...\n",
1294 stateFrom.raw(), stateTo.raw()));
1295
1296 aConsoleProgress->SetNextOperation(Bstr(tr("Copying the execution state")),
1297 1); // weight
1298
1299 /* Leave the lock before a lengthy operation (mMachineState is
1300 * MachineState_Saving here) */
1301 alock.leave();
1302
1303 /* copy the state file */
1304 int vrc = RTFileCopyEx(stateFrom.c_str(),
1305 stateTo.c_str(),
1306 0,
1307 progressCallback,
1308 aConsoleProgress);
1309 alock.enter();
1310
1311 if (RT_FAILURE(vrc))
1312 {
1313 /** @todo r=bird: Delete stateTo when appropriate. */
1314 throw setError(E_FAIL,
1315 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1316 stateFrom.raw(),
1317 stateTo.raw(),
1318 vrc);
1319 }
1320 }
1321 }
1322 catch (HRESULT hrc)
1323 {
1324 LogThisFunc(("Caught %Rhrc [%s]\n", hrc, Global::stringifyMachineState(mData->mMachineState) ));
1325 if ( mSnapshotData.mLastState != mData->mMachineState
1326 && ( mSnapshotData.mLastState == MachineState_Running
1327 ? mData->mMachineState == MachineState_LiveSnapshotting
1328 : mData->mMachineState == MachineState_Saving)
1329 )
1330 setMachineState(mSnapshotData.mLastState);
1331
1332 pSnapshot->uninit();
1333 pSnapshot.setNull();
1334 mSnapshotData.mLastState = MachineState_Null;
1335 mSnapshotData.mSnapshot.setNull();
1336
1337 rc = hrc;
1338 }
1339
1340 if (fTakingSnapshotOnline && SUCCEEDED(rc))
1341 strStateFilePath.cloneTo(aStateFilePath);
1342 else
1343 *aStateFilePath = NULL;
1344
1345 LogFlowThisFunc(("LEAVE - %Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
1346 return rc;
1347}
1348
1349/**
1350 * Implementation for IInternalMachineControl::beginTakingSnapshot().
1351 *
1352 * Called by the Console when it's done saving the VM state into the snapshot
1353 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
1354 *
1355 * This also gets called if the console part of snapshotting failed after the
1356 * BeginTakingSnapshot() call, to clean up the server side.
1357 *
1358 * @note Locks this object for writing.
1359 *
1360 * @param aSuccess Whether Console was successful with the client-side snapshot things.
1361 * @return
1362 */
1363STDMETHODIMP SessionMachine::EndTakingSnapshot(BOOL aSuccess)
1364{
1365 LogFlowThisFunc(("\n"));
1366
1367 AutoCaller autoCaller(this);
1368 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1369
1370 AutoWriteLock alock(this);
1371
1372 AssertReturn( !aSuccess
1373 || ( ( mData->mMachineState == MachineState_Saving
1374 || mData->mMachineState == MachineState_LiveSnapshotting)
1375 && mSnapshotData.mLastState != MachineState_Null
1376 && !mSnapshotData.mSnapshot.isNull()
1377 )
1378 , E_FAIL);
1379
1380 /*
1381 * Restore the state we had when BeginTakingSnapshot() was called,
1382 * Console::fntTakeSnapshotWorker restores its local copy when we return.
1383 * If the state was Running, then let Console::fntTakeSnapshotWorker do it
1384 * all to avoid races.
1385 */
1386 if ( mData->mMachineState != mSnapshotData.mLastState
1387 && mSnapshotData.mLastState != MachineState_Running)
1388 setMachineState(mSnapshotData.mLastState);
1389
1390 return endTakingSnapshot(aSuccess);
1391}
1392
1393/**
1394 * Internal helper method to finalize taking a snapshot. Gets called from
1395 * SessionMachine::EndTakingSnapshot() to finalize the server-side
1396 * parts of snapshotting.
1397 *
1398 * This also gets called from SessionMachine::uninit() if an untaken
1399 * snapshot needs cleaning up.
1400 *
1401 * Expected to be called after completing *all* the tasks related to
1402 * taking the snapshot, either successfully or unsuccessfilly.
1403 *
1404 * @param aSuccess TRUE if the snapshot has been taken successfully.
1405 *
1406 * @note Locks this objects for writing.
1407 */
1408HRESULT SessionMachine::endTakingSnapshot(BOOL aSuccess)
1409{
1410 LogFlowThisFuncEnter();
1411
1412 AutoCaller autoCaller(this);
1413 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1414
1415 AutoMultiWriteLock2 alock(mParent, this);
1416 // saveSettings needs VirtualBox lock
1417
1418 AssertReturn(!mSnapshotData.mSnapshot.isNull(), E_FAIL);
1419
1420 MultiResult rc(S_OK);
1421
1422 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
1423 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
1424
1425 bool fOnline = Global::IsOnline(mSnapshotData.mLastState);
1426
1427 if (aSuccess)
1428 {
1429 // new snapshot becomes the current one
1430 mData->mCurrentSnapshot = mSnapshotData.mSnapshot;
1431
1432 /* memorize the first snapshot if necessary */
1433 if (!mData->mFirstSnapshot)
1434 mData->mFirstSnapshot = mData->mCurrentSnapshot;
1435
1436 if (!fOnline)
1437 /* the machine was powered off or saved when taking a snapshot, so
1438 * reset the mCurrentStateModified flag */
1439 mData->mCurrentStateModified = FALSE;
1440
1441 rc = saveSettings();
1442 }
1443
1444 if (aSuccess && SUCCEEDED(rc))
1445 {
1446 /* associate old hard disks with the snapshot and do locking/unlocking*/
1447 fixupMedia(true /* aCommit */, fOnline);
1448
1449 /* inform callbacks */
1450 mParent->onSnapshotTaken(mData->mUuid,
1451 mSnapshotData.mSnapshot->getId());
1452 }
1453 else
1454 {
1455 /* delete all differencing hard disks created (this will also attach
1456 * their parents back by rolling back mMediaData) */
1457 fixupMedia(false /* aCommit */);
1458
1459 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
1460 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
1461
1462 /* delete the saved state file (it might have been already created) */
1463 if (mSnapshotData.mSnapshot->stateFilePath().length())
1464 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
1465
1466 mSnapshotData.mSnapshot->uninit();
1467 }
1468
1469 /* clear out the snapshot data */
1470 mSnapshotData.mLastState = MachineState_Null;
1471 mSnapshotData.mSnapshot.setNull();
1472
1473 LogFlowThisFuncLeave();
1474 return rc;
1475}
1476
1477////////////////////////////////////////////////////////////////////////////////
1478//
1479// RestoreSnapshot methods (SessionMachine and related tasks)
1480//
1481////////////////////////////////////////////////////////////////////////////////
1482
1483/**
1484 * Implementation for IInternalMachineControl::restoreSnapshot().
1485 *
1486 * Gets called from Console::RestoreSnapshot(), and that's basically the
1487 * only thing Console does. Restoring a snapshot happens entirely on the
1488 * server side since the machine cannot be running.
1489 *
1490 * This creates a new thread that does the work and returns a progress
1491 * object to the client which is then returned to the caller of
1492 * Console::RestoreSnapshot().
1493 *
1494 * Actual work then takes place in RestoreSnapshotTask::handler().
1495 *
1496 * @note Locks this + children objects for writing!
1497 *
1498 * @param aInitiator in: rhe console on which Console::RestoreSnapshot was called.
1499 * @param aSnapshot in: the snapshot to restore.
1500 * @param aMachineState in: client-side machine state.
1501 * @param aProgress out: progress object to monitor restore thread.
1502 * @return
1503 */
1504STDMETHODIMP SessionMachine::RestoreSnapshot(IConsole *aInitiator,
1505 ISnapshot *aSnapshot,
1506 MachineState_T *aMachineState,
1507 IProgress **aProgress)
1508{
1509 LogFlowThisFuncEnter();
1510
1511 AssertReturn(aInitiator, E_INVALIDARG);
1512 AssertReturn(aSnapshot && aMachineState && aProgress, E_POINTER);
1513
1514 AutoCaller autoCaller(this);
1515 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1516
1517 AutoWriteLock alock(this);
1518
1519 // machine must not be running
1520 ComAssertRet(!Global::IsOnlineOrTransient(mData->mMachineState),
1521 E_FAIL);
1522
1523 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(aSnapshot));
1524 ComPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
1525
1526 // create a progress object. The number of operations is:
1527 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
1528 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
1529
1530 ULONG ulOpCount = 1; // one for preparations
1531 ULONG ulTotalWeight = 1; // one for preparations
1532 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
1533 it != pSnapMachine->mMediaData->mAttachments.end();
1534 ++it)
1535 {
1536 ComObjPtr<MediumAttachment> &pAttach = *it;
1537 AutoReadLock attachLock(pAttach);
1538 if (pAttach->type() == DeviceType_HardDisk)
1539 {
1540 ++ulOpCount;
1541 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
1542 Assert(pAttach->medium());
1543 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pAttach->medium()->name().c_str()));
1544 }
1545 }
1546
1547 ULONG ulStateFileSizeMB = 0;
1548 if (pSnapshot->stateFilePath().length())
1549 {
1550 ++ulOpCount; // one for the saved state
1551
1552 uint64_t ullSize;
1553 int irc = RTFileQuerySize(pSnapshot->stateFilePath().c_str(), &ullSize);
1554 if (!RT_SUCCESS(irc))
1555 // if we can't access the file here, then we'll be doomed later also, so fail right away
1556 setError(E_FAIL, tr("Cannot access state file '%s', runtime error, %Rra"), pSnapshot->stateFilePath().c_str(), irc);
1557 if (ullSize == 0) // avoid division by zero
1558 ullSize = _1M;
1559
1560 ulStateFileSizeMB = (ULONG)(ullSize / _1M);
1561 LogFlowThisFunc(("op %d: saved state file '%s' has %RI64 bytes (%d MB)\n",
1562 ulOpCount, pSnapshot->stateFilePath().raw(), ullSize, ulStateFileSizeMB));
1563
1564 ulTotalWeight += ulStateFileSizeMB;
1565 }
1566
1567 ComObjPtr<Progress> pProgress;
1568 pProgress.createObject();
1569 pProgress->init(mParent, aInitiator,
1570 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->getName().c_str()),
1571 FALSE /* aCancelable */,
1572 ulOpCount,
1573 ulTotalWeight,
1574 Bstr(tr("Restoring machine settings")),
1575 1);
1576
1577 /* create and start the task on a separate thread (note that it will not
1578 * start working until we release alock) */
1579 RestoreSnapshotTask *task = new RestoreSnapshotTask(this,
1580 pProgress,
1581 pSnapshot,
1582 ulStateFileSizeMB);
1583 int vrc = RTThreadCreate(NULL,
1584 taskHandler,
1585 (void*)task,
1586 0,
1587 RTTHREADTYPE_MAIN_WORKER,
1588 0,
1589 "RestoreSnap");
1590 if (RT_FAILURE(vrc))
1591 {
1592 delete task;
1593 ComAssertRCRet(vrc, E_FAIL);
1594 }
1595
1596 /* set the proper machine state (note: after creating a Task instance) */
1597 setMachineState(MachineState_RestoringSnapshot);
1598
1599 /* return the progress to the caller */
1600 pProgress.queryInterfaceTo(aProgress);
1601
1602 /* return the new state to the caller */
1603 *aMachineState = mData->mMachineState;
1604
1605 LogFlowThisFuncLeave();
1606
1607 return S_OK;
1608}
1609
1610/**
1611 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
1612 * This method gets called indirectly through SessionMachine::taskHandler() which then
1613 * calls RestoreSnapshotTask::handler().
1614 *
1615 * The RestoreSnapshotTask contains the progress object returned to the console by
1616 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
1617 *
1618 * @note Locks mParent + this object for writing.
1619 *
1620 * @param aTask Task data.
1621 */
1622void SessionMachine::restoreSnapshotHandler(RestoreSnapshotTask &aTask)
1623{
1624 LogFlowThisFuncEnter();
1625
1626 AutoCaller autoCaller(this);
1627
1628 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
1629 if (!autoCaller.isOk())
1630 {
1631 /* we might have been uninitialized because the session was accidentally
1632 * closed by the client, so don't assert */
1633 aTask.pProgress->notifyComplete(E_FAIL,
1634 COM_IIDOF(IMachine),
1635 getComponentName(),
1636 tr("The session has been accidentally closed"));
1637
1638 LogFlowThisFuncLeave();
1639 return;
1640 }
1641
1642 /* saveSettings() needs mParent lock */
1643 AutoWriteLock vboxLock(mParent);
1644
1645 /* @todo We don't need mParent lock so far so unlock() it. Better is to
1646 * provide an AutoWriteLock argument that lets create a non-locking
1647 * instance */
1648 vboxLock.unlock();
1649
1650 AutoWriteLock alock(this);
1651
1652 /* discard all current changes to mUserData (name, OSType etc.) (note that
1653 * the machine is powered off, so there is no need to inform the direct
1654 * session) */
1655 if (isModified())
1656 rollback(false /* aNotify */);
1657
1658 HRESULT rc = S_OK;
1659
1660 bool stateRestored = false;
1661
1662 try
1663 {
1664 /* discard the saved state file if the machine was Saved prior to this
1665 * operation */
1666 if (aTask.machineStateBackup == MachineState_Saved)
1667 {
1668 Assert(!mSSData->mStateFilePath.isEmpty());
1669 RTFileDelete(mSSData->mStateFilePath.c_str());
1670 mSSData->mStateFilePath.setNull();
1671 aTask.modifyBackedUpState(MachineState_PoweredOff);
1672 rc = saveStateSettings(SaveSTS_StateFilePath);
1673 CheckComRCThrowRC(rc);
1674 }
1675
1676 RTTIMESPEC snapshotTimeStamp;
1677 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
1678
1679 {
1680 AutoReadLock snapshotLock(aTask.pSnapshot);
1681
1682 /* remember the timestamp of the snapshot we're restoring from */
1683 snapshotTimeStamp = aTask.pSnapshot->getTimeStamp();
1684
1685 ComPtr<SnapshotMachine> pSnapshotMachine(aTask.pSnapshot->getSnapshotMachine());
1686
1687 /* copy all hardware data from the snapshot */
1688 copyFrom(pSnapshotMachine);
1689
1690 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
1691
1692 /* restore the attachments from the snapshot */
1693 mMediaData.backup();
1694 mMediaData->mAttachments = pSnapshotMachine->mMediaData->mAttachments;
1695
1696 /* leave the locks before the potentially lengthy operation */
1697 snapshotLock.unlock();
1698 alock.leave();
1699
1700 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
1701 aTask.pProgress,
1702 1,
1703 false /* aOnline */);
1704
1705 alock.enter();
1706 snapshotLock.lock();
1707
1708 CheckComRCThrowRC(rc);
1709
1710 /* Note: on success, current (old) hard disks will be
1711 * deassociated/deleted on #commit() called from #saveSettings() at
1712 * the end. On failure, newly created implicit diffs will be
1713 * deleted by #rollback() at the end. */
1714
1715 /* should not have a saved state file associated at this point */
1716 Assert(mSSData->mStateFilePath.isEmpty());
1717
1718 if (!aTask.pSnapshot->stateFilePath().isEmpty())
1719 {
1720 Utf8Str snapStateFilePath = aTask.pSnapshot->stateFilePath();
1721
1722 Utf8Str stateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
1723 mUserData->mSnapshotFolderFull.raw(),
1724 RTPATH_DELIMITER,
1725 mData->mUuid.raw());
1726
1727 LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
1728 snapStateFilePath.raw(), stateFilePath.raw()));
1729
1730 aTask.pProgress->SetNextOperation(Bstr(tr("Restoring the execution state")),
1731 aTask.m_ulStateFileSizeMB); // weight
1732
1733 /* leave the lock before the potentially lengthy operation */
1734 snapshotLock.unlock();
1735 alock.leave();
1736
1737 /* copy the state file */
1738 int vrc = RTFileCopyEx(snapStateFilePath.c_str(),
1739 stateFilePath.c_str(),
1740 0,
1741 progressCallback,
1742 static_cast<IProgress*>(aTask.pProgress));
1743
1744 alock.enter();
1745 snapshotLock.lock();
1746
1747 if (RT_SUCCESS(vrc))
1748 mSSData->mStateFilePath = stateFilePath;
1749 else
1750 throw setError(E_FAIL,
1751 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1752 snapStateFilePath.raw(),
1753 stateFilePath.raw(),
1754 vrc);
1755 }
1756
1757 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", aTask.pSnapshot->getId().raw()));
1758 /* make the snapshot we restored from the current snapshot */
1759 mData->mCurrentSnapshot = aTask.pSnapshot;
1760 }
1761
1762 /* grab differencing hard disks from the old attachments that will
1763 * become unused and need to be auto-deleted */
1764
1765 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
1766
1767 for (MediaData::AttachmentList::const_iterator it = mMediaData.backedUpData()->mAttachments.begin();
1768 it != mMediaData.backedUpData()->mAttachments.end();
1769 ++it)
1770 {
1771 ComObjPtr<MediumAttachment> pAttach = *it;
1772 ComObjPtr<Medium> pMedium = pAttach->medium();
1773
1774 /* while the hard disk is attached, the number of children or the
1775 * parent cannot change, so no lock */
1776 if ( !pMedium.isNull()
1777 && pAttach->type() == DeviceType_HardDisk
1778 && !pMedium->parent().isNull()
1779 && pMedium->children().size() == 0
1780 )
1781 {
1782 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->name().raw()));
1783
1784 llDiffAttachmentsToDelete.push_back(pAttach);
1785 }
1786 }
1787
1788 int saveFlags = 0;
1789
1790 /* @todo saveSettings() below needs a VirtualBox write lock and we need
1791 * to leave this object's lock to do this to follow the {parent-child}
1792 * locking rule. This is the last chance to do that while we are still
1793 * in a protective state which allows us to temporarily leave the lock*/
1794 alock.unlock();
1795 vboxLock.lock();
1796 alock.lock();
1797
1798 /* we have already discarded the current state, so set the execution
1799 * state accordingly no matter of the discard snapshot result */
1800 if (!mSSData->mStateFilePath.isEmpty())
1801 setMachineState(MachineState_Saved);
1802 else
1803 setMachineState(MachineState_PoweredOff);
1804
1805 updateMachineStateOnClient();
1806 stateRestored = true;
1807
1808 /* assign the timestamp from the snapshot */
1809 Assert(RTTimeSpecGetMilli (&snapshotTimeStamp) != 0);
1810 mData->mLastStateChange = snapshotTimeStamp;
1811
1812 // detach the current-state diffs that we detected above and build a list of
1813 // images to delete _after_ saveSettings()
1814
1815 std::list< ComObjPtr<Medium> > llDiffsToDelete;
1816
1817 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
1818 it != llDiffAttachmentsToDelete.end();
1819 ++it)
1820 {
1821 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
1822 ComObjPtr<Medium> pMedium = pAttach->medium();
1823
1824 AutoWriteLock mlock(pMedium);
1825
1826 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->name().raw()));
1827
1828 // Normally we "detach" the medium by removing the attachment object
1829 // from the current machine data; saveSettings() below would then
1830 // compare the current machine data with the one in the backup
1831 // and actually call Medium::detachFrom(). But that works only half
1832 // the time in our case so instead we force a detachment here:
1833 // remove from machine data
1834 mMediaData->mAttachments.remove(pAttach);
1835 // remove it from the backup or else saveSettings will try to detach
1836 // it again and assert
1837 mMediaData.backedUpData()->mAttachments.remove(pAttach);
1838 // then clean up backrefs
1839 pMedium->detachFrom(mData->mUuid);
1840
1841 llDiffsToDelete.push_back(pMedium);
1842 }
1843
1844 // save all settings, reset the modified flag and commit;
1845 rc = saveSettings(SaveS_ResetCurStateModified | saveFlags);
1846 CheckComRCThrowRC(rc);
1847 // from here on we cannot roll back on failure any more
1848
1849 for (std::list< ComObjPtr<Medium> >::iterator it = llDiffsToDelete.begin();
1850 it != llDiffsToDelete.end();
1851 ++it)
1852 {
1853 ComObjPtr<Medium> &pMedium = *it;
1854 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->name().raw()));
1855
1856 HRESULT rc2 = pMedium->deleteStorageAndWait();
1857 // ignore errors here because we cannot roll back after saveSettings() above
1858 if (SUCCEEDED(rc2))
1859 pMedium->uninit();
1860 }
1861 }
1862 catch (HRESULT aRC)
1863 {
1864 rc = aRC;
1865 }
1866
1867 if (FAILED(rc))
1868 {
1869 /* preserve existing error info */
1870 ErrorInfoKeeper eik;
1871
1872 /* undo all changes on failure */
1873 rollback(false /* aNotify */);
1874
1875 if (!stateRestored)
1876 {
1877 /* restore the machine state */
1878 setMachineState(aTask.machineStateBackup);
1879 updateMachineStateOnClient();
1880 }
1881 }
1882
1883 /* set the result (this will try to fetch current error info on failure) */
1884 aTask.pProgress->notifyComplete(rc);
1885
1886 if (SUCCEEDED(rc))
1887 mParent->onSnapshotDeleted(mData->mUuid, Guid());
1888
1889 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
1890
1891 LogFlowThisFuncLeave();
1892}
1893
1894////////////////////////////////////////////////////////////////////////////////
1895//
1896// DeleteSnapshot methods (SessionMachine and related tasks)
1897//
1898////////////////////////////////////////////////////////////////////////////////
1899
1900/**
1901 * Implementation for IInternalMachineControl::deleteSnapshot().
1902 *
1903 * Gets called from Console::DeleteSnapshot(), and that's basically the
1904 * only thing Console does. Deleting a snapshot happens entirely on the
1905 * server side since the machine cannot be running.
1906 *
1907 * This creates a new thread that does the work and returns a progress
1908 * object to the client which is then returned to the caller of
1909 * Console::DeleteSnapshot().
1910 *
1911 * Actual work then takes place in DeleteSnapshotTask::handler().
1912 *
1913 * @note Locks mParent + this + children objects for writing!
1914 */
1915STDMETHODIMP SessionMachine::DeleteSnapshot(IConsole *aInitiator,
1916 IN_BSTR aId,
1917 MachineState_T *aMachineState,
1918 IProgress **aProgress)
1919{
1920 LogFlowThisFuncEnter();
1921
1922 Guid id(aId);
1923 AssertReturn(aInitiator && !id.isEmpty(), E_INVALIDARG);
1924 AssertReturn(aMachineState && aProgress, E_POINTER);
1925
1926 AutoCaller autoCaller(this);
1927 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1928
1929 /* saveSettings() needs mParent lock */
1930 AutoMultiWriteLock2 alock(mParent, this);
1931
1932 // machine must not be running
1933 ComAssertRet(!Global::IsOnlineOrTransient(mData->mMachineState), E_FAIL);
1934
1935 AutoWriteLock treeLock(snapshotsTreeLockHandle());
1936
1937 ComObjPtr<Snapshot> pSnapshot;
1938 HRESULT rc = findSnapshot(id, pSnapshot, true /* aSetError */);
1939 CheckComRCReturnRC(rc);
1940
1941 AutoWriteLock snapshotLock(pSnapshot);
1942
1943 size_t childrenCount = pSnapshot->getChildrenCount();
1944 if (childrenCount > 1)
1945 return setError(VBOX_E_INVALID_OBJECT_STATE,
1946 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"),
1947 pSnapshot->getName().c_str(),
1948 mUserData->mName.raw(),
1949 childrenCount);
1950
1951 /* If the snapshot being discarded is the current one, ensure current
1952 * settings are committed and saved.
1953 */
1954 if (pSnapshot == mData->mCurrentSnapshot)
1955 {
1956 if (isModified())
1957 {
1958 rc = saveSettings();
1959 CheckComRCReturnRC(rc);
1960 }
1961 }
1962
1963 ComPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
1964
1965 /* create a progress object. The number of operations is:
1966 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
1967 */
1968 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
1969
1970 ULONG ulOpCount = 1; // one for preparations
1971 ULONG ulTotalWeight = 1; // one for preparations
1972
1973 if (pSnapshot->stateFilePath().length())
1974 {
1975 ++ulOpCount;
1976 ++ulTotalWeight; // assume 1 MB for deleting the state file
1977 }
1978
1979 // count normal hard disks and add their sizes to the weight
1980 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
1981 it != pSnapMachine->mMediaData->mAttachments.end();
1982 ++it)
1983 {
1984 ComObjPtr<MediumAttachment> &pAttach = *it;
1985 AutoReadLock attachLock(pAttach);
1986 if (pAttach->type() == DeviceType_HardDisk)
1987 {
1988 Assert(pAttach->medium());
1989 ComObjPtr<Medium> pHD = pAttach->medium();
1990 AutoReadLock mlock(pHD);
1991 if (pHD->type() == MediumType_Normal)
1992 {
1993 ++ulOpCount;
1994 ulTotalWeight += pHD->size() / _1M;
1995 }
1996 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->name().c_str()));
1997 }
1998 }
1999
2000 ComObjPtr<Progress> pProgress;
2001 pProgress.createObject();
2002 pProgress->init(mParent, aInitiator,
2003 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->getName().c_str()),
2004 FALSE /* aCancelable */,
2005 ulOpCount,
2006 ulTotalWeight,
2007 Bstr(tr("Setting up")),
2008 1);
2009
2010 /* create and start the task on a separate thread */
2011 DeleteSnapshotTask *task = new DeleteSnapshotTask(this, pProgress, pSnapshot);
2012 int vrc = RTThreadCreate(NULL,
2013 taskHandler,
2014 (void*)task,
2015 0,
2016 RTTHREADTYPE_MAIN_WORKER,
2017 0,
2018 "DeleteSnapshot");
2019 if (RT_FAILURE(vrc))
2020 {
2021 delete task;
2022 return E_FAIL;
2023 }
2024
2025 /* set the proper machine state (note: after creating a Task instance) */
2026 setMachineState(MachineState_DeletingSnapshot);
2027
2028 /* return the progress to the caller */
2029 pProgress.queryInterfaceTo(aProgress);
2030
2031 /* return the new state to the caller */
2032 *aMachineState = mData->mMachineState;
2033
2034 LogFlowThisFuncLeave();
2035
2036 return S_OK;
2037}
2038
2039/**
2040 * Helper struct for SessionMachine::deleteSnapshotHandler().
2041 */
2042struct MediumDiscardRec
2043{
2044 MediumDiscardRec()
2045 : chain(NULL)
2046 {}
2047
2048 MediumDiscardRec(const ComObjPtr<Medium> &aHd,
2049 Medium::MergeChain *aChain = NULL)
2050 : hd(aHd),
2051 chain(aChain)
2052 {}
2053
2054 MediumDiscardRec(const ComObjPtr<Medium> &aHd,
2055 Medium::MergeChain *aChain,
2056 const ComObjPtr<Medium> &aReplaceHd,
2057 const ComObjPtr<MediumAttachment> &aReplaceHda,
2058 const Guid &aSnapshotId)
2059 : hd(aHd),
2060 chain(aChain),
2061 replaceHd(aReplaceHd),
2062 replaceHda(aReplaceHda),
2063 snapshotId(aSnapshotId)
2064 {}
2065
2066 ComObjPtr<Medium> hd;
2067 Medium::MergeChain *chain;
2068 /* these are for the replace hard disk case: */
2069 ComObjPtr<Medium> replaceHd;
2070 ComObjPtr<MediumAttachment> replaceHda;
2071 Guid snapshotId;
2072};
2073
2074typedef std::list <MediumDiscardRec> MediumDiscardRecList;
2075
2076/**
2077 * Worker method for the delete snapshot thread created by SessionMachine::DeleteSnapshot().
2078 * This method gets called indirectly through SessionMachine::taskHandler() which then
2079 * calls DeleteSnapshotTask::handler().
2080 *
2081 * The DeleteSnapshotTask contains the progress object returned to the console by
2082 * SessionMachine::DeleteSnapshot, through which progress and results are reported.
2083 *
2084 * @note Locks mParent + this + child objects for writing!
2085 *
2086 * @param aTask Task data.
2087 */
2088void SessionMachine::deleteSnapshotHandler(DeleteSnapshotTask &aTask)
2089{
2090 LogFlowThisFuncEnter();
2091
2092 AutoCaller autoCaller(this);
2093
2094 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
2095 if (!autoCaller.isOk())
2096 {
2097 /* we might have been uninitialized because the session was accidentally
2098 * closed by the client, so don't assert */
2099 aTask.pProgress->notifyComplete(E_FAIL,
2100 COM_IIDOF(IMachine),
2101 getComponentName(),
2102 tr("The session has been accidentally closed"));
2103 LogFlowThisFuncLeave();
2104 return;
2105 }
2106
2107 /* Locking order: */
2108 AutoMultiWriteLock3 alock(this->lockHandle(),
2109 this->snapshotsTreeLockHandle(),
2110 aTask.pSnapshot->lockHandle());
2111
2112 ComPtr<SnapshotMachine> pSnapMachine = aTask.pSnapshot->getSnapshotMachine();
2113 /* no need to lock the snapshot machine since it is const by definiton */
2114
2115 HRESULT rc = S_OK;
2116
2117 /* save the snapshot ID (for callbacks) */
2118 Guid snapshotId = aTask.pSnapshot->getId();
2119
2120 MediumDiscardRecList toDiscard;
2121
2122 bool settingsChanged = false;
2123
2124 try
2125 {
2126 /* first pass: */
2127 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2128
2129 // go thru the attachments of the snapshot machine
2130 // (the media in here point to the disk states _before_ the snapshot
2131 // was taken, i.e. the state we're restoring to; for each such
2132 // medium, we will need to merge it with its one and only child (the
2133 // diff image holding the changes written after the snapshot was taken)
2134 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2135 it != pSnapMachine->mMediaData->mAttachments.end();
2136 ++it)
2137 {
2138 ComObjPtr<MediumAttachment> &pAttach = *it;
2139 AutoReadLock attachLock(pAttach);
2140 if (pAttach->type() == DeviceType_HardDisk)
2141 {
2142 Assert(pAttach->medium());
2143 ComObjPtr<Medium> pHD = pAttach->medium();
2144 // do not lock, prepareDiscared() has a write lock which will hang otherwise
2145
2146#ifdef DEBUG
2147 pHD->dumpBackRefs();
2148#endif
2149
2150 Medium::MergeChain *chain = NULL;
2151
2152 // needs to be discarded (merged with the child if any), check prerequisites
2153 rc = pHD->prepareDiscard(chain);
2154 CheckComRCThrowRC(rc);
2155
2156 // for simplicity, we merge pHd onto its child (forward merge), not the
2157 // other way round, because that saves us from updating the attachments
2158 // for the machine that follows the snapshot (next snapshot or real machine),
2159 // unless it's a base image:
2160
2161 if ( pHD->parent().isNull()
2162 && chain != NULL
2163 )
2164 {
2165 // parent is null -> this disk is a base hard disk: we will
2166 // then do a backward merge, i.e. merge its only child onto
2167 // the base disk; prepareDiscard() does necessary checks.
2168 // So here we need then to update the attachment that refers
2169 // to the child and have it point to the parent instead
2170
2171 /* The below assert would be nice but I don't want to move
2172 * Medium::MergeChain to the header just for that
2173 * Assert (!chain->isForward()); */
2174
2175 // prepareDiscard() should have raised an error already
2176 // if there was more than one child
2177 Assert(pHD->children().size() == 1);
2178
2179 ComObjPtr<Medium> pReplaceHD = pHD->children().front();
2180
2181 const Guid *pReplaceMachineId = pReplaceHD->getFirstMachineBackrefId();
2182 NOREF(pReplaceMachineId);
2183 Assert(pReplaceMachineId);
2184 Assert(*pReplaceMachineId == mData->mUuid);
2185
2186 Guid snapshotId;
2187 const Guid *pSnapshotId = pReplaceHD->getFirstMachineBackrefSnapshotId();
2188 if (pSnapshotId)
2189 snapshotId = *pSnapshotId;
2190
2191 HRESULT rc2 = S_OK;
2192
2193 attachLock.unlock();
2194
2195 // First we must detach the child (otherwise mergeTo() called
2196 // by discard() will assert because it will be going to delete
2197 // the child), so adjust the backreferences:
2198 // 1) detach the first child hard disk
2199 rc2 = pReplaceHD->detachFrom(mData->mUuid, snapshotId);
2200 AssertComRC(rc2);
2201 // 2) attach to machine and snapshot
2202 rc2 = pHD->attachTo(mData->mUuid, snapshotId);
2203 AssertComRC(rc2);
2204
2205 /* replace the hard disk in the attachment object */
2206 if (snapshotId.isEmpty())
2207 {
2208 /* in current state */
2209 AssertBreak(pAttach = findAttachment(mMediaData->mAttachments, pReplaceHD));
2210 }
2211 else
2212 {
2213 /* in snapshot */
2214 ComObjPtr<Snapshot> snapshot;
2215 rc2 = findSnapshot(snapshotId, snapshot);
2216 AssertComRC(rc2);
2217
2218 /* don't lock the snapshot; cannot be modified outside */
2219 MediaData::AttachmentList &snapAtts = snapshot->getSnapshotMachine()->mMediaData->mAttachments;
2220 AssertBreak(pAttach = findAttachment(snapAtts, pReplaceHD));
2221 }
2222
2223 AutoWriteLock attLock(pAttach);
2224 pAttach->updateMedium(pHD, false /* aImplicit */);
2225
2226 toDiscard.push_back(MediumDiscardRec(pHD,
2227 chain,
2228 pReplaceHD,
2229 pAttach,
2230 snapshotId));
2231 continue;
2232 }
2233
2234 toDiscard.push_back(MediumDiscardRec(pHD, chain));
2235 }
2236 }
2237
2238 /* Now we checked that we can successfully merge all normal hard disks
2239 * (unless a runtime error like end-of-disc happens). Prior to
2240 * performing the actual merge, we want to discard the snapshot itself
2241 * and remove it from the XML file to make sure that a possible merge
2242 * ruintime error will not make this snapshot inconsistent because of
2243 * the partially merged or corrupted hard disks */
2244
2245 /* second pass: */
2246 LogFlowThisFunc(("2: Discarding snapshot...\n"));
2247
2248 {
2249 ComObjPtr<Snapshot> parentSnapshot = aTask.pSnapshot->parent();
2250 Utf8Str stateFilePath = aTask.pSnapshot->stateFilePath();
2251
2252 /* Note that discarding the snapshot will deassociate it from the
2253 * hard disks which will allow the merge+delete operation for them*/
2254 aTask.pSnapshot->beginDiscard();
2255 aTask.pSnapshot->uninit();
2256
2257 rc = saveAllSnapshots();
2258 CheckComRCThrowRC(rc);
2259
2260 /// @todo (dmik)
2261 // if we implement some warning mechanism later, we'll have
2262 // to return a warning if the state file path cannot be deleted
2263 if (!stateFilePath.isEmpty())
2264 {
2265 aTask.pProgress->SetNextOperation(Bstr(tr("Discarding the execution state")),
2266 1); // weight
2267
2268 RTFileDelete(stateFilePath.c_str());
2269 }
2270
2271 /// @todo NEWMEDIA to provide a good level of fauilt tolerance, we
2272 /// should restore the shapshot in the snapshot tree if
2273 /// saveSnapshotSettings fails. Actually, we may call
2274 /// #saveSnapshotSettings() with a special flag that will tell it to
2275 /// skip the given snapshot as if it would have been discarded and
2276 /// only actually discard it if the save operation succeeds.
2277 }
2278
2279 /* here we come when we've irrevesibly discarded the snapshot which
2280 * means that the VM settigns (our relevant changes to mData) need to be
2281 * saved too */
2282 /// @todo NEWMEDIA maybe save everything in one operation in place of
2283 /// saveSnapshotSettings() above
2284 settingsChanged = true;
2285
2286 /* third pass: */
2287 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
2288
2289 /* leave the locks before the potentially lengthy operation */
2290 alock.leave();
2291
2292 /// @todo NEWMEDIA turn the following errors into warnings because the
2293 /// snapshot itself has been already deleted (and interpret these
2294 /// warnings properly on the GUI side)
2295
2296 for (MediumDiscardRecList::iterator it = toDiscard.begin();
2297 it != toDiscard.end();)
2298 {
2299 rc = it->hd->discard(aTask.pProgress,
2300 it->hd->size() / _1M, // weight
2301 it->chain);
2302 CheckComRCBreakRC(rc);
2303
2304 /* prevent from calling cancelDiscard() */
2305 it = toDiscard.erase(it);
2306 }
2307
2308 LogFlowThisFunc(("Entering locks again...\n"));
2309 alock.enter();
2310 LogFlowThisFunc(("Entered locks OK\n"));
2311
2312 CheckComRCThrowRC(rc);
2313 }
2314 catch (HRESULT aRC) { rc = aRC; }
2315
2316 if (FAILED(rc))
2317 {
2318 HRESULT rc2 = S_OK;
2319
2320 /* un-prepare the remaining hard disks */
2321 for (MediumDiscardRecList::const_iterator it = toDiscard.begin();
2322 it != toDiscard.end(); ++it)
2323 {
2324 it->hd->cancelDiscard (it->chain);
2325
2326 if (!it->replaceHd.isNull())
2327 {
2328 /* undo hard disk replacement */
2329
2330 rc2 = it->replaceHd->attachTo (mData->mUuid, it->snapshotId);
2331 AssertComRC(rc2);
2332
2333 rc2 = it->hd->detachFrom (mData->mUuid, it->snapshotId);
2334 AssertComRC(rc2);
2335
2336 AutoWriteLock attLock (it->replaceHda);
2337 it->replaceHda->updateMedium(it->replaceHd, false /* aImplicit */);
2338 }
2339 }
2340 }
2341
2342 alock.unlock();
2343
2344 // whether we were successful or not, we need to set the machine
2345 // state and save the machine settings;
2346 {
2347 // preserve existing error info so that the result can
2348 // be properly reported to the progress object below
2349 ErrorInfoKeeper eik;
2350
2351 // restore the machine state that was saved when the
2352 // task was started
2353 setMachineState(aTask.machineStateBackup);
2354 updateMachineStateOnClient();
2355
2356 if (settingsChanged)
2357 {
2358 // saveSettings needs VirtualBox write lock in addition to our own
2359 // (parent -> child locking order!)
2360 AutoWriteLock vboxLock(mParent);
2361 alock.lock();
2362
2363 saveSettings(SaveS_InformCallbacksAnyway);
2364 }
2365 }
2366
2367 // report the result (this will try to fetch current error info on failure)
2368 aTask.pProgress->notifyComplete(rc);
2369
2370 if (SUCCEEDED(rc))
2371 mParent->onSnapshotDeleted(mData->mUuid, snapshotId);
2372
2373 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", rc));
2374 LogFlowThisFuncLeave();
2375}
2376
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