VirtualBox

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

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

Main: debugging notes, coding style

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