VirtualBox

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

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

Main: Bstr makeover (third attempt) -- make Bstr(NULL) and Bstr() behave the same; resulting cleanup; make some more internal methods use Utf8Str instead of Bstr; fix a lot of CheckComArgNotNull??() usage

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