VirtualBox

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

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

Main: remove templates for 'weak' com pointers which do nothing anyway

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

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