VirtualBox

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

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

Main: finish integration of Main lock validation with IPRT; only enabled with VBOX_WITH_STRICT_LOCKS=1 (do NOT enable unless you want Main to stop working now)

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