VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/SnapshotImpl.cpp@ 95423

Last change on this file since 95423 was 95423, checked in by vboxsync, 3 years ago

Audio/Main: Bigger revamp of the audio interface(s) to later also support host audio device enumeration and selection for individual VMs. The audio settings now live in a dedicated (per-VM) IAudioSettings interface (audio adapter + audio host device stuff), to further tidy up the IMachine interface. Also added stubs for IAudioDevice + IHostAudioDevice, plus enmuerations, left for further implementation. Added a new IHostAudioDeviceChangedEvent that can also be used later by API clients. bugref:10050

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 161.0 KB
Line 
1/* $Id: SnapshotImpl.cpp 95423 2022-06-29 11:13:40Z vboxsync $ */
2/** @file
3 * COM class implementation for Snapshot and SnapshotMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2022 Oracle Corporation
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
18#define LOG_GROUP LOG_GROUP_MAIN_SNAPSHOT
19#include <set>
20#include <map>
21
22#include "SnapshotImpl.h"
23#include "LoggingNew.h"
24
25#include "MachineImpl.h"
26#include "MediumImpl.h"
27#include "MediumFormatImpl.h"
28#include "ProgressImpl.h"
29#include "Global.h"
30#include "StringifyEnums.h"
31
32/// @todo these three includes are required for about one or two lines, try
33// to remove them and put that code in shared code in MachineImplcpp
34#include "SharedFolderImpl.h"
35#include "USBControllerImpl.h"
36#include "USBDeviceFiltersImpl.h"
37#include "VirtualBoxImpl.h"
38
39#include "AutoCaller.h"
40#include "VBox/com/MultiResult.h"
41
42#include <iprt/path.h>
43#include <iprt/cpp/utils.h>
44
45#include <VBox/param.h>
46#include <iprt/errcore.h>
47
48#include <VBox/settings.h>
49
50////////////////////////////////////////////////////////////////////////////////
51//
52// Snapshot private data definition
53//
54////////////////////////////////////////////////////////////////////////////////
55
56typedef std::list< ComObjPtr<Snapshot> > SnapshotsList;
57
58struct Snapshot::Data
59{
60 Data()
61 : pVirtualBox(NULL)
62 {
63 RTTimeSpecSetMilli(&timeStamp, 0);
64 };
65
66 ~Data()
67 {}
68
69 const Guid uuid;
70 Utf8Str strName;
71 Utf8Str strDescription;
72 RTTIMESPEC timeStamp;
73 ComObjPtr<SnapshotMachine> pMachine;
74
75 /** weak VirtualBox parent */
76 VirtualBox * const pVirtualBox;
77
78 // pParent and llChildren are protected by the machine lock
79 ComObjPtr<Snapshot> pParent;
80 SnapshotsList llChildren;
81};
82
83////////////////////////////////////////////////////////////////////////////////
84//
85// Constructor / destructor
86//
87////////////////////////////////////////////////////////////////////////////////
88DEFINE_EMPTY_CTOR_DTOR(Snapshot)
89
90HRESULT Snapshot::FinalConstruct()
91{
92 LogFlowThisFunc(("\n"));
93 return BaseFinalConstruct();
94}
95
96void Snapshot::FinalRelease()
97{
98 LogFlowThisFunc(("\n"));
99 uninit();
100 BaseFinalRelease();
101}
102
103/**
104 * Initializes the instance
105 *
106 * @param aVirtualBox VirtualBox object
107 * @param aId id of the snapshot
108 * @param aName name of the snapshot
109 * @param aDescription name of the snapshot (NULL if no description)
110 * @param aTimeStamp timestamp of the snapshot, in ms since 1970-01-01 UTC
111 * @param aMachine machine associated with this snapshot
112 * @param aParent parent snapshot (NULL if no parent)
113 */
114HRESULT Snapshot::init(VirtualBox *aVirtualBox,
115 const Guid &aId,
116 const Utf8Str &aName,
117 const Utf8Str &aDescription,
118 const RTTIMESPEC &aTimeStamp,
119 SnapshotMachine *aMachine,
120 Snapshot *aParent)
121{
122 LogFlowThisFunc(("uuid=%s aParent->uuid=%s\n", aId.toString().c_str(), (aParent) ? aParent->m->uuid.toString().c_str() : ""));
123
124 ComAssertRet(!aId.isZero() && aId.isValid() && aMachine, E_INVALIDARG);
125
126 /* Enclose the state transition NotReady->InInit->Ready */
127 AutoInitSpan autoInitSpan(this);
128 AssertReturn(autoInitSpan.isOk(), E_FAIL);
129
130 m = new Data;
131
132 /* share parent weakly */
133 unconst(m->pVirtualBox) = aVirtualBox;
134
135 m->pParent = aParent;
136
137 unconst(m->uuid) = aId;
138 m->strName = aName;
139 m->strDescription = aDescription;
140 m->timeStamp = aTimeStamp;
141 m->pMachine = aMachine;
142
143 if (aParent)
144 aParent->m->llChildren.push_back(this);
145
146 /* Confirm a successful initialization when it's the case */
147 autoInitSpan.setSucceeded();
148
149 return S_OK;
150}
151
152/**
153 * Uninitializes the instance and sets the ready flag to FALSE.
154 * Called either from FinalRelease(), by the parent when it gets destroyed,
155 * or by a third party when it decides this object is no more valid.
156 *
157 * Since this manipulates the snapshots tree, the caller must hold the
158 * machine lock in write mode (which protects the snapshots tree)!
159 *
160 * @note All children of this snapshot get uninitialized, too, in a stack
161 * friendly manner.
162 */
163void Snapshot::uninit()
164{
165 LogFlowThisFunc(("\n"));
166
167 {
168 /* If "this" is already uninitialized or was never initialized, skip
169 * all activity since it makes no sense. Also would cause asserts with
170 * the automatic refcount updating with SnapshotList/ComPtr. Also,
171 * make sure that the possible fake error is undone. */
172 ErrorInfoKeeper eik;
173 AutoLimitedCaller autoCaller(this);
174 if (FAILED(autoCaller.rc()))
175 return;
176 }
177
178 SnapshotsList llSnapshotsTodo;
179 llSnapshotsTodo.push_back(this);
180 SnapshotsList llSnapshotsAll;
181
182 while (llSnapshotsTodo.size() > 0)
183 {
184 /* This also guarantees that the refcount doesn't actually drop to 0
185 * again while the uninit is already ongoing. */
186 ComObjPtr<Snapshot> pSnapshot = llSnapshotsTodo.front();
187 llSnapshotsTodo.pop_front();
188
189 /* Enclose the state transition Ready->InUninit->NotReady */
190 AutoUninitSpan autoUninitSpan(pSnapshot);
191 if (autoUninitSpan.uninitDone())
192 continue;
193
194 /* Remember snapshots (depth first), for associated SnapshotMachine
195 * uninitialization, which must be done in dept first order, otherwise
196 * the Medium object uninit is done in the wrong order. */
197 llSnapshotsAll.push_front(pSnapshot);
198
199 Assert(pSnapshot->m->pMachine->isWriteLockOnCurrentThread());
200
201 /* Remove initial snapshot from parent snapshot's list of children. */
202 if (pSnapshot == this)
203 pSnapshot->i_deparent();
204
205 /* Paranoia. Shouldn't be set any more at processing time. */
206 Assert(!pSnapshot->m || pSnapshot->m->pParent.isNull());
207
208 /* Process all children */
209 SnapshotsList::const_iterator itBegin = pSnapshot->m->llChildren.begin();
210 SnapshotsList::const_iterator itEnd = pSnapshot->m->llChildren.end();
211 for (SnapshotsList::const_iterator it = itBegin; it != itEnd; ++it)
212 {
213 Snapshot *pChild = *it;
214
215 if (!pChild || !pChild->m)
216 continue;
217
218 pChild->m->pParent.setNull();
219 llSnapshotsTodo.push_back(pChild);
220 }
221
222 /* Children information obsolete, will be processed anyway. */
223 pSnapshot->m->llChildren.clear();
224
225 autoUninitSpan.setSucceeded();
226 }
227
228 /* Now handle SnapshotMachine uninit and free memory. */
229 while (llSnapshotsAll.size() > 0)
230 {
231 ComObjPtr<Snapshot> pSnapshot = llSnapshotsAll.front();
232 llSnapshotsAll.pop_front();
233
234 if (pSnapshot->m->pMachine)
235 {
236 pSnapshot->m->pMachine->uninit();
237 pSnapshot->m->pMachine.setNull();
238 }
239
240 delete pSnapshot->m;
241 pSnapshot->m = NULL;
242 }
243}
244
245/**
246 * Delete the current snapshot by removing it from the tree of snapshots
247 * and reparenting its children.
248 *
249 * After this, the caller must call uninit() on the snapshot. We can't call
250 * that from here because if we do, the AutoUninitSpan waits forever for
251 * the number of callers to become 0 (it is 1 because of the AutoCaller in here).
252 *
253 * NOTE: this does NOT lock the snapshot, it is assumed that the machine state
254 * (and the snapshots tree) is protected by the caller having requested the machine
255 * lock in write mode AND the machine state must be DeletingSnapshot.
256 */
257void Snapshot::i_beginSnapshotDelete()
258{
259 AutoCaller autoCaller(this);
260 if (FAILED(autoCaller.rc()))
261 return;
262
263 // caller must have acquired the machine's write lock
264 Assert( m->pMachine->mData->mMachineState == MachineState_DeletingSnapshot
265 || m->pMachine->mData->mMachineState == MachineState_DeletingSnapshotOnline
266 || m->pMachine->mData->mMachineState == MachineState_DeletingSnapshotPaused);
267 Assert(m->pMachine->isWriteLockOnCurrentThread());
268
269 // the snapshot must have only one child when being deleted or no children at all
270 AssertReturnVoid(m->llChildren.size() <= 1);
271
272 ComObjPtr<Snapshot> parentSnapshot = m->pParent;
273
274 /// @todo (dmik):
275 // when we introduce clones later, deleting the snapshot will affect
276 // the current and first snapshots of clones, if they are direct children
277 // of this snapshot. So we will need to lock machines associated with
278 // child snapshots as well and update mCurrentSnapshot and/or
279 // mFirstSnapshot fields.
280
281 if (this == m->pMachine->mData->mCurrentSnapshot)
282 {
283 m->pMachine->mData->mCurrentSnapshot = parentSnapshot;
284
285 /* we've changed the base of the current state so mark it as
286 * modified as it no longer guaranteed to be its copy */
287 m->pMachine->mData->mCurrentStateModified = TRUE;
288 }
289
290 if (this == m->pMachine->mData->mFirstSnapshot)
291 {
292 if (m->llChildren.size() == 1)
293 {
294 ComObjPtr<Snapshot> childSnapshot = m->llChildren.front();
295 m->pMachine->mData->mFirstSnapshot = childSnapshot;
296 }
297 else
298 m->pMachine->mData->mFirstSnapshot.setNull();
299 }
300
301 // reparent our children
302 for (SnapshotsList::const_iterator it = m->llChildren.begin();
303 it != m->llChildren.end();
304 ++it)
305 {
306 ComObjPtr<Snapshot> child = *it;
307 // no need to lock, snapshots tree is protected by machine lock
308 child->m->pParent = m->pParent;
309 if (m->pParent)
310 m->pParent->m->llChildren.push_back(child);
311 }
312
313 // clear our own children list (since we reparented the children)
314 m->llChildren.clear();
315}
316
317/**
318 * Internal helper that removes "this" from the list of children of its
319 * parent. Used in places when reparenting is necessary.
320 *
321 * The caller must hold the machine lock in write mode (which protects the snapshots tree)!
322 */
323void Snapshot::i_deparent()
324{
325 Assert(m->pMachine->isWriteLockOnCurrentThread());
326
327 if (m->pParent.isNull())
328 return;
329
330 Assert(m->pParent->m);
331
332 SnapshotsList &llParent = m->pParent->m->llChildren;
333 for (SnapshotsList::iterator it = llParent.begin();
334 it != llParent.end();
335 ++it)
336 {
337 Snapshot *pParentsChild = *it;
338 if (this == pParentsChild)
339 {
340 llParent.erase(it);
341 break;
342 }
343 }
344
345 m->pParent.setNull();
346}
347
348////////////////////////////////////////////////////////////////////////////////
349//
350// ISnapshot public methods
351//
352////////////////////////////////////////////////////////////////////////////////
353
354HRESULT Snapshot::getId(com::Guid &aId)
355{
356 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
357
358 aId = m->uuid;
359
360 return S_OK;
361}
362
363HRESULT Snapshot::getName(com::Utf8Str &aName)
364{
365 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
366 aName = m->strName;
367 return S_OK;
368}
369
370/**
371 * @note Locks this object for writing, then calls Machine::onSnapshotChange()
372 * (see its lock requirements).
373 */
374HRESULT Snapshot::setName(const com::Utf8Str &aName)
375{
376 HRESULT rc = S_OK;
377
378 // prohibit setting a UUID only as the machine name, or else it can
379 // never be found by findMachine()
380 Guid test(aName);
381
382 if (!test.isZero() && test.isValid())
383 return setError(E_INVALIDARG, tr("A machine cannot have a UUID as its name"));
384
385 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
386
387 if (m->strName != aName)
388 {
389 m->strName = aName;
390 alock.release(); /* Important! (child->parent locks are forbidden) */
391 rc = m->pMachine->i_onSnapshotChange(this);
392 }
393
394 return rc;
395}
396
397HRESULT Snapshot::getDescription(com::Utf8Str &aDescription)
398{
399 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
400 aDescription = m->strDescription;
401 return S_OK;
402}
403
404HRESULT Snapshot::setDescription(const com::Utf8Str &aDescription)
405{
406 HRESULT rc = S_OK;
407
408 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
409 if (m->strDescription != aDescription)
410 {
411 m->strDescription = aDescription;
412 alock.release(); /* Important! (child->parent locks are forbidden) */
413 rc = m->pMachine->i_onSnapshotChange(this);
414 }
415
416 return rc;
417}
418
419HRESULT Snapshot::getTimeStamp(LONG64 *aTimeStamp)
420{
421 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
422
423 *aTimeStamp = RTTimeSpecGetMilli(&m->timeStamp);
424 return S_OK;
425}
426
427HRESULT Snapshot::getOnline(BOOL *aOnline)
428{
429 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
430
431 *aOnline = i_getStateFilePath().isNotEmpty();
432 return S_OK;
433}
434
435HRESULT Snapshot::getMachine(ComPtr<IMachine> &aMachine)
436{
437 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
438
439 m->pMachine.queryInterfaceTo(aMachine.asOutParam());
440
441 return S_OK;
442}
443
444
445HRESULT Snapshot::getParent(ComPtr<ISnapshot> &aParent)
446{
447 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
448
449 m->pParent.queryInterfaceTo(aParent.asOutParam());
450 return S_OK;
451}
452
453HRESULT Snapshot::getChildren(std::vector<ComPtr<ISnapshot> > &aChildren)
454{
455 // snapshots tree is protected by machine lock
456 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
457 aChildren.resize(0);
458 for (SnapshotsList::const_iterator it = m->llChildren.begin();
459 it != m->llChildren.end();
460 ++it)
461 aChildren.push_back(*it);
462 return S_OK;
463}
464
465HRESULT Snapshot::getChildrenCount(ULONG *count)
466{
467 *count = i_getChildrenCount();
468
469 return S_OK;
470}
471
472////////////////////////////////////////////////////////////////////////////////
473//
474// Snapshot public internal methods
475//
476////////////////////////////////////////////////////////////////////////////////
477
478/**
479 * Returns the parent snapshot or NULL if there's none. Must have caller + locking!
480 * @return
481 */
482const ComObjPtr<Snapshot>& Snapshot::i_getParent() const
483{
484 return m->pParent;
485}
486
487/**
488 * Returns the first child snapshot or NULL if there's none. Must have caller + locking!
489 * @return
490 */
491const ComObjPtr<Snapshot> Snapshot::i_getFirstChild() const
492{
493 if (!m->llChildren.size())
494 return NULL;
495 return m->llChildren.front();
496}
497
498/**
499 * @note
500 * Must be called from under the object's lock!
501 */
502const Utf8Str& Snapshot::i_getStateFilePath() const
503{
504 return m->pMachine->mSSData->strStateFilePath;
505}
506
507/**
508 * Returns the depth in the snapshot tree for this snapshot.
509 *
510 * @note takes the snapshot tree lock
511 */
512
513uint32_t Snapshot::i_getDepth()
514{
515 AutoCaller autoCaller(this);
516 AssertComRC(autoCaller.rc());
517
518 // snapshots tree is protected by machine lock
519 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
520
521 uint32_t cDepth = 0;
522 ComObjPtr<Snapshot> pSnap(this);
523 while (!pSnap.isNull())
524 {
525 pSnap = pSnap->m->pParent;
526 cDepth++;
527 }
528
529 return cDepth;
530}
531
532/**
533 * Returns the number of direct child snapshots, without grandchildren.
534 * @return
535 */
536ULONG Snapshot::i_getChildrenCount()
537{
538 AutoCaller autoCaller(this);
539 AssertComRC(autoCaller.rc());
540
541 // snapshots tree is protected by machine lock
542 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
543
544 return (ULONG)m->llChildren.size();
545}
546
547/**
548 * Returns the number of child snapshots including all grandchildren.
549 * @return
550 */
551ULONG Snapshot::i_getAllChildrenCount()
552{
553 AutoCaller autoCaller(this);
554 AssertComRC(autoCaller.rc());
555
556 // snapshots tree is protected by machine lock
557 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
558
559 std::list<const Snapshot *> llSnapshotsTodo;
560 llSnapshotsTodo.push_back(this);
561
562 ULONG cChildren = 0;
563
564 while (llSnapshotsTodo.size() > 0)
565 {
566 const Snapshot *pSnapshot = llSnapshotsTodo.front();
567 llSnapshotsTodo.pop_front();
568
569 /* Check if snapshot is uninitialized already, can happen if an API
570 * client asks at an inconvenient time. */
571 if (!pSnapshot->m)
572 continue;
573
574 cChildren += (ULONG)pSnapshot->m->llChildren.size();
575
576 /* count all children */
577 SnapshotsList::const_iterator itBegin = pSnapshot->m->llChildren.begin();
578 SnapshotsList::const_iterator itEnd = pSnapshot->m->llChildren.end();
579 for (SnapshotsList::const_iterator it = itBegin; it != itEnd; ++it)
580 llSnapshotsTodo.push_back(*it);
581 }
582
583 return cChildren;
584}
585
586/**
587 * Returns the SnapshotMachine that this snapshot belongs to.
588 * Caller must hold the snapshot's object lock!
589 * @return
590 */
591const ComObjPtr<SnapshotMachine>& Snapshot::i_getSnapshotMachine() const
592{
593 return m->pMachine;
594}
595
596/**
597 * Returns the UUID of this snapshot.
598 * Caller must hold the snapshot's object lock!
599 * @return
600 */
601Guid Snapshot::i_getId() const
602{
603 return m->uuid;
604}
605
606/**
607 * Returns the name of this snapshot.
608 * Caller must hold the snapshot's object lock!
609 * @return
610 */
611const Utf8Str& Snapshot::i_getName() const
612{
613 return m->strName;
614}
615
616/**
617 * Returns the time stamp of this snapshot.
618 * Caller must hold the snapshot's object lock!
619 * @return
620 */
621RTTIMESPEC Snapshot::i_getTimeStamp() const
622{
623 return m->timeStamp;
624}
625
626/**
627 * Searches for a snapshot with the given ID among children, grand-children,
628 * etc. of this snapshot. This snapshot itself is also included in the search.
629 *
630 * Caller must hold the machine lock (which protects the snapshots tree!)
631 */
632ComObjPtr<Snapshot> Snapshot::i_findChildOrSelf(IN_GUID aId)
633{
634 ComObjPtr<Snapshot> child;
635
636 AutoCaller autoCaller(this);
637 AssertComRC(autoCaller.rc());
638
639 // no need to lock, uuid is const
640 if (m->uuid == aId)
641 child = this;
642 else
643 {
644 for (SnapshotsList::const_iterator it = m->llChildren.begin();
645 it != m->llChildren.end();
646 ++it)
647 {
648 if ((child = (*it)->i_findChildOrSelf(aId)))
649 break;
650 }
651 }
652
653 return child;
654}
655
656/**
657 * Searches for a first snapshot with the given name among children,
658 * grand-children, etc. of this snapshot. This snapshot itself is also included
659 * in the search.
660 *
661 * Caller must hold the machine lock (which protects the snapshots tree!)
662 */
663ComObjPtr<Snapshot> Snapshot::i_findChildOrSelf(const Utf8Str &aName)
664{
665 ComObjPtr<Snapshot> child;
666 AssertReturn(!aName.isEmpty(), child);
667
668 AutoCaller autoCaller(this);
669 AssertComRC(autoCaller.rc());
670
671 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
672
673 if (m->strName == aName)
674 child = this;
675 else
676 {
677 alock.release();
678 for (SnapshotsList::const_iterator it = m->llChildren.begin();
679 it != m->llChildren.end();
680 ++it)
681 {
682 if ((child = (*it)->i_findChildOrSelf(aName)))
683 break;
684 }
685 }
686
687 return child;
688}
689
690/**
691 * Internal implementation for Snapshot::updateSavedStatePaths (below).
692 * @param strOldPath
693 * @param strNewPath
694 */
695void Snapshot::i_updateSavedStatePathsImpl(const Utf8Str &strOldPath,
696 const Utf8Str &strNewPath)
697{
698 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
699
700 const Utf8Str &path = m->pMachine->mSSData->strStateFilePath;
701 LogFlowThisFunc(("Snap[%s].statePath={%s}\n", m->strName.c_str(), path.c_str()));
702
703 /* state file may be NULL (for offline snapshots) */
704 if ( path.isNotEmpty()
705 && RTPathStartsWith(path.c_str(), strOldPath.c_str())
706 )
707 {
708 m->pMachine->mSSData->strStateFilePath = Utf8StrFmt("%s%s",
709 strNewPath.c_str(),
710 path.c_str() + strOldPath.length());
711 LogFlowThisFunc(("-> updated: {%s}\n", m->pMachine->mSSData->strStateFilePath.c_str()));
712 }
713
714 for (SnapshotsList::const_iterator it = m->llChildren.begin();
715 it != m->llChildren.end();
716 ++it)
717 {
718 Snapshot *pChild = *it;
719 pChild->i_updateSavedStatePathsImpl(strOldPath, strNewPath);
720 }
721}
722
723/**
724 * Checks if the specified path change affects the saved state file path of
725 * this snapshot or any of its (grand-)children and updates it accordingly.
726 *
727 * Intended to be called by Machine::openConfigLoader() only.
728 *
729 * @param strOldPath old path (full)
730 * @param strNewPath new path (full)
731 *
732 * @note Locks the machine (for the snapshots tree) + this object + children for writing.
733 */
734void Snapshot::i_updateSavedStatePaths(const Utf8Str &strOldPath,
735 const Utf8Str &strNewPath)
736{
737 LogFlowThisFunc(("aOldPath={%s} aNewPath={%s}\n", strOldPath.c_str(), strNewPath.c_str()));
738
739 AutoCaller autoCaller(this);
740 AssertComRC(autoCaller.rc());
741
742 // snapshots tree is protected by machine lock
743 AutoWriteLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
744
745 // call the implementation under the tree lock
746 i_updateSavedStatePathsImpl(strOldPath, strNewPath);
747}
748
749/**
750 * Returns true if this snapshot or one of its children uses the given file,
751 * whose path must be fully qualified, as its saved state. When invoked on a
752 * machine's first snapshot, this can be used to check if a saved state file
753 * is shared with any snapshots.
754 *
755 * Caller must hold the machine lock, which protects the snapshots tree.
756 *
757 * @param strPath
758 * @param pSnapshotToIgnore If != NULL, this snapshot is ignored during the checks.
759 * @return
760 */
761bool Snapshot::i_sharesSavedStateFile(const Utf8Str &strPath,
762 Snapshot *pSnapshotToIgnore)
763{
764 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
765 const Utf8Str &path = m->pMachine->mSSData->strStateFilePath;
766
767 if (path.isEmpty())
768 return false;
769
770 std::list<const Snapshot *> llSnapshotsTodo;
771 llSnapshotsTodo.push_back(this);
772
773 while (llSnapshotsTodo.size() > 0)
774 {
775 const Snapshot *pSnapshot = llSnapshotsTodo.front();
776 llSnapshotsTodo.pop_front();
777
778 if (!pSnapshotToIgnore || pSnapshotToIgnore != this)
779 if (path == strPath)
780 return true;
781
782 /* check all children */
783 SnapshotsList::const_iterator itBegin = pSnapshot->m->llChildren.begin();
784 SnapshotsList::const_iterator itEnd = pSnapshot->m->llChildren.end();
785 for (SnapshotsList::const_iterator it = itBegin; it != itEnd; ++it)
786 llSnapshotsTodo.push_back(*it);
787 }
788
789 return false;
790}
791
792
793/**
794 * Internal implementation for Snapshot::updateNVRAMPaths (below).
795 * @param strOldPath
796 * @param strNewPath
797 */
798void Snapshot::i_updateNVRAMPathsImpl(const Utf8Str &strOldPath,
799 const Utf8Str &strNewPath)
800{
801 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
802
803 const Utf8Str path = m->pMachine->mNvramStore->i_getNonVolatileStorageFile();
804 LogFlowThisFunc(("Snap[%s].nvramPath={%s}\n", m->strName.c_str(), path.c_str()));
805
806 /* NVRAM filename may be empty */
807 if ( path.isNotEmpty()
808 && RTPathStartsWith(path.c_str(), strOldPath.c_str())
809 )
810 {
811 m->pMachine->mNvramStore->i_updateNonVolatileStorageFile(Utf8StrFmt("%s%s",
812 strNewPath.c_str(),
813 path.c_str() + strOldPath.length()));
814 LogFlowThisFunc(("-> updated: {%s}\n", m->pMachine->mNvramStore->i_getNonVolatileStorageFile().c_str()));
815 }
816
817 for (SnapshotsList::const_iterator it = m->llChildren.begin();
818 it != m->llChildren.end();
819 ++it)
820 {
821 Snapshot *pChild = *it;
822 pChild->i_updateNVRAMPathsImpl(strOldPath, strNewPath);
823 }
824}
825
826/**
827 * Checks if the specified path change affects the NVRAM file path of
828 * this snapshot or any of its (grand-)children and updates it accordingly.
829 *
830 * Intended to be called by Machine::openConfigLoader() only.
831 *
832 * @param strOldPath old path (full)
833 * @param strNewPath new path (full)
834 *
835 * @note Locks the machine (for the snapshots tree) + this object + children for writing.
836 */
837void Snapshot::i_updateNVRAMPaths(const Utf8Str &strOldPath,
838 const Utf8Str &strNewPath)
839{
840 LogFlowThisFunc(("aOldPath={%s} aNewPath={%s}\n", strOldPath.c_str(), strNewPath.c_str()));
841
842 AutoCaller autoCaller(this);
843 AssertComRC(autoCaller.rc());
844
845 // snapshots tree is protected by machine lock
846 AutoWriteLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
847
848 // call the implementation under the tree lock
849 i_updateSavedStatePathsImpl(strOldPath, strNewPath);
850}
851
852/**
853 * Saves the settings attributes of one snapshot.
854 *
855 * @param data Target for saving snapshot settings.
856 * @return
857 */
858HRESULT Snapshot::i_saveSnapshotOne(settings::Snapshot &data) const
859{
860 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
861
862 data.uuid = m->uuid;
863 data.strName = m->strName;
864 data.timestamp = m->timeStamp;
865 data.strDescription = m->strDescription;
866
867 // state file (only if this snapshot is online)
868 if (i_getStateFilePath().isNotEmpty())
869 m->pMachine->i_copyPathRelativeToMachine(i_getStateFilePath(), data.strStateFile);
870 else
871 data.strStateFile.setNull();
872
873 HRESULT rc = m->pMachine->i_saveHardware(data.hardware, &data.debugging, &data.autostart);
874 if (FAILED(rc)) return rc;
875
876 return S_OK;
877}
878
879/**
880 * Saves the given snapshot and all its children.
881 * It is assumed that the given node is empty.
882 *
883 * @param data Target for saving snapshot settings.
884 */
885HRESULT Snapshot::i_saveSnapshot(settings::Snapshot &data) const
886{
887 // snapshots tree is protected by machine lock
888 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
889
890 std::list<const Snapshot *> llSnapshotsTodo;
891 llSnapshotsTodo.push_back(this);
892 std::list<settings::Snapshot *> llSettingsTodo;
893 llSettingsTodo.push_back(&data);
894
895 while (llSnapshotsTodo.size() > 0)
896 {
897 const Snapshot *pSnapshot = llSnapshotsTodo.front();
898 llSnapshotsTodo.pop_front();
899 settings::Snapshot *current = llSettingsTodo.front();
900 llSettingsTodo.pop_front();
901
902 HRESULT rc = pSnapshot->i_saveSnapshotOne(*current);
903 if (FAILED(rc))
904 return rc;
905
906 /* save all children */
907 SnapshotsList::const_iterator itBegin = pSnapshot->m->llChildren.begin();
908 SnapshotsList::const_iterator itEnd = pSnapshot->m->llChildren.end();
909 for (SnapshotsList::const_iterator it = itBegin; it != itEnd; ++it)
910 {
911 AutoCaller autoCaller(*it);
912 if (FAILED(autoCaller.rc()))
913 continue;
914
915 llSnapshotsTodo.push_back(*it);
916 current->llChildSnapshots.push_back(settings::Snapshot::Empty);
917 llSettingsTodo.push_back(&current->llChildSnapshots.back());
918 }
919 }
920
921 return S_OK;
922}
923
924/**
925 * Part of the cleanup engine of Machine::Unregister().
926 *
927 * This removes all medium attachments from the snapshot's machine and returns
928 * the snapshot's saved state file name, if any, and then calls uninit().
929 *
930 * This processes children depth first, so the given MediaList receives child
931 * media first before their parents. If the caller wants to close all media,
932 * they should go thru the list from the beginning to the end because media
933 * cannot be closed if they have children.
934 *
935 * This calls uninit() on itself, so the snapshots tree (beginning with a machine's pFirstSnapshot) becomes invalid after this.
936 * It does not alter the main machine's snapshot pointers (pFirstSnapshot, pCurrentSnapshot).
937 *
938 * Caller must hold the machine write lock (which protects the snapshots tree!)
939 *
940 * @param writeLock Machine write lock, which can get released temporarily here.
941 * @param cleanupMode Cleanup mode; see Machine::detachAllMedia().
942 * @param llMedia List of media returned to caller, depending on cleanupMode.
943 * @param llFilenames
944 * @return
945 */
946HRESULT Snapshot::i_uninitAll(AutoWriteLock &writeLock,
947 CleanupMode_T cleanupMode,
948 MediaList &llMedia,
949 std::list<Utf8Str> &llFilenames)
950{
951 Assert(m->pMachine->isWriteLockOnCurrentThread());
952
953 HRESULT rc = S_OK;
954
955 SnapshotsList llSnapshotsTodo;
956 llSnapshotsTodo.push_front(this);
957 SnapshotsList llSnapshotsAll;
958
959 /* Enumerate all snapshots depth first, avoids trouble with updates. */
960 while (llSnapshotsTodo.size() > 0)
961 {
962 ComObjPtr<Snapshot> pSnapshot = llSnapshotsTodo.front();
963 llSnapshotsTodo.pop_front();
964
965 llSnapshotsAll.push_front(pSnapshot);
966
967 /* Process all children */
968 SnapshotsList::const_iterator itBegin = pSnapshot->m->llChildren.begin();
969 SnapshotsList::const_iterator itEnd = pSnapshot->m->llChildren.end();
970 for (SnapshotsList::const_iterator it = itBegin; it != itEnd; ++it)
971 {
972 Snapshot *pChild = *it;
973 pChild->m->pParent.setNull();
974 llSnapshotsTodo.push_front(pChild);
975 }
976 }
977
978 /* Process all snapshots in enumeration order. */
979 while (llSnapshotsAll.size() > 0)
980 {
981 /* This also guarantees that the refcount doesn't actually drop to 0
982 * again while the uninit is already ongoing. */
983 ComObjPtr<Snapshot> pSnapshot = llSnapshotsAll.front();
984 llSnapshotsAll.pop_front();
985
986 rc = pSnapshot->m->pMachine->i_detachAllMedia(writeLock,
987 pSnapshot,
988 cleanupMode,
989 llMedia);
990 if (SUCCEEDED(rc))
991 {
992 Utf8Str strFile;
993
994 // report the saved state file if it's not on the list yet
995 strFile = pSnapshot->m->pMachine->mSSData->strStateFilePath;
996 if (strFile.isNotEmpty())
997 {
998 std::list<Utf8Str>::const_iterator itFound = find(llFilenames.begin(), llFilenames.end(), strFile);
999
1000 if (itFound != llFilenames.end())
1001 llFilenames.push_back(strFile);
1002 }
1003
1004 strFile = pSnapshot->m->pMachine->mNvramStore->i_getNonVolatileStorageFile();
1005 if (strFile.isNotEmpty() && RTFileExists(strFile.c_str()))
1006 llFilenames.push_back(strFile);
1007 }
1008
1009 pSnapshot->m->pParent.setNull();
1010 pSnapshot->m->llChildren.clear();
1011 pSnapshot->uninit();
1012 }
1013
1014 return S_OK;
1015}
1016
1017////////////////////////////////////////////////////////////////////////////////
1018//
1019// SnapshotMachine implementation
1020//
1021////////////////////////////////////////////////////////////////////////////////
1022
1023SnapshotMachine::SnapshotMachine()
1024 : mMachine(NULL)
1025{}
1026
1027SnapshotMachine::~SnapshotMachine()
1028{}
1029
1030HRESULT SnapshotMachine::FinalConstruct()
1031{
1032 LogFlowThisFunc(("\n"));
1033
1034 return BaseFinalConstruct();
1035}
1036
1037void SnapshotMachine::FinalRelease()
1038{
1039 LogFlowThisFunc(("\n"));
1040
1041 uninit();
1042
1043 BaseFinalRelease();
1044}
1045
1046/**
1047 * Initializes the SnapshotMachine object when taking a snapshot.
1048 *
1049 * @param aSessionMachine machine to take a snapshot from
1050 * @param aSnapshotId snapshot ID of this snapshot machine
1051 * @param aStateFilePath file where the execution state will be later saved
1052 * (or NULL for the offline snapshot)
1053 *
1054 * @note The aSessionMachine must be locked for writing.
1055 */
1056HRESULT SnapshotMachine::init(SessionMachine *aSessionMachine,
1057 IN_GUID aSnapshotId,
1058 const Utf8Str &aStateFilePath)
1059{
1060 LogFlowThisFuncEnter();
1061 LogFlowThisFunc(("mName={%s}\n", aSessionMachine->mUserData->s.strName.c_str()));
1062
1063 Guid l_guid(aSnapshotId);
1064 AssertReturn(aSessionMachine && (!l_guid.isZero() && l_guid.isValid()), E_INVALIDARG);
1065
1066 /* Enclose the state transition NotReady->InInit->Ready */
1067 AutoInitSpan autoInitSpan(this);
1068 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1069
1070 AssertReturn(aSessionMachine->isWriteLockOnCurrentThread(), E_FAIL);
1071
1072 mSnapshotId = aSnapshotId;
1073 ComObjPtr<Machine> pMachine = aSessionMachine->mPeer;
1074
1075 /* mPeer stays NULL */
1076 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
1077 unconst(mMachine) = pMachine;
1078 /* share the parent pointer */
1079 unconst(mParent) = pMachine->mParent;
1080
1081 /* take the pointer to Data to share */
1082 mData.share(pMachine->mData);
1083
1084 /* take the pointer to UserData to share (our UserData must always be the
1085 * same as Machine's data) */
1086 mUserData.share(pMachine->mUserData);
1087
1088 /* make a private copy of all other data */
1089 mHWData.attachCopy(aSessionMachine->mHWData);
1090
1091 /* SSData is always unique for SnapshotMachine */
1092 mSSData.allocate();
1093 mSSData->strStateFilePath = aStateFilePath;
1094
1095 HRESULT rc = S_OK;
1096
1097 /* Create copies of all attachments (mMediaData after attaching a copy
1098 * contains just references to original objects). Additionally associate
1099 * media with the snapshot (Machine::uninitDataAndChildObjects() will
1100 * deassociate at destruction). */
1101 mMediumAttachments.allocate();
1102 for (MediumAttachmentList::const_iterator
1103 it = aSessionMachine->mMediumAttachments->begin();
1104 it != aSessionMachine->mMediumAttachments->end();
1105 ++it)
1106 {
1107 ComObjPtr<MediumAttachment> pAtt;
1108 pAtt.createObject();
1109 rc = pAtt->initCopy(this, *it);
1110 if (FAILED(rc)) return rc;
1111 mMediumAttachments->push_back(pAtt);
1112
1113 Medium *pMedium = pAtt->i_getMedium();
1114 if (pMedium) // can be NULL for non-harddisk
1115 {
1116 rc = pMedium->i_addBackReference(mData->mUuid, mSnapshotId);
1117 AssertComRC(rc);
1118 }
1119 }
1120
1121 /* create copies of all shared folders (mHWData after attaching a copy
1122 * contains just references to original objects) */
1123 for (HWData::SharedFolderList::iterator
1124 it = mHWData->mSharedFolders.begin();
1125 it != mHWData->mSharedFolders.end();
1126 ++it)
1127 {
1128 ComObjPtr<SharedFolder> pFolder;
1129 pFolder.createObject();
1130 rc = pFolder->initCopy(this, *it);
1131 if (FAILED(rc)) return rc;
1132 *it = pFolder;
1133 }
1134
1135 /* create copies of all PCI device assignments (mHWData after attaching
1136 * a copy contains just references to original objects) */
1137 for (HWData::PCIDeviceAssignmentList::iterator
1138 it = mHWData->mPCIDeviceAssignments.begin();
1139 it != mHWData->mPCIDeviceAssignments.end();
1140 ++it)
1141 {
1142 ComObjPtr<PCIDeviceAttachment> pDev;
1143 pDev.createObject();
1144 rc = pDev->initCopy(this, *it);
1145 if (FAILED(rc)) return rc;
1146 *it = pDev;
1147 }
1148
1149 /* create copies of all storage controllers (mStorageControllerData
1150 * after attaching a copy contains just references to original objects) */
1151 mStorageControllers.allocate();
1152 for (StorageControllerList::const_iterator
1153 it = aSessionMachine->mStorageControllers->begin();
1154 it != aSessionMachine->mStorageControllers->end();
1155 ++it)
1156 {
1157 ComObjPtr<StorageController> ctrl;
1158 ctrl.createObject();
1159 rc = ctrl->initCopy(this, *it);
1160 if (FAILED(rc)) return rc;
1161 mStorageControllers->push_back(ctrl);
1162 }
1163
1164 /* create all other child objects that will be immutable private copies */
1165
1166 unconst(mBIOSSettings).createObject();
1167 rc = mBIOSSettings->initCopy(this, pMachine->mBIOSSettings);
1168 if (FAILED(rc)) return rc;
1169
1170 unconst(mTrustedPlatformModule).createObject();
1171 rc = mTrustedPlatformModule->initCopy(this, pMachine->mTrustedPlatformModule);
1172 if (FAILED(rc)) return rc;
1173
1174 unconst(mNvramStore).createObject();
1175 rc = mNvramStore->initCopy(this, pMachine->mNvramStore);
1176 if (FAILED(rc)) return rc;
1177
1178 unconst(mRecordingSettings).createObject();
1179 rc = mRecordingSettings->initCopy(this, pMachine->mRecordingSettings);
1180 if (FAILED(rc)) return rc;
1181
1182 unconst(mGraphicsAdapter).createObject();
1183 rc = mGraphicsAdapter->initCopy(this, pMachine->mGraphicsAdapter);
1184 if (FAILED(rc)) return rc;
1185
1186 unconst(mVRDEServer).createObject();
1187 rc = mVRDEServer->initCopy(this, pMachine->mVRDEServer);
1188 if (FAILED(rc)) return rc;
1189
1190 unconst(mAudioSettings).createObject();
1191 rc = mAudioSettings->initCopy(this, pMachine->mAudioSettings);
1192 if (FAILED(rc)) return rc;
1193
1194 /* create copies of all USB controllers (mUSBControllerData
1195 * after attaching a copy contains just references to original objects) */
1196 mUSBControllers.allocate();
1197 for (USBControllerList::const_iterator
1198 it = aSessionMachine->mUSBControllers->begin();
1199 it != aSessionMachine->mUSBControllers->end();
1200 ++it)
1201 {
1202 ComObjPtr<USBController> ctrl;
1203 ctrl.createObject();
1204 rc = ctrl->initCopy(this, *it);
1205 if (FAILED(rc)) return rc;
1206 mUSBControllers->push_back(ctrl);
1207 }
1208
1209 unconst(mUSBDeviceFilters).createObject();
1210 rc = mUSBDeviceFilters->initCopy(this, pMachine->mUSBDeviceFilters);
1211 if (FAILED(rc)) return rc;
1212
1213 mNetworkAdapters.resize(pMachine->mNetworkAdapters.size());
1214 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
1215 {
1216 unconst(mNetworkAdapters[slot]).createObject();
1217 rc = mNetworkAdapters[slot]->initCopy(this, pMachine->mNetworkAdapters[slot]);
1218 if (FAILED(rc)) return rc;
1219 }
1220
1221 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
1222 {
1223 unconst(mSerialPorts[slot]).createObject();
1224 rc = mSerialPorts[slot]->initCopy(this, pMachine->mSerialPorts[slot]);
1225 if (FAILED(rc)) return rc;
1226 }
1227
1228 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
1229 {
1230 unconst(mParallelPorts[slot]).createObject();
1231 rc = mParallelPorts[slot]->initCopy(this, pMachine->mParallelPorts[slot]);
1232 if (FAILED(rc)) return rc;
1233 }
1234
1235 unconst(mBandwidthControl).createObject();
1236 rc = mBandwidthControl->initCopy(this, pMachine->mBandwidthControl);
1237 if (FAILED(rc)) return rc;
1238
1239 /* Confirm a successful initialization when it's the case */
1240 autoInitSpan.setSucceeded();
1241
1242 LogFlowThisFuncLeave();
1243 return S_OK;
1244}
1245
1246/**
1247 * Initializes the SnapshotMachine object when loading from the settings file.
1248 *
1249 * @param aMachine machine the snapshot belongs to
1250 * @param hardware hardware settings
1251 * @param pDbg debuging settings
1252 * @param pAutostart autostart settings
1253 * @param aSnapshotId snapshot ID of this snapshot machine
1254 * @param aStateFilePath file where the execution state is saved
1255 * (or NULL for the offline snapshot)
1256 *
1257 * @note Doesn't lock anything.
1258 */
1259HRESULT SnapshotMachine::initFromSettings(Machine *aMachine,
1260 const settings::Hardware &hardware,
1261 const settings::Debugging *pDbg,
1262 const settings::Autostart *pAutostart,
1263 IN_GUID aSnapshotId,
1264 const Utf8Str &aStateFilePath)
1265{
1266 LogFlowThisFuncEnter();
1267 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
1268
1269 Guid l_guid(aSnapshotId);
1270 AssertReturn(aMachine && (!l_guid.isZero() && l_guid.isValid()), E_INVALIDARG);
1271
1272 /* Enclose the state transition NotReady->InInit->Ready */
1273 AutoInitSpan autoInitSpan(this);
1274 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1275
1276 /* Don't need to lock aMachine when VirtualBox is starting up */
1277
1278 mSnapshotId = aSnapshotId;
1279
1280 /* mPeer stays NULL */
1281 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
1282 unconst(mMachine) = aMachine;
1283 /* share the parent pointer */
1284 unconst(mParent) = aMachine->mParent;
1285
1286 /* take the pointer to Data to share */
1287 mData.share(aMachine->mData);
1288 /*
1289 * take the pointer to UserData to share
1290 * (our UserData must always be the same as Machine's data)
1291 */
1292 mUserData.share(aMachine->mUserData);
1293 /* allocate private copies of all other data (will be loaded from settings) */
1294 mHWData.allocate();
1295 mMediumAttachments.allocate();
1296 mStorageControllers.allocate();
1297 mUSBControllers.allocate();
1298
1299 /* SSData is always unique for SnapshotMachine */
1300 mSSData.allocate();
1301 mSSData->strStateFilePath = aStateFilePath;
1302
1303 /* create all other child objects that will be immutable private copies */
1304
1305 unconst(mBIOSSettings).createObject();
1306 mBIOSSettings->init(this);
1307
1308 unconst(mTrustedPlatformModule).createObject();
1309 mTrustedPlatformModule->init(this);
1310
1311 unconst(mNvramStore).createObject();
1312 mNvramStore->init(this);
1313
1314 unconst(mRecordingSettings).createObject();
1315 mRecordingSettings->init(this);
1316
1317 unconst(mGraphicsAdapter).createObject();
1318 mGraphicsAdapter->init(this);
1319
1320 unconst(mVRDEServer).createObject();
1321 mVRDEServer->init(this);
1322
1323 unconst(mAudioSettings).createObject();
1324 mAudioSettings->init(this);
1325
1326 unconst(mUSBDeviceFilters).createObject();
1327 mUSBDeviceFilters->init(this);
1328
1329 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
1330 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
1331 {
1332 unconst(mNetworkAdapters[slot]).createObject();
1333 mNetworkAdapters[slot]->init(this, slot);
1334 }
1335
1336 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
1337 {
1338 unconst(mSerialPorts[slot]).createObject();
1339 mSerialPorts[slot]->init(this, slot);
1340 }
1341
1342 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
1343 {
1344 unconst(mParallelPorts[slot]).createObject();
1345 mParallelPorts[slot]->init(this, slot);
1346 }
1347
1348 unconst(mBandwidthControl).createObject();
1349 mBandwidthControl->init(this);
1350
1351 /* load hardware and storage settings */
1352 HRESULT rc = i_loadHardware(NULL, &mSnapshotId, hardware, pDbg, pAutostart);
1353
1354 if (SUCCEEDED(rc))
1355 /* commit all changes made during the initialization */
1356 i_commit(); /// @todo r=dj why do we need a commit in init?!? this is very expensive
1357 /// @todo r=klaus for some reason the settings loading logic backs up
1358 // the settings, and therefore a commit is needed. Should probably be changed.
1359
1360 /* Confirm a successful initialization when it's the case */
1361 if (SUCCEEDED(rc))
1362 autoInitSpan.setSucceeded();
1363
1364 LogFlowThisFuncLeave();
1365 return rc;
1366}
1367
1368/**
1369 * Uninitializes this SnapshotMachine object.
1370 */
1371void SnapshotMachine::uninit()
1372{
1373 LogFlowThisFuncEnter();
1374
1375 /* Enclose the state transition Ready->InUninit->NotReady */
1376 AutoUninitSpan autoUninitSpan(this);
1377 if (autoUninitSpan.uninitDone())
1378 return;
1379
1380 uninitDataAndChildObjects();
1381
1382 /* free the essential data structure last */
1383 mData.free();
1384
1385 unconst(mMachine) = NULL;
1386 unconst(mParent) = NULL;
1387 unconst(mPeer) = NULL;
1388
1389 LogFlowThisFuncLeave();
1390}
1391
1392/**
1393 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
1394 * with the primary Machine instance (mMachine) if it exists.
1395 */
1396RWLockHandle *SnapshotMachine::lockHandle() const
1397{
1398 AssertReturn(mMachine != NULL, NULL);
1399 return mMachine->lockHandle();
1400}
1401
1402////////////////////////////////////////////////////////////////////////////////
1403//
1404// SnapshotMachine public internal methods
1405//
1406////////////////////////////////////////////////////////////////////////////////
1407
1408/**
1409 * Called by the snapshot object associated with this SnapshotMachine when
1410 * snapshot data such as name or description is changed.
1411 *
1412 * @warning Caller must hold no locks when calling this.
1413 */
1414HRESULT SnapshotMachine::i_onSnapshotChange(Snapshot *aSnapshot)
1415{
1416 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1417 AutoWriteLock slock(aSnapshot COMMA_LOCKVAL_SRC_POS);
1418 Guid uuidMachine(mData->mUuid),
1419 uuidSnapshot(aSnapshot->i_getId());
1420 bool fNeedsGlobalSaveSettings = false;
1421
1422 /* Flag the machine as dirty or change won't get saved. We disable the
1423 * modification of the current state flag, cause this snapshot data isn't
1424 * related to the current state. */
1425 mMachine->i_setModified(Machine::IsModified_Snapshots, false /* fAllowStateModification */);
1426 slock.release();
1427 HRESULT rc = mMachine->i_saveSettings(&fNeedsGlobalSaveSettings,
1428 alock,
1429 SaveS_Force); // we know we need saving, no need to check
1430 alock.release();
1431
1432 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
1433 {
1434 // save the global settings
1435 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
1436 rc = mParent->i_saveSettings();
1437 }
1438
1439 /* inform callbacks */
1440 mParent->i_onSnapshotChanged(uuidMachine, uuidSnapshot);
1441
1442 return rc;
1443}
1444
1445////////////////////////////////////////////////////////////////////////////////
1446//
1447// SessionMachine task records
1448//
1449////////////////////////////////////////////////////////////////////////////////
1450
1451/**
1452 * Still abstract base class for SessionMachine::TakeSnapshotTask,
1453 * SessionMachine::RestoreSnapshotTask and SessionMachine::DeleteSnapshotTask.
1454 */
1455class SessionMachine::SnapshotTask
1456 : public SessionMachine::Task
1457{
1458public:
1459 SnapshotTask(SessionMachine *m,
1460 Progress *p,
1461 const Utf8Str &t,
1462 Snapshot *s)
1463 : Task(m, p, t),
1464 m_pSnapshot(s)
1465 {}
1466
1467 ComObjPtr<Snapshot> m_pSnapshot;
1468};
1469
1470/** Take snapshot task */
1471class SessionMachine::TakeSnapshotTask
1472 : public SessionMachine::SnapshotTask
1473{
1474public:
1475 TakeSnapshotTask(SessionMachine *m,
1476 Progress *p,
1477 const Utf8Str &t,
1478 Snapshot *s,
1479 const Utf8Str &strName,
1480 const Utf8Str &strDescription,
1481 const Guid &uuidSnapshot,
1482 bool fPause,
1483 uint32_t uMemSize,
1484 bool fTakingSnapshotOnline)
1485 : SnapshotTask(m, p, t, s)
1486 , m_strName(strName)
1487 , m_strDescription(strDescription)
1488 , m_uuidSnapshot(uuidSnapshot)
1489 , m_fPause(fPause)
1490#if 0 /*unused*/
1491 , m_uMemSize(uMemSize)
1492#endif
1493 , m_fTakingSnapshotOnline(fTakingSnapshotOnline)
1494 {
1495 RT_NOREF(uMemSize);
1496 if (fTakingSnapshotOnline)
1497 m_pDirectControl = m->mData->mSession.mDirectControl;
1498 // If the VM is already paused then there's no point trying to pause
1499 // again during taking an (always online) snapshot.
1500 if (m_machineStateBackup == MachineState_Paused)
1501 m_fPause = false;
1502 }
1503
1504private:
1505 void handler()
1506 {
1507 try
1508 {
1509 ((SessionMachine *)(Machine *)m_pMachine)->i_takeSnapshotHandler(*this);
1510 }
1511 catch(...)
1512 {
1513 LogRel(("Some exception in the function i_takeSnapshotHandler()\n"));
1514 }
1515 }
1516
1517 Utf8Str m_strName;
1518 Utf8Str m_strDescription;
1519 Guid m_uuidSnapshot;
1520 Utf8Str m_strStateFilePath;
1521 ComPtr<IInternalSessionControl> m_pDirectControl;
1522 bool m_fPause;
1523#if 0 /*unused*/
1524 uint32_t m_uMemSize;
1525#endif
1526 bool m_fTakingSnapshotOnline;
1527
1528 friend HRESULT SessionMachine::i_finishTakingSnapshot(TakeSnapshotTask &task, AutoWriteLock &alock, bool aSuccess);
1529 friend void SessionMachine::i_takeSnapshotHandler(TakeSnapshotTask &task);
1530 friend void SessionMachine::i_takeSnapshotProgressCancelCallback(void *pvUser);
1531};
1532
1533/** Restore snapshot task */
1534class SessionMachine::RestoreSnapshotTask
1535 : public SessionMachine::SnapshotTask
1536{
1537public:
1538 RestoreSnapshotTask(SessionMachine *m,
1539 Progress *p,
1540 const Utf8Str &t,
1541 Snapshot *s)
1542 : SnapshotTask(m, p, t, s)
1543 {}
1544
1545private:
1546 void handler()
1547 {
1548 try
1549 {
1550 ((SessionMachine *)(Machine *)m_pMachine)->i_restoreSnapshotHandler(*this);
1551 }
1552 catch(...)
1553 {
1554 LogRel(("Some exception in the function i_restoreSnapshotHandler()\n"));
1555 }
1556 }
1557};
1558
1559/** Delete snapshot task */
1560class SessionMachine::DeleteSnapshotTask
1561 : public SessionMachine::SnapshotTask
1562{
1563public:
1564 DeleteSnapshotTask(SessionMachine *m,
1565 Progress *p,
1566 const Utf8Str &t,
1567 bool fDeleteOnline,
1568 Snapshot *s)
1569 : SnapshotTask(m, p, t, s),
1570 m_fDeleteOnline(fDeleteOnline)
1571 {}
1572
1573private:
1574 void handler()
1575 {
1576 try
1577 {
1578 ((SessionMachine *)(Machine *)m_pMachine)->i_deleteSnapshotHandler(*this);
1579 }
1580 catch(...)
1581 {
1582 LogRel(("Some exception in the function i_deleteSnapshotHandler()\n"));
1583 }
1584 }
1585
1586 bool m_fDeleteOnline;
1587 friend void SessionMachine::i_deleteSnapshotHandler(DeleteSnapshotTask &task);
1588};
1589
1590
1591////////////////////////////////////////////////////////////////////////////////
1592//
1593// TakeSnapshot methods (Machine and related tasks)
1594//
1595////////////////////////////////////////////////////////////////////////////////
1596
1597HRESULT Machine::takeSnapshot(const com::Utf8Str &aName,
1598 const com::Utf8Str &aDescription,
1599 BOOL fPause,
1600 com::Guid &aId,
1601 ComPtr<IProgress> &aProgress)
1602{
1603 NOREF(aName);
1604 NOREF(aDescription);
1605 NOREF(fPause);
1606 NOREF(aId);
1607 NOREF(aProgress);
1608 ReturnComNotImplemented();
1609}
1610
1611HRESULT SessionMachine::takeSnapshot(const com::Utf8Str &aName,
1612 const com::Utf8Str &aDescription,
1613 BOOL fPause,
1614 com::Guid &aId,
1615 ComPtr<IProgress> &aProgress)
1616{
1617 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1618 LogFlowThisFunc(("aName='%s' mMachineState=%d\n", aName.c_str(), mData->mMachineState));
1619
1620 if (Global::IsTransient(mData->mMachineState))
1621 return setError(VBOX_E_INVALID_VM_STATE,
1622 tr("Cannot take a snapshot of the machine while it is changing the state (machine state: %s)"),
1623 Global::stringifyMachineState(mData->mMachineState));
1624
1625 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
1626 if (FAILED(rc))
1627 return rc;
1628
1629 // prepare the progress object:
1630 // a) count the no. of hard disk attachments to get a matching no. of progress sub-operations
1631 ULONG cOperations = 2; // always at least setting up + finishing up
1632 ULONG ulTotalOperationsWeight = 2; // one each for setting up + finishing up
1633
1634 for (MediumAttachmentList::iterator
1635 it = mMediumAttachments->begin();
1636 it != mMediumAttachments->end();
1637 ++it)
1638 {
1639 const ComObjPtr<MediumAttachment> pAtt(*it);
1640 AutoReadLock attlock(pAtt COMMA_LOCKVAL_SRC_POS);
1641 AutoCaller attCaller(pAtt);
1642 if (pAtt->i_getType() == DeviceType_HardDisk)
1643 {
1644 ++cOperations;
1645
1646 // assume that creating a diff image takes as long as saving a 1MB state
1647 ulTotalOperationsWeight += 1;
1648 }
1649 }
1650
1651 // b) one extra sub-operations for online snapshots OR offline snapshots that have a saved state (needs to be copied)
1652 const bool fTakingSnapshotOnline = Global::IsOnline(mData->mMachineState);
1653 LogFlowThisFunc(("fTakingSnapshotOnline = %d\n", fTakingSnapshotOnline));
1654 if (fTakingSnapshotOnline)
1655 {
1656 ++cOperations;
1657 ulTotalOperationsWeight += mHWData->mMemorySize;
1658 }
1659
1660 // finally, create the progress object
1661 ComObjPtr<Progress> pProgress;
1662 pProgress.createObject();
1663 rc = pProgress->init(mParent,
1664 static_cast<IMachine *>(this),
1665 Bstr(tr("Taking a snapshot of the virtual machine")).raw(),
1666 fTakingSnapshotOnline /* aCancelable */,
1667 cOperations,
1668 ulTotalOperationsWeight,
1669 Bstr(tr("Setting up snapshot operation")).raw(), // first sub-op description
1670 1); // ulFirstOperationWeight
1671 if (FAILED(rc))
1672 return rc;
1673
1674 /* create an ID for the snapshot */
1675 Guid snapshotId;
1676 snapshotId.create();
1677
1678 /* create and start the task on a separate thread (note that it will not
1679 * start working until we release alock) */
1680 TakeSnapshotTask *pTask = new TakeSnapshotTask(this,
1681 pProgress,
1682 "TakeSnap",
1683 NULL /* pSnapshot */,
1684 aName,
1685 aDescription,
1686 snapshotId,
1687 !!fPause,
1688 mHWData->mMemorySize,
1689 fTakingSnapshotOnline);
1690 MachineState_T const machineStateBackup = pTask->m_machineStateBackup;
1691 rc = pTask->createThread();
1692 pTask = NULL;
1693 if (FAILED(rc))
1694 return rc;
1695
1696 /* set the proper machine state (note: after creating a Task instance) */
1697 if (fTakingSnapshotOnline)
1698 {
1699 if (machineStateBackup != MachineState_Paused && !fPause)
1700 i_setMachineState(MachineState_LiveSnapshotting);
1701 else
1702 i_setMachineState(MachineState_OnlineSnapshotting);
1703 i_updateMachineStateOnClient();
1704 }
1705 else
1706 i_setMachineState(MachineState_Snapshotting);
1707
1708 aId = snapshotId;
1709 pProgress.queryInterfaceTo(aProgress.asOutParam());
1710
1711 return rc;
1712}
1713
1714/**
1715 * Task thread implementation for SessionMachine::TakeSnapshot(), called from
1716 * SessionMachine::taskHandler().
1717 *
1718 * @note Locks this object for writing.
1719 *
1720 * @param task
1721 * @return
1722 */
1723void SessionMachine::i_takeSnapshotHandler(TakeSnapshotTask &task)
1724{
1725 LogFlowThisFuncEnter();
1726
1727 // Taking a snapshot consists of the following:
1728 // 1) creating a Snapshot object with the current state of the machine
1729 // (hardware + storage)
1730 // 2) creating a diff image for each virtual hard disk, into which write
1731 // operations go after the snapshot has been created
1732 // 3) if the machine is online: saving the state of the virtual machine
1733 // (in the VM process)
1734 // 4) reattach the hard disks
1735 // 5) update the various snapshot/machine objects, save settings
1736
1737 HRESULT rc = S_OK;
1738 AutoCaller autoCaller(this);
1739 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
1740 if (FAILED(autoCaller.rc()))
1741 {
1742 /* we might have been uninitialized because the session was accidentally
1743 * closed by the client, so don't assert */
1744 rc = setError(E_FAIL,
1745 tr("The session has been accidentally closed"));
1746 task.m_pProgress->i_notifyComplete(rc);
1747 LogFlowThisFuncLeave();
1748 return;
1749 }
1750
1751 LogRel(("Taking snapshot %s\n", task.m_strName.c_str()));
1752
1753 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1754
1755 bool fBeganTakingSnapshot = false;
1756 BOOL fSuspendedBySave = FALSE;
1757
1758 std::set<ComObjPtr<Medium> > pMediumsForNotify;
1759 std::map<Guid, DeviceType_T> uIdsForNotify;
1760
1761 try
1762 {
1763 /// @todo at this point we have to be in the right state!!!!
1764 AssertStmt( mData->mMachineState == MachineState_Snapshotting
1765 || mData->mMachineState == MachineState_OnlineSnapshotting
1766 || mData->mMachineState == MachineState_LiveSnapshotting, throw E_FAIL);
1767 AssertStmt(task.m_machineStateBackup != mData->mMachineState, throw E_FAIL);
1768 AssertStmt(task.m_pSnapshot.isNull(), throw E_FAIL);
1769
1770 if ( mData->mCurrentSnapshot
1771 && mData->mCurrentSnapshot->i_getDepth() >= SETTINGS_SNAPSHOT_DEPTH_MAX)
1772 {
1773 throw setError(VBOX_E_INVALID_OBJECT_STATE,
1774 tr("Cannot take another snapshot for machine '%s', because it exceeds the maximum snapshot depth limit. Please delete some earlier snapshot which you no longer need"),
1775 mUserData->s.strName.c_str());
1776 }
1777
1778 /* save settings to ensure current changes are committed and
1779 * hard disks are fixed up */
1780 rc = i_saveSettings(NULL, alock); /******************1 */
1781 // no need to check for whether VirtualBox.xml needs changing since
1782 // we can't have a machine XML rename pending at this point
1783 if (FAILED(rc))
1784 throw rc;
1785
1786 /* task.m_strStateFilePath is "" when the machine is offline or saved */
1787 if (task.m_fTakingSnapshotOnline)
1788 {
1789 Bstr value;
1790 rc = GetExtraData(Bstr("VBoxInternal2/ForceTakeSnapshotWithoutState").raw(),
1791 value.asOutParam());
1792 if (FAILED(rc) || value != "1")
1793 // creating a new online snapshot: we need a fresh saved state file
1794 i_composeSavedStateFilename(task.m_strStateFilePath);
1795 }
1796 else if (task.m_machineStateBackup == MachineState_Saved || task.m_machineStateBackup == MachineState_AbortedSaved)
1797 // taking an offline snapshot from machine in "saved" state: use existing state file
1798 task.m_strStateFilePath = mSSData->strStateFilePath;
1799
1800 if (task.m_strStateFilePath.isNotEmpty())
1801 {
1802 // ensure the directory for the saved state file exists
1803 rc = VirtualBox::i_ensureFilePathExists(task.m_strStateFilePath, true /* fCreate */);
1804 if (FAILED(rc))
1805 throw rc;
1806 }
1807
1808 /* STEP 1: create the snapshot object */
1809
1810 /* create a snapshot machine object */
1811 ComObjPtr<SnapshotMachine> pSnapshotMachine;
1812 pSnapshotMachine.createObject();
1813 rc = pSnapshotMachine->init(this, task.m_uuidSnapshot.ref(), task.m_strStateFilePath);
1814 AssertComRCThrowRC(rc);
1815
1816 /* create a snapshot object */
1817 RTTIMESPEC time;
1818 RTTimeNow(&time);
1819 task.m_pSnapshot.createObject();
1820 rc = task.m_pSnapshot->init(mParent,
1821 task.m_uuidSnapshot,
1822 task.m_strName,
1823 task.m_strDescription,
1824 time,
1825 pSnapshotMachine,
1826 mData->mCurrentSnapshot);
1827 AssertComRCThrowRC(rc);
1828
1829 /* STEP 2: create the diff images */
1830 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
1831 task.m_fTakingSnapshotOnline));
1832
1833 // Backup the media data so we can recover if something goes wrong.
1834 // The matching commit() is in fixupMedia() during SessionMachine::i_finishTakingSnapshot()
1835 i_setModified(IsModified_Storage);
1836 mMediumAttachments.backup();
1837
1838 alock.release();
1839 /* create new differencing hard disks and attach them to this machine */
1840 rc = i_createImplicitDiffs(task.m_pProgress,
1841 1, // operation weight; must be the same as in Machine::TakeSnapshot()
1842 task.m_fTakingSnapshotOnline);
1843 if (FAILED(rc))
1844 throw rc;
1845 alock.acquire();
1846
1847 // MUST NOT save the settings or the media registry here, because
1848 // this causes trouble with rolling back settings if the user cancels
1849 // taking the snapshot after the diff images have been created.
1850
1851 fBeganTakingSnapshot = true;
1852
1853 // STEP 3: save the VM state (if online)
1854 if (task.m_fTakingSnapshotOnline)
1855 {
1856 task.m_pProgress->SetNextOperation(Bstr(tr("Saving the machine state")).raw(),
1857 mHWData->mMemorySize); // operation weight, same as computed
1858 // when setting up progress object
1859
1860 if (task.m_strStateFilePath.isNotEmpty())
1861 {
1862 alock.release();
1863 task.m_pProgress->i_setCancelCallback(i_takeSnapshotProgressCancelCallback, &task);
1864 rc = task.m_pDirectControl->SaveStateWithReason(Reason_Snapshot,
1865 task.m_pProgress,
1866 task.m_pSnapshot,
1867 Bstr(task.m_strStateFilePath).raw(),
1868 task.m_fPause,
1869 &fSuspendedBySave);
1870 task.m_pProgress->i_setCancelCallback(NULL, NULL);
1871 alock.acquire();
1872 if (FAILED(rc))
1873 throw rc;
1874 }
1875 else
1876 LogRel(("Machine: skipped saving state as part of online snapshot\n"));
1877
1878 if (FAILED(task.m_pProgress->NotifyPointOfNoReturn()))
1879 throw setError(E_FAIL, tr("Canceled"));
1880
1881 // STEP 4: reattach hard disks
1882 LogFlowThisFunc(("Reattaching new differencing hard disks...\n"));
1883
1884 task.m_pProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")).raw(),
1885 1); // operation weight, same as computed when setting up progress object
1886
1887 com::SafeIfaceArray<IMediumAttachment> atts;
1888 rc = COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
1889 if (FAILED(rc))
1890 throw rc;
1891
1892 alock.release();
1893 rc = task.m_pDirectControl->ReconfigureMediumAttachments(ComSafeArrayAsInParam(atts));
1894 alock.acquire();
1895 if (FAILED(rc))
1896 throw rc;
1897 }
1898
1899 // Handle NVRAM file snapshotting
1900 Utf8Str strNVRAM = mNvramStore->i_getNonVolatileStorageFile();
1901 Utf8Str strNVRAMSnap = pSnapshotMachine->i_getSnapshotNVRAMFilename();
1902 if (strNVRAM.isNotEmpty() && strNVRAMSnap.isNotEmpty() && RTFileExists(strNVRAM.c_str()))
1903 {
1904 Utf8Str strNVRAMSnapAbs;
1905 i_calculateFullPath(strNVRAMSnap, strNVRAMSnapAbs);
1906 rc = VirtualBox::i_ensureFilePathExists(strNVRAMSnapAbs, true /* fCreate */);
1907 if (FAILED(rc))
1908 throw rc;
1909 int vrc = RTFileCopy(strNVRAM.c_str(), strNVRAMSnapAbs.c_str());
1910 if (RT_FAILURE(vrc))
1911 throw setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
1912 tr("Could not copy NVRAM file '%s' to '%s' (%Rrc)"),
1913 strNVRAM.c_str(), strNVRAMSnapAbs.c_str(), vrc);
1914 pSnapshotMachine->mNvramStore->i_updateNonVolatileStorageFile(strNVRAMSnap);
1915 }
1916
1917 // store parent of newly created diffs before commit for notify
1918 {
1919 MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
1920 for (MediumAttachmentList::const_iterator
1921 it = mMediumAttachments->begin();
1922 it != mMediumAttachments->end();
1923 ++it)
1924 {
1925 MediumAttachment *pAttach = *it;
1926 Medium *pMedium = pAttach->i_getMedium();
1927 if (!pMedium)
1928 continue;
1929
1930 bool fFound = false;
1931 /* was this medium attached before? */
1932 for (MediumAttachmentList::iterator
1933 oldIt = oldAtts.begin();
1934 oldIt != oldAtts.end();
1935 ++oldIt)
1936 {
1937 MediumAttachment *pOldAttach = *oldIt;
1938 if (pOldAttach->i_getMedium() == pMedium)
1939 {
1940 fFound = true;
1941 break;
1942 }
1943 }
1944 if (!fFound)
1945 {
1946 pMediumsForNotify.insert(pMedium->i_getParent());
1947 uIdsForNotify[pMedium->i_getId()] = pMedium->i_getDeviceType();
1948 }
1949 }
1950 }
1951
1952 /*
1953 * Finalize the requested snapshot object. This will reset the
1954 * machine state to the state it had at the beginning.
1955 */
1956 rc = i_finishTakingSnapshot(task, alock, true /*aSuccess*/); /*******************2+3 */
1957 // do not throw rc here because we can't call i_finishTakingSnapshot() twice
1958 LogFlowThisFunc(("i_finishTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, ::stringifyMachineState(mData->mMachineState)));
1959 }
1960 catch (HRESULT rcThrown)
1961 {
1962 rc = rcThrown;
1963 LogThisFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, ::stringifyMachineState(mData->mMachineState)));
1964
1965 /// @todo r=klaus check that the implicit diffs created above are cleaned up im the relevant error cases
1966
1967 /* preserve existing error info */
1968 ErrorInfoKeeper eik;
1969
1970 if (fBeganTakingSnapshot)
1971 i_finishTakingSnapshot(task, alock, false /*aSuccess*/);
1972
1973 // have to postpone this to the end as i_finishTakingSnapshot() needs
1974 // it for various cleanup steps
1975 if (task.m_pSnapshot)
1976 {
1977 task.m_pSnapshot->uninit();
1978 task.m_pSnapshot.setNull();
1979 }
1980 }
1981 Assert(alock.isWriteLockOnCurrentThread());
1982
1983 {
1984 // Keep all error information over the cleanup steps
1985 ErrorInfoKeeper eik;
1986
1987 /*
1988 * Fix up the machine state.
1989 *
1990 * For offline snapshots we just update the local copy, for the other
1991 * variants do the entire work. This ensures that the state is in sync
1992 * with the VM process (in particular the VM execution state).
1993 */
1994 bool fNeedClientMachineStateUpdate = false;
1995 if ( mData->mMachineState == MachineState_LiveSnapshotting
1996 || mData->mMachineState == MachineState_OnlineSnapshotting
1997 || mData->mMachineState == MachineState_Snapshotting)
1998 {
1999 if (!task.m_fTakingSnapshotOnline)
2000 i_setMachineState(task.m_machineStateBackup); /**************** 4 Machine::i_saveStateSettings*/
2001 else
2002 {
2003 MachineState_T enmMachineState = MachineState_Null;
2004 HRESULT rc2 = task.m_pDirectControl->COMGETTER(NominalState)(&enmMachineState);
2005 if (FAILED(rc2) || enmMachineState == MachineState_Null)
2006 {
2007 AssertMsgFailed(("state=%s\n", ::stringifyMachineState(enmMachineState)));
2008 // pure nonsense, try to continue somehow
2009 enmMachineState = MachineState_Aborted;
2010 }
2011 if (enmMachineState == MachineState_Paused)
2012 {
2013 if (fSuspendedBySave)
2014 {
2015 alock.release();
2016 rc2 = task.m_pDirectControl->ResumeWithReason(Reason_Snapshot);
2017 alock.acquire();
2018 if (SUCCEEDED(rc2))
2019 enmMachineState = task.m_machineStateBackup;
2020 }
2021 else
2022 enmMachineState = task.m_machineStateBackup;
2023 }
2024 if (enmMachineState != mData->mMachineState)
2025 {
2026 fNeedClientMachineStateUpdate = true;
2027 i_setMachineState(enmMachineState);
2028 }
2029 }
2030 }
2031
2032 /* check the remote state to see that we got it right. */
2033 MachineState_T enmMachineState = MachineState_Null;
2034 if (!task.m_pDirectControl.isNull())
2035 {
2036 ComPtr<IConsole> pConsole;
2037 task.m_pDirectControl->COMGETTER(RemoteConsole)(pConsole.asOutParam());
2038 if (!pConsole.isNull())
2039 pConsole->COMGETTER(State)(&enmMachineState);
2040 }
2041 LogFlowThisFunc(("local mMachineState=%s remote mMachineState=%s\n",
2042 ::stringifyMachineState(mData->mMachineState), ::stringifyMachineState(enmMachineState)));
2043
2044 if (fNeedClientMachineStateUpdate)
2045 i_updateMachineStateOnClient();
2046 }
2047
2048 task.m_pProgress->i_notifyComplete(rc);
2049
2050 if (SUCCEEDED(rc))
2051 mParent->i_onSnapshotTaken(mData->mUuid, task.m_uuidSnapshot);
2052
2053 if (SUCCEEDED(rc))
2054 {
2055 for (std::map<Guid, DeviceType_T>::const_iterator it = uIdsForNotify.begin();
2056 it != uIdsForNotify.end();
2057 ++it)
2058 {
2059 mParent->i_onMediumRegistered(it->first, it->second, TRUE);
2060 }
2061
2062 for (std::set<ComObjPtr<Medium> >::const_iterator it = pMediumsForNotify.begin();
2063 it != pMediumsForNotify.end();
2064 ++it)
2065 {
2066 if (it->isNotNull())
2067 mParent->i_onMediumConfigChanged(*it);
2068 }
2069 }
2070 LogRel(("Finished taking snapshot %s\n", task.m_strName.c_str()));
2071 LogFlowThisFuncLeave();
2072}
2073
2074
2075/**
2076 * Progress cancelation callback employed by SessionMachine::i_takeSnapshotHandler.
2077 */
2078/*static*/
2079void SessionMachine::i_takeSnapshotProgressCancelCallback(void *pvUser)
2080{
2081 TakeSnapshotTask *pTask = (TakeSnapshotTask *)pvUser;
2082 AssertPtrReturnVoid(pTask);
2083 AssertReturnVoid(!pTask->m_pDirectControl.isNull());
2084 pTask->m_pDirectControl->CancelSaveStateWithReason();
2085}
2086
2087
2088/**
2089 * Called by the Console when it's done saving the VM state into the snapshot
2090 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
2091 *
2092 * This also gets called if the console part of snapshotting failed after the
2093 * BeginTakingSnapshot() call, to clean up the server side.
2094 *
2095 * @note Locks VirtualBox and this object for writing.
2096 *
2097 * @param task
2098 * @param alock
2099 * @param aSuccess Whether Console was successful with the client-side
2100 * snapshot things.
2101 * @return
2102 */
2103HRESULT SessionMachine::i_finishTakingSnapshot(TakeSnapshotTask &task, AutoWriteLock &alock, bool aSuccess)
2104{
2105 LogFlowThisFunc(("\n"));
2106
2107 Assert(alock.isWriteLockOnCurrentThread());
2108
2109 AssertReturn( !aSuccess
2110 || mData->mMachineState == MachineState_Snapshotting
2111 || mData->mMachineState == MachineState_OnlineSnapshotting
2112 || mData->mMachineState == MachineState_LiveSnapshotting, E_FAIL);
2113
2114 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
2115 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
2116
2117 HRESULT rc = S_OK;
2118
2119 if (aSuccess)
2120 {
2121 // new snapshot becomes the current one
2122 mData->mCurrentSnapshot = task.m_pSnapshot;
2123
2124 /* memorize the first snapshot if necessary */
2125 if (!mData->mFirstSnapshot)
2126 mData->mFirstSnapshot = mData->mCurrentSnapshot;
2127
2128 int flSaveSettings = SaveS_Force; // do not do a deep compare in machine settings,
2129 // snapshots change, so we know we need to save
2130 if (!task.m_fTakingSnapshotOnline)
2131 /* the machine was powered off or saved when taking a snapshot, so
2132 * reset the mCurrentStateModified flag */
2133 flSaveSettings |= SaveS_ResetCurStateModified;
2134
2135 rc = i_saveSettings(NULL, alock, flSaveSettings); /******************2 */
2136 }
2137
2138 if (aSuccess && SUCCEEDED(rc))
2139 {
2140 /* associate old hard disks with the snapshot and do locking/unlocking*/
2141 i_commitMedia(task.m_fTakingSnapshotOnline);
2142 alock.release();
2143 }
2144 else
2145 {
2146 /* delete all differencing hard disks created (this will also attach
2147 * their parents back by rolling back mMediaData) */
2148 alock.release();
2149
2150 i_rollbackMedia();
2151
2152 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
2153 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
2154
2155 // delete the saved state file (it might have been already created)
2156 if (task.m_fTakingSnapshotOnline)
2157 // no need to test for whether the saved state file is shared: an online
2158 // snapshot means that a new saved state file was created, which we must
2159 // clean up now
2160 RTFileDelete(task.m_pSnapshot->i_getStateFilePath().c_str());
2161
2162 alock.acquire();
2163
2164 task.m_pSnapshot->uninit();
2165 alock.release();
2166
2167 }
2168
2169 /* clear out the snapshot data */
2170 task.m_pSnapshot.setNull();
2171
2172 /* alock has been released already */
2173 mParent->i_saveModifiedRegistries(); /**************3 */
2174
2175 alock.acquire();
2176
2177 return rc;
2178}
2179
2180////////////////////////////////////////////////////////////////////////////////
2181//
2182// RestoreSnapshot methods (Machine and related tasks)
2183//
2184////////////////////////////////////////////////////////////////////////////////
2185
2186HRESULT Machine::restoreSnapshot(const ComPtr<ISnapshot> &aSnapshot,
2187 ComPtr<IProgress> &aProgress)
2188{
2189 NOREF(aSnapshot);
2190 NOREF(aProgress);
2191 ReturnComNotImplemented();
2192}
2193
2194/**
2195 * Restoring a snapshot happens entirely on the server side, the machine cannot be running.
2196 *
2197 * This creates a new thread that does the work and returns a progress object to the client.
2198 * Actual work then takes place in RestoreSnapshotTask::handler().
2199 *
2200 * @note Locks this + children objects for writing!
2201 *
2202 * @param aSnapshot in: the snapshot to restore.
2203 * @param aProgress out: progress object to monitor restore thread.
2204 * @return
2205 */
2206HRESULT SessionMachine::restoreSnapshot(const ComPtr<ISnapshot> &aSnapshot,
2207 ComPtr<IProgress> &aProgress)
2208{
2209 LogFlowThisFuncEnter();
2210
2211 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2212
2213 // machine must not be running
2214 if (Global::IsOnlineOrTransient(mData->mMachineState))
2215 return setError(VBOX_E_INVALID_VM_STATE,
2216 tr("Cannot delete the current state of the running machine (machine state: %s)"),
2217 Global::stringifyMachineState(mData->mMachineState));
2218
2219 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
2220 if (FAILED(rc))
2221 return rc;
2222
2223 ISnapshot* iSnapshot = aSnapshot;
2224 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(iSnapshot));
2225 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->i_getSnapshotMachine();
2226
2227 // create a progress object. The number of operations is:
2228 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
2229 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2230
2231 ULONG ulOpCount = 1; // one for preparations
2232 ULONG ulTotalWeight = 1; // one for preparations
2233 for (MediumAttachmentList::iterator
2234 it = pSnapMachine->mMediumAttachments->begin();
2235 it != pSnapMachine->mMediumAttachments->end();
2236 ++it)
2237 {
2238 ComObjPtr<MediumAttachment> &pAttach = *it;
2239 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2240 if (pAttach->i_getType() == DeviceType_HardDisk)
2241 {
2242 ++ulOpCount;
2243 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
2244 Assert(pAttach->i_getMedium());
2245 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount,
2246 pAttach->i_getMedium()->i_getName().c_str()));
2247 }
2248 }
2249
2250 ComObjPtr<Progress> pProgress;
2251 pProgress.createObject();
2252 pProgress->init(mParent, static_cast<IMachine*>(this),
2253 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->i_getName().c_str()).raw(),
2254 FALSE /* aCancelable */,
2255 ulOpCount,
2256 ulTotalWeight,
2257 Bstr(tr("Restoring machine settings")).raw(),
2258 1);
2259
2260 /* create and start the task on a separate thread (note that it will not
2261 * start working until we release alock) */
2262 RestoreSnapshotTask *pTask = new RestoreSnapshotTask(this,
2263 pProgress,
2264 "RestoreSnap",
2265 pSnapshot);
2266 rc = pTask->createThread();
2267 pTask = NULL;
2268 if (FAILED(rc))
2269 return rc;
2270
2271 /* set the proper machine state (note: after creating a Task instance) */
2272 i_setMachineState(MachineState_RestoringSnapshot);
2273
2274 /* return the progress to the caller */
2275 pProgress.queryInterfaceTo(aProgress.asOutParam());
2276
2277 LogFlowThisFuncLeave();
2278
2279 return S_OK;
2280}
2281
2282/**
2283 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
2284 * This method gets called indirectly through SessionMachine::taskHandler() which then
2285 * calls RestoreSnapshotTask::handler().
2286 *
2287 * The RestoreSnapshotTask contains the progress object returned to the console by
2288 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
2289 *
2290 * @note Locks mParent + this object for writing.
2291 *
2292 * @param task Task data.
2293 */
2294void SessionMachine::i_restoreSnapshotHandler(RestoreSnapshotTask &task)
2295{
2296 LogFlowThisFuncEnter();
2297
2298 AutoCaller autoCaller(this);
2299
2300 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
2301 if (!autoCaller.isOk())
2302 {
2303 /* we might have been uninitialized because the session was accidentally
2304 * closed by the client, so don't assert */
2305 task.m_pProgress->i_notifyComplete(E_FAIL,
2306 COM_IIDOF(IMachine),
2307 getComponentName(),
2308 tr("The session has been accidentally closed"));
2309
2310 LogFlowThisFuncLeave();
2311 return;
2312 }
2313
2314 HRESULT rc = S_OK;
2315 Guid snapshotId;
2316 std::set<ComObjPtr<Medium> > pMediumsForNotify;
2317 std::map<Guid, std::pair<DeviceType_T, BOOL> > uIdsForNotify;
2318
2319 try
2320 {
2321 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2322
2323 /* Discard all current changes to mUserData (name, OSType etc.).
2324 * Note that the machine is powered off, so there is no need to inform
2325 * the direct session. */
2326 if (mData->flModifications)
2327 i_rollback(false /* aNotify */);
2328
2329 /* Delete the saved state file if the machine was Saved prior to this
2330 * operation */
2331 if (task.m_machineStateBackup == MachineState_Saved || task.m_machineStateBackup == MachineState_AbortedSaved)
2332 {
2333 Assert(!mSSData->strStateFilePath.isEmpty());
2334
2335 // release the saved state file AFTER unsetting the member variable
2336 // so that releaseSavedStateFile() won't think it's still in use
2337 Utf8Str strStateFile(mSSData->strStateFilePath);
2338 mSSData->strStateFilePath.setNull();
2339 i_releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
2340
2341 task.modifyBackedUpState(MachineState_PoweredOff);
2342
2343 rc = i_saveStateSettings(SaveSTS_StateFilePath);
2344 if (FAILED(rc))
2345 throw rc;
2346 }
2347
2348 RTTIMESPEC snapshotTimeStamp;
2349 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
2350
2351 {
2352 AutoReadLock snapshotLock(task.m_pSnapshot COMMA_LOCKVAL_SRC_POS);
2353
2354 /* remember the timestamp of the snapshot we're restoring from */
2355 snapshotTimeStamp = task.m_pSnapshot->i_getTimeStamp();
2356
2357 // save the snapshot ID (paranoia, here we hold the lock)
2358 snapshotId = task.m_pSnapshot->i_getId();
2359
2360 ComPtr<SnapshotMachine> pSnapshotMachine(task.m_pSnapshot->i_getSnapshotMachine());
2361
2362 /* copy all hardware data from the snapshot */
2363 i_copyFrom(pSnapshotMachine);
2364
2365 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
2366
2367 // restore the attachments from the snapshot
2368 i_setModified(IsModified_Storage);
2369 mMediumAttachments.backup();
2370 mMediumAttachments->clear();
2371 for (MediumAttachmentList::const_iterator
2372 it = pSnapshotMachine->mMediumAttachments->begin();
2373 it != pSnapshotMachine->mMediumAttachments->end();
2374 ++it)
2375 {
2376 ComObjPtr<MediumAttachment> pAttach;
2377 pAttach.createObject();
2378 pAttach->initCopy(this, *it);
2379 mMediumAttachments->push_back(pAttach);
2380 }
2381
2382 /* release the locks before the potentially lengthy operation */
2383 snapshotLock.release();
2384 alock.release();
2385
2386 rc = i_createImplicitDiffs(task.m_pProgress,
2387 1,
2388 false /* aOnline */);
2389 if (FAILED(rc))
2390 throw rc;
2391
2392 alock.acquire();
2393 snapshotLock.acquire();
2394
2395 /* Note: on success, current (old) hard disks will be
2396 * deassociated/deleted on #commit() called from #i_saveSettings() at
2397 * the end. On failure, newly created implicit diffs will be
2398 * deleted by #rollback() at the end. */
2399
2400 /* should not have a saved state file associated at this point */
2401 Assert(mSSData->strStateFilePath.isEmpty());
2402
2403 const Utf8Str &strSnapshotStateFile = task.m_pSnapshot->i_getStateFilePath();
2404
2405 if (strSnapshotStateFile.isNotEmpty())
2406 // online snapshot: then share the state file
2407 mSSData->strStateFilePath = strSnapshotStateFile;
2408
2409 const Utf8Str srcNVRAM(pSnapshotMachine->mNvramStore->i_getNonVolatileStorageFile());
2410 const Utf8Str dstNVRAM(mNvramStore->i_getNonVolatileStorageFile());
2411 if (dstNVRAM.isNotEmpty() && RTFileExists(dstNVRAM.c_str()))
2412 RTFileDelete(dstNVRAM.c_str());
2413 if (srcNVRAM.isNotEmpty() && dstNVRAM.isNotEmpty() && RTFileExists(srcNVRAM.c_str()))
2414 RTFileCopy(srcNVRAM.c_str(), dstNVRAM.c_str());
2415
2416 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", task.m_pSnapshot->i_getId().raw()));
2417 /* make the snapshot we restored from the current snapshot */
2418 mData->mCurrentSnapshot = task.m_pSnapshot;
2419 }
2420
2421 // store parent of newly created diffs for notify
2422 {
2423 MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
2424 for (MediumAttachmentList::const_iterator
2425 it = mMediumAttachments->begin();
2426 it != mMediumAttachments->end();
2427 ++it)
2428 {
2429 MediumAttachment *pAttach = *it;
2430 Medium *pMedium = pAttach->i_getMedium();
2431 if (!pMedium)
2432 continue;
2433
2434 bool fFound = false;
2435 /* was this medium attached before? */
2436 for (MediumAttachmentList::iterator
2437 oldIt = oldAtts.begin();
2438 oldIt != oldAtts.end();
2439 ++oldIt)
2440 {
2441 MediumAttachment *pOldAttach = *oldIt;
2442 if (pOldAttach->i_getMedium() == pMedium)
2443 {
2444 fFound = true;
2445 break;
2446 }
2447 }
2448 if (!fFound)
2449 {
2450 pMediumsForNotify.insert(pMedium->i_getParent());
2451 uIdsForNotify[pMedium->i_getId()] = std::pair<DeviceType_T, BOOL>(pMedium->i_getDeviceType(), TRUE);
2452 }
2453 }
2454 }
2455
2456 /* grab differencing hard disks from the old attachments that will
2457 * become unused and need to be auto-deleted */
2458 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
2459
2460 for (MediumAttachmentList::const_iterator
2461 it = mMediumAttachments.backedUpData()->begin();
2462 it != mMediumAttachments.backedUpData()->end();
2463 ++it)
2464 {
2465 ComObjPtr<MediumAttachment> pAttach = *it;
2466 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
2467
2468 /* while the hard disk is attached, the number of children or the
2469 * parent cannot change, so no lock */
2470 if ( !pMedium.isNull()
2471 && pAttach->i_getType() == DeviceType_HardDisk
2472 && !pMedium->i_getParent().isNull()
2473 && pMedium->i_getChildren().size() == 0
2474 )
2475 {
2476 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->i_getName().c_str()));
2477
2478 llDiffAttachmentsToDelete.push_back(pAttach);
2479 }
2480 }
2481
2482 /* we have already deleted the current state, so set the execution
2483 * state accordingly no matter of the delete snapshot result */
2484 if (mSSData->strStateFilePath.isNotEmpty())
2485 task.modifyBackedUpState(MachineState_Saved);
2486 else
2487 task.modifyBackedUpState(MachineState_PoweredOff);
2488
2489 /* Paranoia: no one must have saved the settings in the mean time. If
2490 * it happens nevertheless we'll close our eyes and continue below. */
2491 Assert(mMediumAttachments.isBackedUp());
2492
2493 /* assign the timestamp from the snapshot */
2494 Assert(RTTimeSpecGetMilli(&snapshotTimeStamp) != 0);
2495 mData->mLastStateChange = snapshotTimeStamp;
2496
2497 // detach the current-state diffs that we detected above and build a list of
2498 // image files to delete _after_ i_saveSettings()
2499
2500 MediaList llDiffsToDelete;
2501
2502 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
2503 it != llDiffAttachmentsToDelete.end();
2504 ++it)
2505 {
2506 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
2507 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
2508
2509 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2510
2511 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->i_getName().c_str()));
2512
2513 // Normally we "detach" the medium by removing the attachment object
2514 // from the current machine data; i_saveSettings() below would then
2515 // compare the current machine data with the one in the backup
2516 // and actually call Medium::removeBackReference(). But that works only half
2517 // the time in our case so instead we force a detachment here:
2518 // remove from machine data
2519 mMediumAttachments->remove(pAttach);
2520 // Remove it from the backup or else i_saveSettings will try to detach
2521 // it again and assert. The paranoia check avoids crashes (see
2522 // assert above) if this code is buggy and saves settings in the
2523 // wrong place.
2524 if (mMediumAttachments.isBackedUp())
2525 mMediumAttachments.backedUpData()->remove(pAttach);
2526 // then clean up backrefs
2527 pMedium->i_removeBackReference(mData->mUuid);
2528
2529 llDiffsToDelete.push_back(pMedium);
2530 }
2531
2532 // save machine settings, reset the modified flag and commit;
2533 bool fNeedsGlobalSaveSettings = false;
2534 rc = i_saveSettings(&fNeedsGlobalSaveSettings, alock,
2535 SaveS_ResetCurStateModified);
2536 if (FAILED(rc))
2537 throw rc;
2538
2539 // release the locks before updating registry and deleting image files
2540 alock.release();
2541
2542 // unconditionally add the parent registry.
2543 mParent->i_markRegistryModified(mParent->i_getGlobalRegistryId());
2544
2545 // from here on we cannot roll back on failure any more
2546
2547 for (MediaList::iterator it = llDiffsToDelete.begin();
2548 it != llDiffsToDelete.end();
2549 ++it)
2550 {
2551 ComObjPtr<Medium> &pMedium = *it;
2552 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->i_getName().c_str()));
2553
2554 ComObjPtr<Medium> pParent = pMedium->i_getParent();
2555 // store the id here because it becomes NULL after deleting storage.
2556 com::Guid id = pMedium->i_getId();
2557 HRESULT rc2 = pMedium->i_deleteStorage(NULL /* aProgress */,
2558 true /* aWait */,
2559 false /* aNotify */);
2560 // ignore errors here because we cannot roll back after i_saveSettings() above
2561 if (SUCCEEDED(rc2))
2562 {
2563 pMediumsForNotify.insert(pParent);
2564 uIdsForNotify[id] = std::pair<DeviceType_T, BOOL>(pMedium->i_getDeviceType(), FALSE);
2565 pMedium->uninit();
2566 }
2567 }
2568 }
2569 catch (HRESULT aRC)
2570 {
2571 rc = aRC;
2572 }
2573
2574 if (FAILED(rc))
2575 {
2576 /* preserve existing error info */
2577 ErrorInfoKeeper eik;
2578
2579 /* undo all changes on failure */
2580 i_rollback(false /* aNotify */);
2581
2582 }
2583
2584 mParent->i_saveModifiedRegistries();
2585
2586 /* restore the machine state */
2587 i_setMachineState(task.m_machineStateBackup);
2588
2589 /* set the result (this will try to fetch current error info on failure) */
2590 task.m_pProgress->i_notifyComplete(rc);
2591
2592 if (SUCCEEDED(rc))
2593 {
2594 mParent->i_onSnapshotRestored(mData->mUuid, snapshotId);
2595 for (std::map<Guid, std::pair<DeviceType_T, BOOL> >::const_iterator it = uIdsForNotify.begin();
2596 it != uIdsForNotify.end();
2597 ++it)
2598 {
2599 mParent->i_onMediumRegistered(it->first, it->second.first, it->second.second);
2600 }
2601 for (std::set<ComObjPtr<Medium> >::const_iterator it = pMediumsForNotify.begin();
2602 it != pMediumsForNotify.end();
2603 ++it)
2604 {
2605 if (it->isNotNull())
2606 mParent->i_onMediumConfigChanged(*it);
2607 }
2608 }
2609
2610 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
2611
2612 LogFlowThisFuncLeave();
2613}
2614
2615////////////////////////////////////////////////////////////////////////////////
2616//
2617// DeleteSnapshot methods (SessionMachine and related tasks)
2618//
2619////////////////////////////////////////////////////////////////////////////////
2620
2621HRESULT Machine::deleteSnapshot(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2622{
2623 NOREF(aId);
2624 NOREF(aProgress);
2625 ReturnComNotImplemented();
2626}
2627
2628HRESULT SessionMachine::deleteSnapshot(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2629{
2630 return i_deleteSnapshot(aId, aId,
2631 FALSE /* fDeleteAllChildren */,
2632 aProgress);
2633}
2634
2635HRESULT Machine::deleteSnapshotAndAllChildren(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2636{
2637 NOREF(aId);
2638 NOREF(aProgress);
2639 ReturnComNotImplemented();
2640}
2641
2642HRESULT SessionMachine::deleteSnapshotAndAllChildren(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2643{
2644 return i_deleteSnapshot(aId, aId,
2645 TRUE /* fDeleteAllChildren */,
2646 aProgress);
2647}
2648
2649HRESULT Machine::deleteSnapshotRange(const com::Guid &aStartId, const com::Guid &aEndId, ComPtr<IProgress> &aProgress)
2650{
2651 NOREF(aStartId);
2652 NOREF(aEndId);
2653 NOREF(aProgress);
2654 ReturnComNotImplemented();
2655}
2656
2657HRESULT SessionMachine::deleteSnapshotRange(const com::Guid &aStartId, const com::Guid &aEndId, ComPtr<IProgress> &aProgress)
2658{
2659 return i_deleteSnapshot(aStartId, aEndId,
2660 FALSE /* fDeleteAllChildren */,
2661 aProgress);
2662}
2663
2664
2665/**
2666 * Implementation for SessionMachine::i_deleteSnapshot().
2667 *
2668 * Gets called from SessionMachine::DeleteSnapshot(). Deleting a snapshot
2669 * happens entirely on the server side if the machine is not running, and
2670 * if it is running then the merges are done via internal session callbacks.
2671 *
2672 * This creates a new thread that does the work and returns a progress
2673 * object to the client.
2674 *
2675 * Actual work then takes place in SessionMachine::i_deleteSnapshotHandler().
2676 *
2677 * @note Locks mParent + this + children objects for writing!
2678 */
2679HRESULT SessionMachine::i_deleteSnapshot(const com::Guid &aStartId,
2680 const com::Guid &aEndId,
2681 BOOL aDeleteAllChildren,
2682 ComPtr<IProgress> &aProgress)
2683{
2684 LogFlowThisFuncEnter();
2685
2686 AssertReturn(!aStartId.isZero() && !aEndId.isZero() && aStartId.isValid() && aEndId.isValid(), E_INVALIDARG);
2687
2688 /** @todo implement the "and all children" and "range" variants */
2689 if (aDeleteAllChildren || aStartId != aEndId)
2690 ReturnComNotImplemented();
2691
2692 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2693
2694 if (Global::IsTransient(mData->mMachineState))
2695 return setError(VBOX_E_INVALID_VM_STATE,
2696 tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
2697 Global::stringifyMachineState(mData->mMachineState));
2698
2699 // be very picky about machine states
2700 if ( Global::IsOnlineOrTransient(mData->mMachineState)
2701 && mData->mMachineState != MachineState_PoweredOff
2702 && mData->mMachineState != MachineState_Saved
2703 && mData->mMachineState != MachineState_Teleported
2704 && mData->mMachineState != MachineState_Aborted
2705 && mData->mMachineState != MachineState_AbortedSaved
2706 && mData->mMachineState != MachineState_Running
2707 && mData->mMachineState != MachineState_Paused)
2708 return setError(VBOX_E_INVALID_VM_STATE,
2709 tr("Invalid machine state: %s"),
2710 Global::stringifyMachineState(mData->mMachineState));
2711
2712 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
2713 if (FAILED(rc))
2714 return rc;
2715
2716 ComObjPtr<Snapshot> pSnapshot;
2717 rc = i_findSnapshotById(aStartId, pSnapshot, true /* aSetError */);
2718 if (FAILED(rc))
2719 return rc;
2720
2721 AutoWriteLock snapshotLock(pSnapshot COMMA_LOCKVAL_SRC_POS);
2722 Utf8Str str;
2723
2724 size_t childrenCount = pSnapshot->i_getChildrenCount();
2725 if (childrenCount > 1)
2726 return setError(VBOX_E_INVALID_OBJECT_STATE,
2727 tr("Snapshot '%s' of the machine '%s' cannot be deleted, because it has %d child snapshots, which is more than the one snapshot allowed for deletion",
2728 "", childrenCount),
2729 pSnapshot->i_getName().c_str(),
2730 mUserData->s.strName.c_str(),
2731 childrenCount);
2732
2733 if (pSnapshot == mData->mCurrentSnapshot && childrenCount >= 1)
2734 return setError(VBOX_E_INVALID_OBJECT_STATE,
2735 tr("Snapshot '%s' of the machine '%s' cannot be deleted, because it is the current snapshot and has one child snapshot"),
2736 pSnapshot->i_getName().c_str(),
2737 mUserData->s.strName.c_str());
2738
2739 /* If the snapshot being deleted is the current one, ensure current
2740 * settings are committed and saved.
2741 */
2742 if (pSnapshot == mData->mCurrentSnapshot)
2743 {
2744 if (mData->flModifications)
2745 {
2746 snapshotLock.release();
2747 rc = i_saveSettings(NULL, alock);
2748 snapshotLock.acquire();
2749 // no need to change for whether VirtualBox.xml needs saving since
2750 // we can't have a machine XML rename pending at this point
2751 if (FAILED(rc)) return rc;
2752 }
2753 }
2754
2755 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->i_getSnapshotMachine();
2756
2757 /* create a progress object. The number of operations is:
2758 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
2759 */
2760 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2761
2762 ULONG ulOpCount = 1; // one for preparations
2763 ULONG ulTotalWeight = 1; // one for preparations
2764
2765 if (pSnapshot->i_getStateFilePath().isNotEmpty())
2766 {
2767 ++ulOpCount;
2768 ++ulTotalWeight; // assume 1 MB for deleting the state file
2769 }
2770
2771 bool fDeleteOnline = mData->mMachineState == MachineState_Running || mData->mMachineState == MachineState_Paused;
2772
2773 // count normal hard disks and add their sizes to the weight
2774 for (MediumAttachmentList::iterator
2775 it = pSnapMachine->mMediumAttachments->begin();
2776 it != pSnapMachine->mMediumAttachments->end();
2777 ++it)
2778 {
2779 ComObjPtr<MediumAttachment> &pAttach = *it;
2780 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2781 if (pAttach->i_getType() == DeviceType_HardDisk)
2782 {
2783 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
2784 Assert(pHD);
2785 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2786
2787 MediumType_T type = pHD->i_getType();
2788 // writethrough and shareable images are unaffected by snapshots,
2789 // so do nothing for them
2790 if ( type != MediumType_Writethrough
2791 && type != MediumType_Shareable
2792 && type != MediumType_Readonly)
2793 {
2794 // normal or immutable media need attention
2795 ++ulOpCount;
2796 // offline merge includes medium resizing
2797 if (!fDeleteOnline)
2798 ++ulOpCount;
2799 ulTotalWeight += (ULONG)(pHD->i_getSize() / _1M);
2800 }
2801 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->i_getName().c_str()));
2802 }
2803 }
2804
2805 ComObjPtr<Progress> pProgress;
2806 pProgress.createObject();
2807 pProgress->init(mParent, static_cast<IMachine*>(this),
2808 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->i_getName().c_str()).raw(),
2809 FALSE /* aCancelable */,
2810 ulOpCount,
2811 ulTotalWeight,
2812 Bstr(tr("Setting up")).raw(),
2813 1);
2814
2815 /* create and start the task on a separate thread */
2816 DeleteSnapshotTask *pTask = new DeleteSnapshotTask(this, pProgress,
2817 "DeleteSnap",
2818 fDeleteOnline,
2819 pSnapshot);
2820 rc = pTask->createThread();
2821 pTask = NULL;
2822 if (FAILED(rc))
2823 return rc;
2824
2825 // the task might start running but will block on acquiring the machine's write lock
2826 // which we acquired above; once this function leaves, the task will be unblocked;
2827 // set the proper machine state here now (note: after creating a Task instance)
2828 if (mData->mMachineState == MachineState_Running)
2829 {
2830 i_setMachineState(MachineState_DeletingSnapshotOnline);
2831 i_updateMachineStateOnClient();
2832 }
2833 else if (mData->mMachineState == MachineState_Paused)
2834 {
2835 i_setMachineState(MachineState_DeletingSnapshotPaused);
2836 i_updateMachineStateOnClient();
2837 }
2838 else
2839 i_setMachineState(MachineState_DeletingSnapshot);
2840
2841 /* return the progress to the caller */
2842 pProgress.queryInterfaceTo(aProgress.asOutParam());
2843
2844 LogFlowThisFuncLeave();
2845
2846 return S_OK;
2847}
2848
2849/**
2850 * Helper struct for SessionMachine::deleteSnapshotHandler().
2851 */
2852struct MediumDeleteRec
2853{
2854 MediumDeleteRec()
2855 : mfNeedsOnlineMerge(false),
2856 mpMediumLockList(NULL)
2857 {}
2858
2859 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2860 const ComObjPtr<Medium> &aSource,
2861 const ComObjPtr<Medium> &aTarget,
2862 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2863 bool fMergeForward,
2864 const ComObjPtr<Medium> &aParentForTarget,
2865 MediumLockList *aChildrenToReparent,
2866 bool fNeedsOnlineMerge,
2867 MediumLockList *aMediumLockList,
2868 const ComPtr<IToken> &aHDLockToken)
2869 : mpHD(aHd),
2870 mpSource(aSource),
2871 mpTarget(aTarget),
2872 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2873 mfMergeForward(fMergeForward),
2874 mpParentForTarget(aParentForTarget),
2875 mpChildrenToReparent(aChildrenToReparent),
2876 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2877 mpMediumLockList(aMediumLockList),
2878 mpHDLockToken(aHDLockToken)
2879 {}
2880
2881 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2882 const ComObjPtr<Medium> &aSource,
2883 const ComObjPtr<Medium> &aTarget,
2884 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2885 bool fMergeForward,
2886 const ComObjPtr<Medium> &aParentForTarget,
2887 MediumLockList *aChildrenToReparent,
2888 bool fNeedsOnlineMerge,
2889 MediumLockList *aMediumLockList,
2890 const ComPtr<IToken> &aHDLockToken,
2891 const Guid &aMachineId,
2892 const Guid &aSnapshotId)
2893 : mpHD(aHd),
2894 mpSource(aSource),
2895 mpTarget(aTarget),
2896 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2897 mfMergeForward(fMergeForward),
2898 mpParentForTarget(aParentForTarget),
2899 mpChildrenToReparent(aChildrenToReparent),
2900 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2901 mpMediumLockList(aMediumLockList),
2902 mpHDLockToken(aHDLockToken),
2903 mMachineId(aMachineId),
2904 mSnapshotId(aSnapshotId)
2905 {}
2906
2907 ComObjPtr<Medium> mpHD;
2908 ComObjPtr<Medium> mpSource;
2909 ComObjPtr<Medium> mpTarget;
2910 ComObjPtr<MediumAttachment> mpOnlineMediumAttachment;
2911 bool mfMergeForward;
2912 ComObjPtr<Medium> mpParentForTarget;
2913 MediumLockList *mpChildrenToReparent;
2914 bool mfNeedsOnlineMerge;
2915 MediumLockList *mpMediumLockList;
2916 /** optional lock token, used only in case mpHD is not merged/deleted */
2917 ComPtr<IToken> mpHDLockToken;
2918 /* these are for reattaching the hard disk in case of a failure: */
2919 Guid mMachineId;
2920 Guid mSnapshotId;
2921};
2922
2923typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2924
2925/**
2926 * Worker method for the delete snapshot thread created by
2927 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2928 * through SessionMachine::taskHandler() which then calls
2929 * DeleteSnapshotTask::handler().
2930 *
2931 * The DeleteSnapshotTask contains the progress object returned to the console
2932 * by SessionMachine::DeleteSnapshot, through which progress and results are
2933 * reported.
2934 *
2935 * SessionMachine::DeleteSnapshot() has set the machine state to
2936 * MachineState_DeletingSnapshot right after creating this task. Since we block
2937 * on the machine write lock at the beginning, once that has been acquired, we
2938 * can assume that the machine state is indeed that.
2939 *
2940 * @note Locks the machine + the snapshot + the media tree for writing!
2941 *
2942 * @param task Task data.
2943 */
2944void SessionMachine::i_deleteSnapshotHandler(DeleteSnapshotTask &task)
2945{
2946 LogFlowThisFuncEnter();
2947
2948 MultiResult mrc(S_OK);
2949 AutoCaller autoCaller(this);
2950 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
2951 if (FAILED(autoCaller.rc()))
2952 {
2953 /* we might have been uninitialized because the session was accidentally
2954 * closed by the client, so don't assert */
2955 mrc = setError(E_FAIL,
2956 tr("The session has been accidentally closed"));
2957 task.m_pProgress->i_notifyComplete(mrc);
2958 LogFlowThisFuncLeave();
2959 return;
2960 }
2961
2962 MediumDeleteRecList toDelete;
2963 Guid snapshotId;
2964 std::set<ComObjPtr<Medium> > pMediumsForNotify;
2965 std::map<Guid,DeviceType_T> uIdsForNotify;
2966
2967 try
2968 {
2969 HRESULT rc = S_OK;
2970
2971 /* Locking order: */
2972 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2973 task.m_pSnapshot->lockHandle() // snapshot
2974 COMMA_LOCKVAL_SRC_POS);
2975 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2976 // has exited after setting the machine state to MachineState_DeletingSnapshot
2977
2978 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle()
2979 COMMA_LOCKVAL_SRC_POS);
2980
2981 ComObjPtr<SnapshotMachine> pSnapMachine = task.m_pSnapshot->i_getSnapshotMachine();
2982 // no need to lock the snapshot machine since it is const by definition
2983 Guid machineId = pSnapMachine->i_getId();
2984
2985 // save the snapshot ID (for callbacks)
2986 snapshotId = task.m_pSnapshot->i_getId();
2987
2988 // first pass:
2989 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2990
2991 // Go thru the attachments of the snapshot machine (the media in here
2992 // point to the disk states _before_ the snapshot was taken, i.e. the
2993 // state we're restoring to; for each such medium, we will need to
2994 // merge it with its one and only child (the diff image holding the
2995 // changes written after the snapshot was taken).
2996 for (MediumAttachmentList::iterator
2997 it = pSnapMachine->mMediumAttachments->begin();
2998 it != pSnapMachine->mMediumAttachments->end();
2999 ++it)
3000 {
3001 ComObjPtr<MediumAttachment> &pAttach = *it;
3002 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
3003 if (pAttach->i_getType() != DeviceType_HardDisk)
3004 continue;
3005
3006 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
3007 Assert(!pHD.isNull());
3008
3009 {
3010 // writethrough, shareable and readonly images are
3011 // unaffected by snapshots, skip them
3012 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
3013 MediumType_T type = pHD->i_getType();
3014 if ( type == MediumType_Writethrough
3015 || type == MediumType_Shareable
3016 || type == MediumType_Readonly)
3017 continue;
3018 }
3019
3020#ifdef DEBUG
3021 pHD->i_dumpBackRefs();
3022#endif
3023
3024 // needs to be merged with child or deleted, check prerequisites
3025 ComObjPtr<Medium> pTarget;
3026 ComObjPtr<Medium> pSource;
3027 bool fMergeForward = false;
3028 ComObjPtr<Medium> pParentForTarget;
3029 MediumLockList *pChildrenToReparent = NULL;
3030 bool fNeedsOnlineMerge = false;
3031 bool fOnlineMergePossible = task.m_fDeleteOnline;
3032 MediumLockList *pMediumLockList = NULL;
3033 MediumLockList *pVMMALockList = NULL;
3034 ComPtr<IToken> pHDLockToken;
3035 ComObjPtr<MediumAttachment> pOnlineMediumAttachment;
3036 if (fOnlineMergePossible)
3037 {
3038 // Look up the corresponding medium attachment in the currently
3039 // running VM. Any failure prevents a live merge. Could be made
3040 // a tad smarter by trying a few candidates, so that e.g. disks
3041 // which are simply moved to a different controller slot do not
3042 // prevent online merging in general.
3043 pOnlineMediumAttachment =
3044 i_findAttachment(*mMediumAttachments.data(),
3045 pAttach->i_getControllerName(),
3046 pAttach->i_getPort(),
3047 pAttach->i_getDevice());
3048 if (pOnlineMediumAttachment)
3049 {
3050 rc = mData->mSession.mLockedMedia.Get(pOnlineMediumAttachment,
3051 pVMMALockList);
3052 if (FAILED(rc))
3053 fOnlineMergePossible = false;
3054 }
3055 else
3056 fOnlineMergePossible = false;
3057 }
3058
3059 // no need to hold the lock any longer
3060 attachLock.release();
3061
3062 treeLock.release();
3063 rc = i_prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
3064 fOnlineMergePossible,
3065 pVMMALockList, pSource, pTarget,
3066 fMergeForward, pParentForTarget,
3067 pChildrenToReparent,
3068 fNeedsOnlineMerge,
3069 pMediumLockList,
3070 pHDLockToken);
3071 treeLock.acquire();
3072 if (FAILED(rc))
3073 throw rc;
3074
3075 // For simplicity, prepareDeleteSnapshotMedium selects the merge
3076 // direction in the following way: we merge pHD onto its child
3077 // (forward merge), not the other way round, because that saves us
3078 // from unnecessarily shuffling around the attachments for the
3079 // machine that follows the snapshot (next snapshot or current
3080 // state), unless it's a base image. Backwards merges of the first
3081 // snapshot into the base image is essential, as it ensures that
3082 // when all snapshots are deleted the only remaining image is a
3083 // base image. Important e.g. for medium formats which do not have
3084 // a file representation such as iSCSI.
3085
3086 // not going to merge a big source into a small target on online merge. Otherwise it will be resized
3087 if (fNeedsOnlineMerge && pSource->i_getLogicalSize() > pTarget->i_getLogicalSize())
3088 {
3089 rc = setError(E_FAIL,
3090 tr("Unable to merge storage '%s', because it is smaller than the source image. If you resize it to have a capacity of at least %lld bytes you can retry",
3091 "", pSource->i_getLogicalSize()),
3092 pTarget->i_getLocationFull().c_str(), pSource->i_getLogicalSize());
3093 throw rc;
3094 }
3095
3096 // a couple paranoia checks for backward merges
3097 if (pMediumLockList != NULL && !fMergeForward)
3098 {
3099 // parent is null -> this disk is a base hard disk: we will
3100 // then do a backward merge, i.e. merge its only child onto the
3101 // base disk. Here we need then to update the attachment that
3102 // refers to the child and have it point to the parent instead
3103 Assert(pHD->i_getChildren().size() == 1);
3104
3105 ComObjPtr<Medium> pReplaceHD = pHD->i_getChildren().front();
3106
3107 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
3108 }
3109
3110 Guid replaceMachineId;
3111 Guid replaceSnapshotId;
3112
3113 const Guid *pReplaceMachineId = pSource->i_getFirstMachineBackrefId();
3114 // minimal sanity checking
3115 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
3116 if (pReplaceMachineId)
3117 replaceMachineId = *pReplaceMachineId;
3118
3119 const Guid *pSnapshotId = pSource->i_getFirstMachineBackrefSnapshotId();
3120 if (pSnapshotId)
3121 replaceSnapshotId = *pSnapshotId;
3122
3123 if (replaceMachineId.isValid() && !replaceMachineId.isZero())
3124 {
3125 // Adjust the backreferences, otherwise merging will assert.
3126 // Note that the medium attachment object stays associated
3127 // with the snapshot until the merge was successful.
3128 HRESULT rc2 = S_OK;
3129 rc2 = pSource->i_removeBackReference(replaceMachineId, replaceSnapshotId);
3130 AssertComRC(rc2);
3131
3132 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
3133 pOnlineMediumAttachment,
3134 fMergeForward,
3135 pParentForTarget,
3136 pChildrenToReparent,
3137 fNeedsOnlineMerge,
3138 pMediumLockList,
3139 pHDLockToken,
3140 replaceMachineId,
3141 replaceSnapshotId));
3142 }
3143 else
3144 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
3145 pOnlineMediumAttachment,
3146 fMergeForward,
3147 pParentForTarget,
3148 pChildrenToReparent,
3149 fNeedsOnlineMerge,
3150 pMediumLockList,
3151 pHDLockToken));
3152 }
3153
3154 {
3155 /* check available space on the storage */
3156 RTFOFF pcbTotal = 0;
3157 RTFOFF pcbFree = 0;
3158 uint32_t pcbBlock = 0;
3159 uint32_t pcbSector = 0;
3160 std::multimap<uint32_t, uint64_t> neededStorageFreeSpace;
3161 std::map<uint32_t, const char*> serialMapToStoragePath;
3162
3163 for (MediumDeleteRecList::const_iterator
3164 it = toDelete.begin();
3165 it != toDelete.end();
3166 ++it)
3167 {
3168 uint64_t diskSize = 0;
3169 uint32_t pu32Serial = 0;
3170 ComObjPtr<Medium> pSource_local = it->mpSource;
3171 ComObjPtr<Medium> pTarget_local = it->mpTarget;
3172 ComPtr<IMediumFormat> pTargetFormat;
3173
3174 {
3175 if ( pSource_local.isNull()
3176 || pSource_local == pTarget_local)
3177 continue;
3178 }
3179
3180 rc = pTarget_local->COMGETTER(MediumFormat)(pTargetFormat.asOutParam());
3181 if (FAILED(rc))
3182 throw rc;
3183
3184 if (pTarget_local->i_isMediumFormatFile())
3185 {
3186 int vrc = RTFsQuerySerial(pTarget_local->i_getLocationFull().c_str(), &pu32Serial);
3187 if (RT_FAILURE(vrc))
3188 {
3189 rc = setError(E_FAIL,
3190 tr("Unable to merge storage '%s'. Can't get storage UID"),
3191 pTarget_local->i_getLocationFull().c_str());
3192 throw rc;
3193 }
3194
3195 pSource_local->COMGETTER(Size)((LONG64*)&diskSize);
3196
3197 /** @todo r=klaus this is too pessimistic... should take
3198 * the current size and maximum size of the target image
3199 * into account, because a X GB image with Y GB capacity
3200 * can only grow by Y-X GB (ignoring overhead, which
3201 * unfortunately is hard to estimate, some have next to
3202 * nothing, some have a certain percentage...) */
3203 /* store needed free space in multimap */
3204 neededStorageFreeSpace.insert(std::make_pair(pu32Serial, diskSize));
3205 /* linking storage UID with snapshot path, it is a helper container (just for easy finding needed path) */
3206 serialMapToStoragePath.insert(std::make_pair(pu32Serial, pTarget_local->i_getLocationFull().c_str()));
3207 }
3208 }
3209
3210 while (!neededStorageFreeSpace.empty())
3211 {
3212 std::pair<std::multimap<uint32_t,uint64_t>::iterator,std::multimap<uint32_t,uint64_t>::iterator> ret;
3213 uint64_t commonSourceStoragesSize = 0;
3214
3215 /* find all records in multimap with identical storage UID */
3216 ret = neededStorageFreeSpace.equal_range(neededStorageFreeSpace.begin()->first);
3217 std::multimap<uint32_t,uint64_t>::const_iterator it_ns = ret.first;
3218
3219 for (; it_ns != ret.second ; ++it_ns)
3220 {
3221 commonSourceStoragesSize += it_ns->second;
3222 }
3223
3224 /* find appropriate path by storage UID */
3225 std::map<uint32_t,const char*>::const_iterator it_sm = serialMapToStoragePath.find(ret.first->first);
3226 /* get info about a storage */
3227 if (it_sm == serialMapToStoragePath.end())
3228 {
3229 LogFlowThisFunc(("Path to the storage wasn't found...\n"));
3230
3231 rc = setError(E_INVALIDARG,
3232 tr("Unable to merge storage '%s'. Path to the storage wasn't found"),
3233 it_sm->second);
3234 throw rc;
3235 }
3236
3237 int vrc = RTFsQuerySizes(it_sm->second, &pcbTotal, &pcbFree, &pcbBlock, &pcbSector);
3238 if (RT_FAILURE(vrc))
3239 {
3240 rc = setError(E_FAIL,
3241 tr("Unable to merge storage '%s'. Can't get the storage size"),
3242 it_sm->second);
3243 throw rc;
3244 }
3245
3246 if (commonSourceStoragesSize > (uint64_t)pcbFree)
3247 {
3248 LogFlowThisFunc(("Not enough free space to merge...\n"));
3249
3250 rc = setError(E_OUTOFMEMORY,
3251 tr("Unable to merge storage '%s'. Not enough free storage space"),
3252 it_sm->second);
3253 throw rc;
3254 }
3255
3256 neededStorageFreeSpace.erase(ret.first, ret.second);
3257 }
3258
3259 serialMapToStoragePath.clear();
3260 }
3261
3262 // we can release the locks now since the machine state is MachineState_DeletingSnapshot
3263 treeLock.release();
3264 multiLock.release();
3265
3266 /* Now we checked that we can successfully merge all normal hard disks
3267 * (unless a runtime error like end-of-disc happens). Now get rid of
3268 * the saved state (if present), as that will free some disk space.
3269 * The snapshot itself will be deleted as late as possible, so that
3270 * the user can repeat the delete operation if he runs out of disk
3271 * space or cancels the delete operation. */
3272
3273 /* second pass: */
3274 LogFlowThisFunc(("2: Deleting saved state...\n"));
3275
3276 {
3277 // saveAllSnapshots() needs a machine lock, and the snapshots
3278 // tree is protected by the machine lock as well
3279 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
3280
3281 Utf8Str stateFilePath = task.m_pSnapshot->i_getStateFilePath();
3282 if (!stateFilePath.isEmpty())
3283 {
3284 task.m_pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")).raw(),
3285 1); // weight
3286
3287 i_releaseSavedStateFile(stateFilePath, task.m_pSnapshot /* pSnapshotToIgnore */);
3288
3289 // machine will need saving now
3290 machineLock.release();
3291 mParent->i_markRegistryModified(i_getId());
3292 }
3293 }
3294
3295 /* third pass: */
3296 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
3297
3298 /// @todo NEWMEDIA turn the following errors into warnings because the
3299 /// snapshot itself has been already deleted (and interpret these
3300 /// warnings properly on the GUI side)
3301 for (MediumDeleteRecList::iterator it = toDelete.begin();
3302 it != toDelete.end();)
3303 {
3304 const ComObjPtr<Medium> &pMedium(it->mpHD);
3305 ULONG ulWeight;
3306
3307 {
3308 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3309 ulWeight = (ULONG)(pMedium->i_getSize() / _1M);
3310 }
3311
3312 const char *pszOperationText = it->mfNeedsOnlineMerge ?
3313 tr("Merging differencing image '%s'")
3314 : tr("Resizing before merge differencing image '%s'");
3315
3316 task.m_pProgress->SetNextOperation(BstrFmt(pszOperationText,
3317 pMedium->i_getName().c_str()).raw(),
3318 ulWeight);
3319
3320 bool fNeedSourceUninit = false;
3321 bool fReparentTarget = false;
3322 if (it->mpMediumLockList == NULL)
3323 {
3324 /* no real merge needed, just updating state and delete
3325 * diff files if necessary */
3326 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
3327
3328 Assert( !it->mfMergeForward
3329 || pMedium->i_getChildren().size() == 0);
3330
3331 /* Delete the differencing hard disk (has no children). Two
3332 * exceptions: if it's the last medium in the chain or if it's
3333 * a backward merge we don't want to handle due to complexity.
3334 * In both cases leave the image in place. If it's the first
3335 * exception the user can delete it later if he wants. */
3336 if (!pMedium->i_getParent().isNull())
3337 {
3338 Assert(pMedium->i_getState() == MediumState_Deleting);
3339 /* No need to hold the lock any longer. */
3340 mLock.release();
3341 ComObjPtr<Medium> pParent = pMedium->i_getParent();
3342 Guid uMedium = pMedium->i_getId();
3343 DeviceType_T uMediumType = pMedium->i_getDeviceType();
3344 rc = pMedium->i_deleteStorage(&task.m_pProgress,
3345 true /* aWait */,
3346 false /* aNotify */);
3347 if (FAILED(rc))
3348 throw rc;
3349
3350 pMediumsForNotify.insert(pParent);
3351 uIdsForNotify[uMedium] = uMediumType;
3352
3353 // need to uninit the deleted medium
3354 fNeedSourceUninit = true;
3355 }
3356 }
3357 else
3358 {
3359 {
3360 //store ids before merging for notify
3361 pMediumsForNotify.insert(it->mpTarget);
3362 if (it->mfMergeForward)
3363 pMediumsForNotify.insert(it->mpSource->i_getParent());
3364 else
3365 {
3366 //children which will be reparented to target
3367 for (MediaList::const_iterator iit = it->mpSource->i_getChildren().begin();
3368 iit != it->mpSource->i_getChildren().end();
3369 ++iit)
3370 {
3371 pMediumsForNotify.insert(*iit);
3372 }
3373 }
3374 if (it->mfMergeForward)
3375 {
3376 for (ComObjPtr<Medium> pTmpMedium = it->mpTarget->i_getParent();
3377 pTmpMedium && pTmpMedium != it->mpSource;
3378 pTmpMedium = pTmpMedium->i_getParent())
3379 {
3380 uIdsForNotify[pTmpMedium->i_getId()] = pTmpMedium->i_getDeviceType();
3381 }
3382 uIdsForNotify[it->mpSource->i_getId()] = it->mpSource->i_getDeviceType();
3383 }
3384 else
3385 {
3386 for (ComObjPtr<Medium> pTmpMedium = it->mpSource;
3387 pTmpMedium && pTmpMedium != it->mpTarget;
3388 pTmpMedium = pTmpMedium->i_getParent())
3389 {
3390 uIdsForNotify[pTmpMedium->i_getId()] = pTmpMedium->i_getDeviceType();
3391 }
3392 }
3393 }
3394
3395 bool fNeedsSave = false;
3396 if (it->mfNeedsOnlineMerge)
3397 {
3398 // Put the medium merge information (MediumDeleteRec) where
3399 // SessionMachine::FinishOnlineMergeMedium can get at it.
3400 // This callback will arrive while onlineMergeMedium is
3401 // still executing, and there can't be two tasks.
3402 /// @todo r=klaus this hack needs to go, and the logic needs to be "unconvoluted", putting SessionMachine in charge of coordinating the reconfig/resume.
3403 mConsoleTaskData.mDeleteSnapshotInfo = (void *)&(*it);
3404 // online medium merge, in the direction decided earlier
3405 rc = i_onlineMergeMedium(it->mpOnlineMediumAttachment,
3406 it->mpSource,
3407 it->mpTarget,
3408 it->mfMergeForward,
3409 it->mpParentForTarget,
3410 it->mpChildrenToReparent,
3411 it->mpMediumLockList,
3412 task.m_pProgress,
3413 &fNeedsSave);
3414 mConsoleTaskData.mDeleteSnapshotInfo = NULL;
3415 }
3416 else
3417 {
3418 // normal medium merge, in the direction decided earlier
3419 rc = it->mpSource->i_mergeTo(it->mpTarget,
3420 it->mfMergeForward,
3421 it->mpParentForTarget,
3422 it->mpChildrenToReparent,
3423 it->mpMediumLockList,
3424 &task.m_pProgress,
3425 true /* aWait */,
3426 false /* aNotify */);
3427 }
3428
3429 // If the merge failed, we need to do our best to have a usable
3430 // VM configuration afterwards. The return code doesn't tell
3431 // whether the merge completed and so we have to check if the
3432 // source medium (diff images are always file based at the
3433 // moment) is still there or not. Be careful not to lose the
3434 // error code below, before the "Delayed failure exit".
3435 if (FAILED(rc))
3436 {
3437 AutoReadLock mlock(it->mpSource COMMA_LOCKVAL_SRC_POS);
3438 if (!it->mpSource->i_isMediumFormatFile())
3439 // Diff medium not backed by a file - cannot get status so
3440 // be pessimistic.
3441 throw rc;
3442 const Utf8Str &loc = it->mpSource->i_getLocationFull();
3443 // Source medium is still there, so merge failed early.
3444 if (RTFileExists(loc.c_str()))
3445 throw rc;
3446
3447 // Source medium is gone. Assume the merge succeeded and
3448 // thus it's safe to remove the attachment. We use the
3449 // "Delayed failure exit" below.
3450 }
3451
3452 // need to change the medium attachment for backward merges
3453 fReparentTarget = !it->mfMergeForward;
3454
3455 if (!it->mfNeedsOnlineMerge)
3456 {
3457 // need to uninit the medium deleted by the merge
3458 fNeedSourceUninit = true;
3459
3460 // delete the no longer needed medium lock list, which
3461 // implicitly handled the unlocking
3462 delete it->mpMediumLockList;
3463 it->mpMediumLockList = NULL;
3464 }
3465 }
3466
3467 // Now that the medium is successfully merged/deleted/whatever,
3468 // remove the medium attachment from the snapshot. For a backwards
3469 // merge the target attachment needs to be removed from the
3470 // snapshot, as the VM will take it over. For forward merges the
3471 // source medium attachment needs to be removed.
3472 ComObjPtr<MediumAttachment> pAtt;
3473 if (fReparentTarget)
3474 {
3475 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3476 it->mpTarget);
3477 it->mpTarget->i_removeBackReference(machineId, snapshotId);
3478 }
3479 else
3480 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3481 it->mpSource);
3482 pSnapMachine->mMediumAttachments->remove(pAtt);
3483
3484 if (fReparentTarget)
3485 {
3486 // Search for old source attachment and replace with target.
3487 // There can be only one child snapshot in this case.
3488 ComObjPtr<Machine> pMachine = this;
3489 Guid childSnapshotId;
3490 ComObjPtr<Snapshot> pChildSnapshot = task.m_pSnapshot->i_getFirstChild();
3491 if (pChildSnapshot)
3492 {
3493 pMachine = pChildSnapshot->i_getSnapshotMachine();
3494 childSnapshotId = pChildSnapshot->i_getId();
3495 }
3496 pAtt = i_findAttachment(*(pMachine->mMediumAttachments).data(), it->mpSource);
3497 if (pAtt)
3498 {
3499 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
3500 pAtt->i_updateMedium(it->mpTarget);
3501 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3502 }
3503 else
3504 {
3505 // If no attachment is found do not change anything. Maybe
3506 // the source medium was not attached to the snapshot.
3507 // If this is an online deletion the attachment was updated
3508 // already to allow the VM continue execution immediately.
3509 // Needs a bit of special treatment due to this difference.
3510 if (it->mfNeedsOnlineMerge)
3511 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3512 }
3513 }
3514
3515 if (fNeedSourceUninit)
3516 {
3517 // make sure that the diff image to be deleted has no parent,
3518 // even in error cases (where the deparenting may be missing)
3519 if (it->mpSource->i_getParent())
3520 it->mpSource->i_deparent();
3521 it->mpSource->uninit();
3522 }
3523
3524 // One attachment is merged, must save the settings
3525 mParent->i_markRegistryModified(i_getId());
3526
3527 // prevent calling cancelDeleteSnapshotMedium() for this attachment
3528 it = toDelete.erase(it);
3529
3530 // Delayed failure exit when the merge cleanup failed but the
3531 // merge actually succeeded.
3532 if (FAILED(rc))
3533 throw rc;
3534 }
3535
3536 /* 3a: delete NVRAM file if present. */
3537 {
3538 Utf8Str NVRAMPath = pSnapMachine->mNvramStore->i_getNonVolatileStorageFile();
3539 if (NVRAMPath.isNotEmpty() && RTFileExists(NVRAMPath.c_str()))
3540 RTFileDelete(NVRAMPath.c_str());
3541 }
3542
3543 /* third pass: */
3544 {
3545 // beginSnapshotDelete() needs the machine lock, and the snapshots
3546 // tree is protected by the machine lock as well
3547 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
3548
3549 task.m_pSnapshot->i_beginSnapshotDelete();
3550 task.m_pSnapshot->uninit();
3551
3552 machineLock.release();
3553 mParent->i_markRegistryModified(i_getId());
3554 }
3555 }
3556 catch (HRESULT aRC) {
3557 mrc = aRC;
3558 }
3559
3560 if (FAILED(mrc))
3561 {
3562 // preserve existing error info so that the result can
3563 // be properly reported to the progress object below
3564 ErrorInfoKeeper eik;
3565
3566 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
3567 &mParent->i_getMediaTreeLockHandle() // media tree
3568 COMMA_LOCKVAL_SRC_POS);
3569
3570 // un-prepare the remaining hard disks
3571 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
3572 it != toDelete.end();
3573 ++it)
3574 i_cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
3575 it->mpChildrenToReparent,
3576 it->mfNeedsOnlineMerge,
3577 it->mpMediumLockList, it->mpHDLockToken,
3578 it->mMachineId, it->mSnapshotId);
3579 }
3580
3581 // whether we were successful or not, we need to set the machine
3582 // state and save the machine settings;
3583 {
3584 // preserve existing error info so that the result can
3585 // be properly reported to the progress object below
3586 ErrorInfoKeeper eik;
3587
3588 // restore the machine state that was saved when the
3589 // task was started
3590 i_setMachineState(task.m_machineStateBackup);
3591 if (Global::IsOnline(mData->mMachineState))
3592 i_updateMachineStateOnClient();
3593
3594 mParent->i_saveModifiedRegistries();
3595 }
3596
3597 // report the result (this will try to fetch current error info on failure)
3598 task.m_pProgress->i_notifyComplete(mrc);
3599
3600 if (SUCCEEDED(mrc))
3601 {
3602 mParent->i_onSnapshotDeleted(mData->mUuid, snapshotId);
3603 for (std::map<Guid, DeviceType_T>::const_iterator it = uIdsForNotify.begin();
3604 it != uIdsForNotify.end();
3605 ++it)
3606 {
3607 mParent->i_onMediumRegistered(it->first, it->second, FALSE);
3608 }
3609 for (std::set<ComObjPtr<Medium> >::const_iterator it = pMediumsForNotify.begin();
3610 it != pMediumsForNotify.end();
3611 ++it)
3612 {
3613 if (it->isNotNull())
3614 mParent->i_onMediumConfigChanged(*it);
3615 }
3616 }
3617
3618 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", (HRESULT)mrc));
3619 LogFlowThisFuncLeave();
3620}
3621
3622/**
3623 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
3624 * performs necessary state changes. Must not be called for writethrough disks
3625 * because there is nothing to delete/merge then.
3626 *
3627 * This method is to be called prior to calling #deleteSnapshotMedium().
3628 * If #deleteSnapshotMedium() is not called or fails, the state modifications
3629 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
3630 *
3631 * @return COM status code
3632 * @param aHD Hard disk which is connected to the snapshot.
3633 * @param aMachineId UUID of machine this hard disk is attached to.
3634 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
3635 * be a zero UUID if no snapshot is applicable.
3636 * @param fOnlineMergePossible Flag whether an online merge is possible.
3637 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
3638 * Only used if @a fOnlineMergePossible is @c true, and
3639 * must be non-NULL in this case.
3640 * @param aSource Source hard disk for merge (out).
3641 * @param aTarget Target hard disk for merge (out).
3642 * @param aMergeForward Merge direction decision (out).
3643 * @param aParentForTarget New parent if target needs to be reparented (out).
3644 * @param aChildrenToReparent MediumLockList with children which have to be
3645 * reparented to the target (out).
3646 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
3647 * If this is set to @a true then the @a aVMMALockList
3648 * parameter has been modified and is returned as
3649 * @a aMediumLockList.
3650 * @param aMediumLockList Where to store the created medium lock list (may
3651 * return NULL if no real merge is necessary).
3652 * @param aHDLockToken Where to store the write lock token for aHD, in case
3653 * it is not merged or deleted (out).
3654 *
3655 * @note Caller must hold media tree lock for writing. This locks this object
3656 * and every medium object on the merge chain for writing.
3657 */
3658HRESULT SessionMachine::i_prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3659 const Guid &aMachineId,
3660 const Guid &aSnapshotId,
3661 bool fOnlineMergePossible,
3662 MediumLockList *aVMMALockList,
3663 ComObjPtr<Medium> &aSource,
3664 ComObjPtr<Medium> &aTarget,
3665 bool &aMergeForward,
3666 ComObjPtr<Medium> &aParentForTarget,
3667 MediumLockList * &aChildrenToReparent,
3668 bool &fNeedsOnlineMerge,
3669 MediumLockList * &aMediumLockList,
3670 ComPtr<IToken> &aHDLockToken)
3671{
3672 Assert(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3673 Assert(!fOnlineMergePossible || RT_VALID_PTR(aVMMALockList));
3674
3675 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
3676
3677 // Medium must not be writethrough/shareable/readonly at this point
3678 MediumType_T type = aHD->i_getType();
3679 AssertReturn( type != MediumType_Writethrough
3680 && type != MediumType_Shareable
3681 && type != MediumType_Readonly, E_FAIL);
3682
3683 aChildrenToReparent = NULL;
3684 aMediumLockList = NULL;
3685 fNeedsOnlineMerge = false;
3686
3687 if (aHD->i_getChildren().size() == 0)
3688 {
3689 /* This technically is no merge, set those values nevertheless.
3690 * Helps with updating the medium attachments. */
3691 aSource = aHD;
3692 aTarget = aHD;
3693
3694 /* special treatment of the last hard disk in the chain: */
3695 if (aHD->i_getParent().isNull())
3696 {
3697 /* lock only, to prevent any usage until the snapshot deletion
3698 * is completed */
3699 alock.release();
3700 return aHD->LockWrite(aHDLockToken.asOutParam());
3701 }
3702
3703 /* the differencing hard disk w/o children will be deleted, protect it
3704 * from attaching to other VMs (this is why Deleting) */
3705 return aHD->i_markForDeletion();
3706 }
3707
3708 /* not going multi-merge as it's too expensive */
3709 if (aHD->i_getChildren().size() > 1)
3710 return setError(E_FAIL,
3711 tr("Hard disk '%s' has more than one child hard disk (%d)"),
3712 aHD->i_getLocationFull().c_str(),
3713 aHD->i_getChildren().size());
3714
3715 ComObjPtr<Medium> pChild = aHD->i_getChildren().front();
3716
3717 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
3718
3719 /* the rest is a normal merge setup */
3720 if (aHD->i_getParent().isNull())
3721 {
3722 /* base hard disk, backward merge */
3723 const Guid *pMachineId1 = pChild->i_getFirstMachineBackrefId();
3724 const Guid *pMachineId2 = aHD->i_getFirstMachineBackrefId();
3725 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
3726 {
3727 /* backward merge is too tricky, we'll just detach on snapshot
3728 * deletion, so lock only, to prevent any usage */
3729 childLock.release();
3730 alock.release();
3731 return aHD->LockWrite(aHDLockToken.asOutParam());
3732 }
3733
3734 aSource = pChild;
3735 aTarget = aHD;
3736 }
3737 else
3738 {
3739 /* Determine best merge direction. */
3740 bool fMergeForward = true;
3741
3742 childLock.release();
3743 alock.release();
3744 HRESULT rc = aHD->i_queryPreferredMergeDirection(pChild, fMergeForward);
3745 alock.acquire();
3746 childLock.acquire();
3747
3748 if (FAILED(rc) && rc != E_FAIL)
3749 return rc;
3750
3751 if (fMergeForward)
3752 {
3753 aSource = aHD;
3754 aTarget = pChild;
3755 LogFlowThisFunc(("Forward merging selected\n"));
3756 }
3757 else
3758 {
3759 aSource = pChild;
3760 aTarget = aHD;
3761 LogFlowThisFunc(("Backward merging selected\n"));
3762 }
3763 }
3764
3765 HRESULT rc;
3766 childLock.release();
3767 alock.release();
3768 rc = aSource->i_prepareMergeTo(aTarget, &aMachineId, &aSnapshotId,
3769 !fOnlineMergePossible /* fLockMedia */,
3770 aMergeForward, aParentForTarget,
3771 aChildrenToReparent, aMediumLockList);
3772 alock.acquire();
3773 childLock.acquire();
3774 if (SUCCEEDED(rc) && fOnlineMergePossible)
3775 {
3776 /* Try to lock the newly constructed medium lock list. If it succeeds
3777 * this can be handled as an offline merge, i.e. without the need of
3778 * asking the VM to do the merging. Only continue with the online
3779 * merging preparation if applicable. */
3780 childLock.release();
3781 alock.release();
3782 rc = aMediumLockList->Lock();
3783 alock.acquire();
3784 childLock.acquire();
3785 if (FAILED(rc))
3786 {
3787 /* Locking failed, this cannot be done as an offline merge. Try to
3788 * combine the locking information into the lock list of the medium
3789 * attachment in the running VM. If that fails or locking the
3790 * resulting lock list fails then the merge cannot be done online.
3791 * It can be repeated by the user when the VM is shut down. */
3792 MediumLockList::Base::iterator lockListVMMABegin =
3793 aVMMALockList->GetBegin();
3794 MediumLockList::Base::iterator lockListVMMAEnd =
3795 aVMMALockList->GetEnd();
3796 MediumLockList::Base::iterator lockListBegin =
3797 aMediumLockList->GetBegin();
3798 MediumLockList::Base::iterator lockListEnd =
3799 aMediumLockList->GetEnd();
3800 for (MediumLockList::Base::iterator it = lockListVMMABegin,
3801 it2 = lockListBegin;
3802 it2 != lockListEnd;
3803 ++it, ++it2)
3804 {
3805 if ( it == lockListVMMAEnd
3806 || it->GetMedium() != it2->GetMedium())
3807 {
3808 fOnlineMergePossible = false;
3809 break;
3810 }
3811 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
3812 childLock.release();
3813 alock.release();
3814 rc = it->UpdateLock(fLockReq);
3815 alock.acquire();
3816 childLock.acquire();
3817 if (FAILED(rc))
3818 {
3819 // could not update the lock, trigger cleanup below
3820 fOnlineMergePossible = false;
3821 break;
3822 }
3823 }
3824
3825 if (fOnlineMergePossible)
3826 {
3827 /* we will lock the children of the source for reparenting */
3828 if (aChildrenToReparent && !aChildrenToReparent->IsEmpty())
3829 {
3830 /* Cannot just call aChildrenToReparent->Lock(), as one of
3831 * the children is the one under which the current state of
3832 * the VM is located, and this means it is already locked
3833 * (for reading). Note that no special unlocking is needed,
3834 * because cancelMergeTo will unlock everything locked in
3835 * its context (using the unlock on destruction), and both
3836 * cancelDeleteSnapshotMedium (in case something fails) and
3837 * FinishOnlineMergeMedium re-define the read/write lock
3838 * state of everything which the VM need, search for the
3839 * UpdateLock method calls. */
3840 childLock.release();
3841 alock.release();
3842 rc = aChildrenToReparent->Lock(true /* fSkipOverLockedMedia */);
3843 alock.acquire();
3844 childLock.acquire();
3845 MediumLockList::Base::iterator childrenToReparentBegin = aChildrenToReparent->GetBegin();
3846 MediumLockList::Base::iterator childrenToReparentEnd = aChildrenToReparent->GetEnd();
3847 for (MediumLockList::Base::iterator it = childrenToReparentBegin;
3848 it != childrenToReparentEnd;
3849 ++it)
3850 {
3851 ComObjPtr<Medium> pMedium = it->GetMedium();
3852 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3853 if (!it->IsLocked())
3854 {
3855 mediumLock.release();
3856 childLock.release();
3857 alock.release();
3858 rc = aVMMALockList->Update(pMedium, true);
3859 alock.acquire();
3860 childLock.acquire();
3861 mediumLock.acquire();
3862 if (FAILED(rc))
3863 throw rc;
3864 }
3865 }
3866 }
3867 }
3868
3869 if (fOnlineMergePossible)
3870 {
3871 childLock.release();
3872 alock.release();
3873 rc = aVMMALockList->Lock();
3874 alock.acquire();
3875 childLock.acquire();
3876 if (FAILED(rc))
3877 {
3878 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3879 rc = setError(rc,
3880 tr("Cannot lock hard disk '%s' for a live merge"),
3881 aHD->i_getLocationFull().c_str());
3882 }
3883 else
3884 {
3885 delete aMediumLockList;
3886 aMediumLockList = aVMMALockList;
3887 fNeedsOnlineMerge = true;
3888 }
3889 }
3890 else
3891 {
3892 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3893 rc = setError(rc,
3894 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
3895 aHD->i_getLocationFull().c_str());
3896 }
3897
3898 // fix the VM's lock list if anything failed
3899 if (FAILED(rc))
3900 {
3901 lockListVMMABegin = aVMMALockList->GetBegin();
3902 lockListVMMAEnd = aVMMALockList->GetEnd();
3903 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
3904 --lockListLast;
3905 for (MediumLockList::Base::iterator it = lockListVMMABegin;
3906 it != lockListVMMAEnd;
3907 ++it)
3908 {
3909 childLock.release();
3910 alock.release();
3911 it->UpdateLock(it == lockListLast);
3912 alock.acquire();
3913 childLock.acquire();
3914 ComObjPtr<Medium> pMedium = it->GetMedium();
3915 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3916 // blindly apply this, only needed for medium objects which
3917 // would be deleted as part of the merge
3918 pMedium->i_unmarkLockedForDeletion();
3919 }
3920 }
3921 }
3922 }
3923 else if (FAILED(rc))
3924 {
3925 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3926 rc = setError(rc,
3927 tr("Cannot lock hard disk '%s' when deleting a snapshot"),
3928 aHD->i_getLocationFull().c_str());
3929 }
3930
3931 return rc;
3932}
3933
3934/**
3935 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
3936 * what #prepareDeleteSnapshotMedium() did. Must be called if
3937 * #deleteSnapshotMedium() is not called or fails.
3938 *
3939 * @param aHD Hard disk which is connected to the snapshot.
3940 * @param aSource Source hard disk for merge.
3941 * @param aChildrenToReparent Children to unlock.
3942 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
3943 * @param aMediumLockList Medium locks to cancel.
3944 * @param aHDLockToken Optional write lock token for aHD.
3945 * @param aMachineId Machine id to attach the medium to.
3946 * @param aSnapshotId Snapshot id to attach the medium to.
3947 *
3948 * @note Locks the medium tree and the hard disks in the chain for writing.
3949 */
3950void SessionMachine::i_cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3951 const ComObjPtr<Medium> &aSource,
3952 MediumLockList *aChildrenToReparent,
3953 bool fNeedsOnlineMerge,
3954 MediumLockList *aMediumLockList,
3955 const ComPtr<IToken> &aHDLockToken,
3956 const Guid &aMachineId,
3957 const Guid &aSnapshotId)
3958{
3959 if (aMediumLockList == NULL)
3960 {
3961 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
3962
3963 Assert(aHD->i_getChildren().size() == 0);
3964
3965 if (aHD->i_getParent().isNull())
3966 {
3967 Assert(!aHDLockToken.isNull());
3968 if (!aHDLockToken.isNull())
3969 {
3970 HRESULT rc = aHDLockToken->Abandon();
3971 AssertComRC(rc);
3972 }
3973 }
3974 else
3975 {
3976 HRESULT rc = aHD->i_unmarkForDeletion();
3977 AssertComRC(rc);
3978 }
3979 }
3980 else
3981 {
3982 if (fNeedsOnlineMerge)
3983 {
3984 // Online merge uses the medium lock list of the VM, so give
3985 // an empty list to cancelMergeTo so that it works as designed.
3986 aSource->i_cancelMergeTo(aChildrenToReparent, new MediumLockList());
3987
3988 // clean up the VM medium lock list ourselves
3989 MediumLockList::Base::iterator lockListBegin =
3990 aMediumLockList->GetBegin();
3991 MediumLockList::Base::iterator lockListEnd =
3992 aMediumLockList->GetEnd();
3993 MediumLockList::Base::iterator lockListLast = lockListEnd;
3994 --lockListLast;
3995 for (MediumLockList::Base::iterator it = lockListBegin;
3996 it != lockListEnd;
3997 ++it)
3998 {
3999 ComObjPtr<Medium> pMedium = it->GetMedium();
4000 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
4001 if (pMedium->i_getState() == MediumState_Deleting)
4002 pMedium->i_unmarkForDeletion();
4003 else
4004 {
4005 // blindly apply this, only needed for medium objects which
4006 // would be deleted as part of the merge
4007 pMedium->i_unmarkLockedForDeletion();
4008 }
4009 mediumLock.release();
4010 it->UpdateLock(it == lockListLast);
4011 mediumLock.acquire();
4012 }
4013 }
4014 else
4015 {
4016 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
4017 }
4018 }
4019
4020 if (aMachineId.isValid() && !aMachineId.isZero())
4021 {
4022 // reattach the source media to the snapshot
4023 HRESULT rc = aSource->i_addBackReference(aMachineId, aSnapshotId);
4024 AssertComRC(rc);
4025 }
4026}
4027
4028/**
4029 * Perform an online merge of a hard disk, i.e. the equivalent of
4030 * Medium::mergeTo(), just for running VMs. If this fails you need to call
4031 * #cancelDeleteSnapshotMedium().
4032 *
4033 * @return COM status code
4034 * @param aMediumAttachment Identify where the disk is attached in the VM.
4035 * @param aSource Source hard disk for merge.
4036 * @param aTarget Target hard disk for merge.
4037 * @param fMergeForward Merge direction.
4038 * @param aParentForTarget New parent if target needs to be reparented.
4039 * @param aChildrenToReparent Medium lock list with children which have to be
4040 * reparented to the target.
4041 * @param aMediumLockList Where to store the created medium lock list (may
4042 * return NULL if no real merge is necessary).
4043 * @param aProgress Progress indicator.
4044 * @param pfNeedsMachineSaveSettings Whether the VM settings need to be saved (out).
4045 */
4046HRESULT SessionMachine::i_onlineMergeMedium(const ComObjPtr<MediumAttachment> &aMediumAttachment,
4047 const ComObjPtr<Medium> &aSource,
4048 const ComObjPtr<Medium> &aTarget,
4049 bool fMergeForward,
4050 const ComObjPtr<Medium> &aParentForTarget,
4051 MediumLockList *aChildrenToReparent,
4052 MediumLockList *aMediumLockList,
4053 ComObjPtr<Progress> &aProgress,
4054 bool *pfNeedsMachineSaveSettings)
4055{
4056 AssertReturn(aSource != NULL, E_FAIL);
4057 AssertReturn(aTarget != NULL, E_FAIL);
4058 AssertReturn(aSource != aTarget, E_FAIL);
4059 AssertReturn(aMediumLockList != NULL, E_FAIL);
4060 NOREF(fMergeForward);
4061 NOREF(aParentForTarget);
4062 NOREF(aChildrenToReparent);
4063
4064 HRESULT rc = S_OK;
4065
4066 try
4067 {
4068 // Similar code appears in Medium::taskMergeHandle, so
4069 // if you make any changes below check whether they are applicable
4070 // in that context as well.
4071
4072 unsigned uTargetIdx = (unsigned)-1;
4073 unsigned uSourceIdx = (unsigned)-1;
4074 /* Sanity check all hard disks in the chain. */
4075 MediumLockList::Base::iterator lockListBegin =
4076 aMediumLockList->GetBegin();
4077 MediumLockList::Base::iterator lockListEnd =
4078 aMediumLockList->GetEnd();
4079 unsigned i = 0;
4080 for (MediumLockList::Base::iterator it = lockListBegin;
4081 it != lockListEnd;
4082 ++it)
4083 {
4084 MediumLock &mediumLock = *it;
4085 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4086
4087 if (pMedium == aSource)
4088 uSourceIdx = i;
4089 else if (pMedium == aTarget)
4090 uTargetIdx = i;
4091
4092 // In Medium::taskMergeHandler there is lots of consistency
4093 // checking which we cannot do here, as the state details are
4094 // impossible to get outside the Medium class. The locking should
4095 // have done the checks already.
4096
4097 i++;
4098 }
4099
4100 ComAssertThrow( uSourceIdx != (unsigned)-1
4101 && uTargetIdx != (unsigned)-1, E_FAIL);
4102
4103 ComPtr<IInternalSessionControl> directControl;
4104 {
4105 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4106
4107 if (mData->mSession.mState != SessionState_Locked)
4108 throw setError(VBOX_E_INVALID_VM_STATE,
4109 tr("Machine is not locked by a session (session state: %s)"),
4110 Global::stringifySessionState(mData->mSession.mState));
4111 directControl = mData->mSession.mDirectControl;
4112 }
4113
4114 // Must not hold any locks here, as this will call back to finish
4115 // updating the medium attachment, chain linking and state.
4116 rc = directControl->OnlineMergeMedium(aMediumAttachment,
4117 uSourceIdx, uTargetIdx,
4118 aProgress);
4119 if (FAILED(rc))
4120 throw rc;
4121 }
4122 catch (HRESULT aRC) { rc = aRC; }
4123
4124 // The callback mentioned above takes care of update the medium state
4125
4126 if (pfNeedsMachineSaveSettings)
4127 *pfNeedsMachineSaveSettings = true;
4128
4129 return rc;
4130}
4131
4132/**
4133 * Implementation for IInternalMachineControl::finishOnlineMergeMedium().
4134 *
4135 * Gets called after the successful completion of an online merge from
4136 * Console::onlineMergeMedium(), which gets invoked indirectly above in
4137 * the call to IInternalSessionControl::onlineMergeMedium.
4138 *
4139 * This updates the medium information and medium state so that the VM
4140 * can continue with the updated state of the medium chain.
4141 */
4142HRESULT SessionMachine::finishOnlineMergeMedium()
4143{
4144 HRESULT rc = S_OK;
4145 MediumDeleteRec *pDeleteRec = (MediumDeleteRec *)mConsoleTaskData.mDeleteSnapshotInfo;
4146 AssertReturn(pDeleteRec, E_FAIL);
4147 bool fSourceHasChildren = false;
4148
4149 // all hard disks but the target were successfully deleted by
4150 // the merge; reparent target if necessary and uninitialize media
4151
4152 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4153
4154 // Declare this here to make sure the object does not get uninitialized
4155 // before this method completes. Would normally happen as halfway through
4156 // we delete the last reference to the no longer existing medium object.
4157 ComObjPtr<Medium> targetChild;
4158
4159 if (pDeleteRec->mfMergeForward)
4160 {
4161 // first, unregister the target since it may become a base
4162 // hard disk which needs re-registration
4163 rc = mParent->i_unregisterMedium(pDeleteRec->mpTarget);
4164 AssertComRC(rc);
4165
4166 // then, reparent it and disconnect the deleted branch at
4167 // both ends (chain->parent() is source's parent)
4168 pDeleteRec->mpTarget->i_deparent();
4169 pDeleteRec->mpTarget->i_setParent(pDeleteRec->mpParentForTarget);
4170 if (pDeleteRec->mpParentForTarget)
4171 pDeleteRec->mpSource->i_deparent();
4172
4173 // then, register again
4174 rc = mParent->i_registerMedium(pDeleteRec->mpTarget, &pDeleteRec->mpTarget, treeLock);
4175 AssertComRC(rc);
4176 }
4177 else
4178 {
4179 Assert(pDeleteRec->mpTarget->i_getChildren().size() == 1);
4180 targetChild = pDeleteRec->mpTarget->i_getChildren().front();
4181
4182 // disconnect the deleted branch at the elder end
4183 targetChild->i_deparent();
4184
4185 // Update parent UUIDs of the source's children, reparent them and
4186 // disconnect the deleted branch at the younger end
4187 if (pDeleteRec->mpChildrenToReparent && !pDeleteRec->mpChildrenToReparent->IsEmpty())
4188 {
4189 fSourceHasChildren = true;
4190 // Fix the parent UUID of the images which needs to be moved to
4191 // underneath target. The running machine has the images opened,
4192 // but only for reading since the VM is paused. If anything fails
4193 // we must continue. The worst possible result is that the images
4194 // need manual fixing via VBoxManage to adjust the parent UUID.
4195 treeLock.release();
4196 pDeleteRec->mpTarget->i_fixParentUuidOfChildren(pDeleteRec->mpChildrenToReparent);
4197 // The childen are still write locked, unlock them now and don't
4198 // rely on the destructor doing it very late.
4199 pDeleteRec->mpChildrenToReparent->Unlock();
4200 treeLock.acquire();
4201
4202 // obey {parent,child} lock order
4203 AutoWriteLock sourceLock(pDeleteRec->mpSource COMMA_LOCKVAL_SRC_POS);
4204
4205 MediumLockList::Base::iterator childrenBegin = pDeleteRec->mpChildrenToReparent->GetBegin();
4206 MediumLockList::Base::iterator childrenEnd = pDeleteRec->mpChildrenToReparent->GetEnd();
4207 for (MediumLockList::Base::iterator it = childrenBegin;
4208 it != childrenEnd;
4209 ++it)
4210 {
4211 Medium *pMedium = it->GetMedium();
4212 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
4213
4214 pMedium->i_deparent(); // removes pMedium from source
4215 pMedium->i_setParent(pDeleteRec->mpTarget);
4216 }
4217 }
4218 }
4219
4220 /* unregister and uninitialize all hard disks removed by the merge */
4221 MediumLockList *pMediumLockList = NULL;
4222 rc = mData->mSession.mLockedMedia.Get(pDeleteRec->mpOnlineMediumAttachment, pMediumLockList);
4223 const ComObjPtr<Medium> &pLast = pDeleteRec->mfMergeForward ? pDeleteRec->mpTarget : pDeleteRec->mpSource;
4224 AssertReturn(SUCCEEDED(rc) && pMediumLockList, E_FAIL);
4225 MediumLockList::Base::iterator lockListBegin =
4226 pMediumLockList->GetBegin();
4227 MediumLockList::Base::iterator lockListEnd =
4228 pMediumLockList->GetEnd();
4229 for (MediumLockList::Base::iterator it = lockListBegin;
4230 it != lockListEnd;
4231 )
4232 {
4233 MediumLock &mediumLock = *it;
4234 /* Create a real copy of the medium pointer, as the medium
4235 * lock deletion below would invalidate the referenced object. */
4236 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
4237
4238 /* The target and all images not merged (readonly) are skipped */
4239 if ( pMedium == pDeleteRec->mpTarget
4240 || pMedium->i_getState() == MediumState_LockedRead)
4241 {
4242 ++it;
4243 }
4244 else
4245 {
4246 rc = mParent->i_unregisterMedium(pMedium);
4247 AssertComRC(rc);
4248
4249 /* now, uninitialize the deleted hard disk (note that
4250 * due to the Deleting state, uninit() will not touch
4251 * the parent-child relationship so we need to
4252 * uninitialize each disk individually) */
4253
4254 /* note that the operation initiator hard disk (which is
4255 * normally also the source hard disk) is a special case
4256 * -- there is one more caller added by Task to it which
4257 * we must release. Also, if we are in sync mode, the
4258 * caller may still hold an AutoCaller instance for it
4259 * and therefore we cannot uninit() it (it's therefore
4260 * the caller's responsibility) */
4261 if (pMedium == pDeleteRec->mpSource)
4262 {
4263 Assert(pDeleteRec->mpSource->i_getChildren().size() == 0);
4264 Assert(pDeleteRec->mpSource->i_getFirstMachineBackrefId() == NULL);
4265 }
4266
4267 /* Delete the medium lock list entry, which also releases the
4268 * caller added by MergeChain before uninit() and updates the
4269 * iterator to point to the right place. */
4270 rc = pMediumLockList->RemoveByIterator(it);
4271 AssertComRC(rc);
4272
4273 treeLock.release();
4274 pMedium->uninit();
4275 treeLock.acquire();
4276 }
4277
4278 /* Stop as soon as we reached the last medium affected by the merge.
4279 * The remaining images must be kept unchanged. */
4280 if (pMedium == pLast)
4281 break;
4282 }
4283
4284 /* Could be in principle folded into the previous loop, but let's keep
4285 * things simple. Update the medium locking to be the standard state:
4286 * all parent images locked for reading, just the last diff for writing. */
4287 lockListBegin = pMediumLockList->GetBegin();
4288 lockListEnd = pMediumLockList->GetEnd();
4289 MediumLockList::Base::iterator lockListLast = lockListEnd;
4290 --lockListLast;
4291 for (MediumLockList::Base::iterator it = lockListBegin;
4292 it != lockListEnd;
4293 ++it)
4294 {
4295 it->UpdateLock(it == lockListLast);
4296 }
4297
4298 /* If this is a backwards merge of the only remaining snapshot (i.e. the
4299 * source has no children) then update the medium associated with the
4300 * attachment, as the previously associated one (source) is now deleted.
4301 * Without the immediate update the VM could not continue running. */
4302 if (!pDeleteRec->mfMergeForward && !fSourceHasChildren)
4303 {
4304 AutoWriteLock attLock(pDeleteRec->mpOnlineMediumAttachment COMMA_LOCKVAL_SRC_POS);
4305 pDeleteRec->mpOnlineMediumAttachment->i_updateMedium(pDeleteRec->mpTarget);
4306 }
4307
4308 return S_OK;
4309}
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