VirtualBox

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

Last change on this file since 25877 was 25860, checked in by vboxsync, 15 years ago

Main: cleanup: get rid of VirtualBoxBaseProto, move AutoCaller*/*Span* classes out of VirtualBoxBaseProto class scope and into separate header; move CombinedProgress into separate header (it's only used by Console any more)

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