VirtualBox

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

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

Main/Machine: Release lock while waiting in Machine::i_ensureNoStateDependencies. Needs passing the lock from the caller (and a bit of multiple lock untangling). Regression introduced in r76471. bugref:10121

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

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