VirtualBox

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

Last change on this file since 91213 was 91213, checked in by vboxsync, 4 years ago

Main,FE/VBoxManage: Add the necessary Main API bits to control the trusted platform module settings as well as implementing support in VBoxManage, bugref:10075

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 159.2 KB
Line 
1/* $Id: SnapshotImpl.cpp 91213 2021-09-10 17:58:08Z 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.215389.xyz. 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->mBIOSSettings->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->mBIOSSettings->i_updateNonVolatileStorageFile(Utf8StrFmt("%s%s",
760 strNewPath.c_str(),
761 path.c_str() + strOldPath.length()));
762 LogFlowThisFunc(("-> updated: {%s}\n", m->pMachine->mBIOSSettings->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->mBIOSSettings->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(mRecordingSettings).createObject();
1156 rc = mRecordingSettings->initCopy(this, pMachine->mRecordingSettings);
1157 if (FAILED(rc)) return rc;
1158
1159 unconst(mGraphicsAdapter).createObject();
1160 rc = mGraphicsAdapter->initCopy(this, pMachine->mGraphicsAdapter);
1161 if (FAILED(rc)) return rc;
1162
1163 unconst(mVRDEServer).createObject();
1164 rc = mVRDEServer->initCopy(this, pMachine->mVRDEServer);
1165 if (FAILED(rc)) return rc;
1166
1167 unconst(mAudioAdapter).createObject();
1168 rc = mAudioAdapter->initCopy(this, pMachine->mAudioAdapter);
1169 if (FAILED(rc)) return rc;
1170
1171 /* create copies of all USB controllers (mUSBControllerData
1172 * after attaching a copy contains just references to original objects) */
1173 mUSBControllers.allocate();
1174 for (USBControllerList::const_iterator
1175 it = aSessionMachine->mUSBControllers->begin();
1176 it != aSessionMachine->mUSBControllers->end();
1177 ++it)
1178 {
1179 ComObjPtr<USBController> ctrl;
1180 ctrl.createObject();
1181 rc = ctrl->initCopy(this, *it);
1182 if (FAILED(rc)) return rc;
1183 mUSBControllers->push_back(ctrl);
1184 }
1185
1186 unconst(mUSBDeviceFilters).createObject();
1187 rc = mUSBDeviceFilters->initCopy(this, pMachine->mUSBDeviceFilters);
1188 if (FAILED(rc)) return rc;
1189
1190 mNetworkAdapters.resize(pMachine->mNetworkAdapters.size());
1191 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
1192 {
1193 unconst(mNetworkAdapters[slot]).createObject();
1194 rc = mNetworkAdapters[slot]->initCopy(this, pMachine->mNetworkAdapters[slot]);
1195 if (FAILED(rc)) return rc;
1196 }
1197
1198 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
1199 {
1200 unconst(mSerialPorts[slot]).createObject();
1201 rc = mSerialPorts[slot]->initCopy(this, pMachine->mSerialPorts[slot]);
1202 if (FAILED(rc)) return rc;
1203 }
1204
1205 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
1206 {
1207 unconst(mParallelPorts[slot]).createObject();
1208 rc = mParallelPorts[slot]->initCopy(this, pMachine->mParallelPorts[slot]);
1209 if (FAILED(rc)) return rc;
1210 }
1211
1212 unconst(mBandwidthControl).createObject();
1213 rc = mBandwidthControl->initCopy(this, pMachine->mBandwidthControl);
1214 if (FAILED(rc)) return rc;
1215
1216 /* Confirm a successful initialization when it's the case */
1217 autoInitSpan.setSucceeded();
1218
1219 LogFlowThisFuncLeave();
1220 return S_OK;
1221}
1222
1223/**
1224 * Initializes the SnapshotMachine object when loading from the settings file.
1225 *
1226 * @param aMachine machine the snapshot belongs to
1227 * @param hardware hardware settings
1228 * @param pDbg debuging settings
1229 * @param pAutostart autostart settings
1230 * @param aSnapshotId snapshot ID of this snapshot machine
1231 * @param aStateFilePath file where the execution state is saved
1232 * (or NULL for the offline snapshot)
1233 *
1234 * @note Doesn't lock anything.
1235 */
1236HRESULT SnapshotMachine::initFromSettings(Machine *aMachine,
1237 const settings::Hardware &hardware,
1238 const settings::Debugging *pDbg,
1239 const settings::Autostart *pAutostart,
1240 IN_GUID aSnapshotId,
1241 const Utf8Str &aStateFilePath)
1242{
1243 LogFlowThisFuncEnter();
1244 LogFlowThisFunc(("mName={%s}\n", aMachine->mUserData->s.strName.c_str()));
1245
1246 Guid l_guid(aSnapshotId);
1247 AssertReturn(aMachine && (!l_guid.isZero() && l_guid.isValid()), E_INVALIDARG);
1248
1249 /* Enclose the state transition NotReady->InInit->Ready */
1250 AutoInitSpan autoInitSpan(this);
1251 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1252
1253 /* Don't need to lock aMachine when VirtualBox is starting up */
1254
1255 mSnapshotId = aSnapshotId;
1256
1257 /* mPeer stays NULL */
1258 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
1259 unconst(mMachine) = aMachine;
1260 /* share the parent pointer */
1261 unconst(mParent) = aMachine->mParent;
1262
1263 /* take the pointer to Data to share */
1264 mData.share(aMachine->mData);
1265 /*
1266 * take the pointer to UserData to share
1267 * (our UserData must always be the same as Machine's data)
1268 */
1269 mUserData.share(aMachine->mUserData);
1270 /* allocate private copies of all other data (will be loaded from settings) */
1271 mHWData.allocate();
1272 mMediumAttachments.allocate();
1273 mStorageControllers.allocate();
1274 mUSBControllers.allocate();
1275
1276 /* SSData is always unique for SnapshotMachine */
1277 mSSData.allocate();
1278 mSSData->strStateFilePath = aStateFilePath;
1279
1280 /* create all other child objects that will be immutable private copies */
1281
1282 unconst(mBIOSSettings).createObject();
1283 mBIOSSettings->init(this);
1284
1285 unconst(mTrustedPlatformModule).createObject();
1286 mTrustedPlatformModule->init(this);
1287
1288 unconst(mRecordingSettings).createObject();
1289 mRecordingSettings->init(this);
1290
1291 unconst(mGraphicsAdapter).createObject();
1292 mGraphicsAdapter->init(this);
1293
1294 unconst(mVRDEServer).createObject();
1295 mVRDEServer->init(this);
1296
1297 unconst(mAudioAdapter).createObject();
1298 mAudioAdapter->init(this);
1299
1300 unconst(mUSBDeviceFilters).createObject();
1301 mUSBDeviceFilters->init(this);
1302
1303 mNetworkAdapters.resize(Global::getMaxNetworkAdapters(mHWData->mChipsetType));
1304 for (ULONG slot = 0; slot < mNetworkAdapters.size(); slot++)
1305 {
1306 unconst(mNetworkAdapters[slot]).createObject();
1307 mNetworkAdapters[slot]->init(this, slot);
1308 }
1309
1310 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
1311 {
1312 unconst(mSerialPorts[slot]).createObject();
1313 mSerialPorts[slot]->init(this, slot);
1314 }
1315
1316 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
1317 {
1318 unconst(mParallelPorts[slot]).createObject();
1319 mParallelPorts[slot]->init(this, slot);
1320 }
1321
1322 unconst(mBandwidthControl).createObject();
1323 mBandwidthControl->init(this);
1324
1325 /* load hardware and storage settings */
1326 HRESULT rc = i_loadHardware(NULL, &mSnapshotId, hardware, pDbg, pAutostart);
1327
1328 if (SUCCEEDED(rc))
1329 /* commit all changes made during the initialization */
1330 i_commit(); /// @todo r=dj why do we need a commit in init?!? this is very expensive
1331 /// @todo r=klaus for some reason the settings loading logic backs up
1332 // the settings, and therefore a commit is needed. Should probably be changed.
1333
1334 /* Confirm a successful initialization when it's the case */
1335 if (SUCCEEDED(rc))
1336 autoInitSpan.setSucceeded();
1337
1338 LogFlowThisFuncLeave();
1339 return rc;
1340}
1341
1342/**
1343 * Uninitializes this SnapshotMachine object.
1344 */
1345void SnapshotMachine::uninit()
1346{
1347 LogFlowThisFuncEnter();
1348
1349 /* Enclose the state transition Ready->InUninit->NotReady */
1350 AutoUninitSpan autoUninitSpan(this);
1351 if (autoUninitSpan.uninitDone())
1352 return;
1353
1354 uninitDataAndChildObjects();
1355
1356 /* free the essential data structure last */
1357 mData.free();
1358
1359 unconst(mMachine) = NULL;
1360 unconst(mParent) = NULL;
1361 unconst(mPeer) = NULL;
1362
1363 LogFlowThisFuncLeave();
1364}
1365
1366/**
1367 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
1368 * with the primary Machine instance (mMachine) if it exists.
1369 */
1370RWLockHandle *SnapshotMachine::lockHandle() const
1371{
1372 AssertReturn(mMachine != NULL, NULL);
1373 return mMachine->lockHandle();
1374}
1375
1376////////////////////////////////////////////////////////////////////////////////
1377//
1378// SnapshotMachine public internal methods
1379//
1380////////////////////////////////////////////////////////////////////////////////
1381
1382/**
1383 * Called by the snapshot object associated with this SnapshotMachine when
1384 * snapshot data such as name or description is changed.
1385 *
1386 * @warning Caller must hold no locks when calling this.
1387 */
1388HRESULT SnapshotMachine::i_onSnapshotChange(Snapshot *aSnapshot)
1389{
1390 AutoMultiWriteLock2 mlock(this, aSnapshot COMMA_LOCKVAL_SRC_POS);
1391 Guid uuidMachine(mData->mUuid),
1392 uuidSnapshot(aSnapshot->i_getId());
1393 bool fNeedsGlobalSaveSettings = false;
1394
1395 /* Flag the machine as dirty or change won't get saved. We disable the
1396 * modification of the current state flag, cause this snapshot data isn't
1397 * related to the current state. */
1398 mMachine->i_setModified(Machine::IsModified_Snapshots, false /* fAllowStateModification */);
1399 HRESULT rc = mMachine->i_saveSettings(&fNeedsGlobalSaveSettings,
1400 SaveS_Force); // we know we need saving, no need to check
1401 mlock.release();
1402
1403 if (SUCCEEDED(rc) && fNeedsGlobalSaveSettings)
1404 {
1405 // save the global settings
1406 AutoWriteLock vboxlock(mParent COMMA_LOCKVAL_SRC_POS);
1407 rc = mParent->i_saveSettings();
1408 }
1409
1410 /* inform callbacks */
1411 mParent->i_onSnapshotChanged(uuidMachine, uuidSnapshot);
1412
1413 return rc;
1414}
1415
1416////////////////////////////////////////////////////////////////////////////////
1417//
1418// SessionMachine task records
1419//
1420////////////////////////////////////////////////////////////////////////////////
1421
1422/**
1423 * Still abstract base class for SessionMachine::TakeSnapshotTask,
1424 * SessionMachine::RestoreSnapshotTask and SessionMachine::DeleteSnapshotTask.
1425 */
1426class SessionMachine::SnapshotTask
1427 : public SessionMachine::Task
1428{
1429public:
1430 SnapshotTask(SessionMachine *m,
1431 Progress *p,
1432 const Utf8Str &t,
1433 Snapshot *s)
1434 : Task(m, p, t),
1435 m_pSnapshot(s)
1436 {}
1437
1438 ComObjPtr<Snapshot> m_pSnapshot;
1439};
1440
1441/** Take snapshot task */
1442class SessionMachine::TakeSnapshotTask
1443 : public SessionMachine::SnapshotTask
1444{
1445public:
1446 TakeSnapshotTask(SessionMachine *m,
1447 Progress *p,
1448 const Utf8Str &t,
1449 Snapshot *s,
1450 const Utf8Str &strName,
1451 const Utf8Str &strDescription,
1452 const Guid &uuidSnapshot,
1453 bool fPause,
1454 uint32_t uMemSize,
1455 bool fTakingSnapshotOnline)
1456 : SnapshotTask(m, p, t, s)
1457 , m_strName(strName)
1458 , m_strDescription(strDescription)
1459 , m_uuidSnapshot(uuidSnapshot)
1460 , m_fPause(fPause)
1461#if 0 /*unused*/
1462 , m_uMemSize(uMemSize)
1463#endif
1464 , m_fTakingSnapshotOnline(fTakingSnapshotOnline)
1465 {
1466 RT_NOREF(uMemSize);
1467 if (fTakingSnapshotOnline)
1468 m_pDirectControl = m->mData->mSession.mDirectControl;
1469 // If the VM is already paused then there's no point trying to pause
1470 // again during taking an (always online) snapshot.
1471 if (m_machineStateBackup == MachineState_Paused)
1472 m_fPause = false;
1473 }
1474
1475private:
1476 void handler()
1477 {
1478 try
1479 {
1480 ((SessionMachine *)(Machine *)m_pMachine)->i_takeSnapshotHandler(*this);
1481 }
1482 catch(...)
1483 {
1484 LogRel(("Some exception in the function i_takeSnapshotHandler()\n"));
1485 }
1486 }
1487
1488 Utf8Str m_strName;
1489 Utf8Str m_strDescription;
1490 Guid m_uuidSnapshot;
1491 Utf8Str m_strStateFilePath;
1492 ComPtr<IInternalSessionControl> m_pDirectControl;
1493 bool m_fPause;
1494#if 0 /*unused*/
1495 uint32_t m_uMemSize;
1496#endif
1497 bool m_fTakingSnapshotOnline;
1498
1499 friend HRESULT SessionMachine::i_finishTakingSnapshot(TakeSnapshotTask &task, AutoWriteLock &alock, bool aSuccess);
1500 friend void SessionMachine::i_takeSnapshotHandler(TakeSnapshotTask &task);
1501 friend void SessionMachine::i_takeSnapshotProgressCancelCallback(void *pvUser);
1502};
1503
1504/** Restore snapshot task */
1505class SessionMachine::RestoreSnapshotTask
1506 : public SessionMachine::SnapshotTask
1507{
1508public:
1509 RestoreSnapshotTask(SessionMachine *m,
1510 Progress *p,
1511 const Utf8Str &t,
1512 Snapshot *s)
1513 : SnapshotTask(m, p, t, s)
1514 {}
1515
1516private:
1517 void handler()
1518 {
1519 try
1520 {
1521 ((SessionMachine *)(Machine *)m_pMachine)->i_restoreSnapshotHandler(*this);
1522 }
1523 catch(...)
1524 {
1525 LogRel(("Some exception in the function i_restoreSnapshotHandler()\n"));
1526 }
1527 }
1528};
1529
1530/** Delete snapshot task */
1531class SessionMachine::DeleteSnapshotTask
1532 : public SessionMachine::SnapshotTask
1533{
1534public:
1535 DeleteSnapshotTask(SessionMachine *m,
1536 Progress *p,
1537 const Utf8Str &t,
1538 bool fDeleteOnline,
1539 Snapshot *s)
1540 : SnapshotTask(m, p, t, s),
1541 m_fDeleteOnline(fDeleteOnline)
1542 {}
1543
1544private:
1545 void handler()
1546 {
1547 try
1548 {
1549 ((SessionMachine *)(Machine *)m_pMachine)->i_deleteSnapshotHandler(*this);
1550 }
1551 catch(...)
1552 {
1553 LogRel(("Some exception in the function i_deleteSnapshotHandler()\n"));
1554 }
1555 }
1556
1557 bool m_fDeleteOnline;
1558 friend void SessionMachine::i_deleteSnapshotHandler(DeleteSnapshotTask &task);
1559};
1560
1561
1562////////////////////////////////////////////////////////////////////////////////
1563//
1564// TakeSnapshot methods (Machine and related tasks)
1565//
1566////////////////////////////////////////////////////////////////////////////////
1567
1568HRESULT Machine::takeSnapshot(const com::Utf8Str &aName,
1569 const com::Utf8Str &aDescription,
1570 BOOL fPause,
1571 com::Guid &aId,
1572 ComPtr<IProgress> &aProgress)
1573{
1574 NOREF(aName);
1575 NOREF(aDescription);
1576 NOREF(fPause);
1577 NOREF(aId);
1578 NOREF(aProgress);
1579 ReturnComNotImplemented();
1580}
1581
1582HRESULT SessionMachine::takeSnapshot(const com::Utf8Str &aName,
1583 const com::Utf8Str &aDescription,
1584 BOOL fPause,
1585 com::Guid &aId,
1586 ComPtr<IProgress> &aProgress)
1587{
1588 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1589 LogFlowThisFunc(("aName='%s' mMachineState=%d\n", aName.c_str(), mData->mMachineState));
1590
1591 if (Global::IsTransient(mData->mMachineState))
1592 return setError(VBOX_E_INVALID_VM_STATE,
1593 tr("Cannot take a snapshot of the machine while it is changing the state (machine state: %s)"),
1594 Global::stringifyMachineState(mData->mMachineState));
1595
1596 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
1597 if (FAILED(rc))
1598 return rc;
1599
1600 // prepare the progress object:
1601 // a) count the no. of hard disk attachments to get a matching no. of progress sub-operations
1602 ULONG cOperations = 2; // always at least setting up + finishing up
1603 ULONG ulTotalOperationsWeight = 2; // one each for setting up + finishing up
1604
1605 for (MediumAttachmentList::iterator
1606 it = mMediumAttachments->begin();
1607 it != mMediumAttachments->end();
1608 ++it)
1609 {
1610 const ComObjPtr<MediumAttachment> pAtt(*it);
1611 AutoReadLock attlock(pAtt COMMA_LOCKVAL_SRC_POS);
1612 AutoCaller attCaller(pAtt);
1613 if (pAtt->i_getType() == DeviceType_HardDisk)
1614 {
1615 ++cOperations;
1616
1617 // assume that creating a diff image takes as long as saving a 1MB state
1618 ulTotalOperationsWeight += 1;
1619 }
1620 }
1621
1622 // b) one extra sub-operations for online snapshots OR offline snapshots that have a saved state (needs to be copied)
1623 const bool fTakingSnapshotOnline = Global::IsOnline(mData->mMachineState);
1624 LogFlowThisFunc(("fTakingSnapshotOnline = %d\n", fTakingSnapshotOnline));
1625 if (fTakingSnapshotOnline)
1626 {
1627 ++cOperations;
1628 ulTotalOperationsWeight += mHWData->mMemorySize;
1629 }
1630
1631 // finally, create the progress object
1632 ComObjPtr<Progress> pProgress;
1633 pProgress.createObject();
1634 rc = pProgress->init(mParent,
1635 static_cast<IMachine *>(this),
1636 Bstr(tr("Taking a snapshot of the virtual machine")).raw(),
1637 fTakingSnapshotOnline /* aCancelable */,
1638 cOperations,
1639 ulTotalOperationsWeight,
1640 Bstr(tr("Setting up snapshot operation")).raw(), // first sub-op description
1641 1); // ulFirstOperationWeight
1642 if (FAILED(rc))
1643 return rc;
1644
1645 /* create an ID for the snapshot */
1646 Guid snapshotId;
1647 snapshotId.create();
1648
1649 /* create and start the task on a separate thread (note that it will not
1650 * start working until we release alock) */
1651 TakeSnapshotTask *pTask = new TakeSnapshotTask(this,
1652 pProgress,
1653 "TakeSnap",
1654 NULL /* pSnapshot */,
1655 aName,
1656 aDescription,
1657 snapshotId,
1658 !!fPause,
1659 mHWData->mMemorySize,
1660 fTakingSnapshotOnline);
1661 MachineState_T const machineStateBackup = pTask->m_machineStateBackup;
1662 rc = pTask->createThread();
1663 pTask = NULL;
1664 if (FAILED(rc))
1665 return rc;
1666
1667 /* set the proper machine state (note: after creating a Task instance) */
1668 if (fTakingSnapshotOnline)
1669 {
1670 if (machineStateBackup != MachineState_Paused && !fPause)
1671 i_setMachineState(MachineState_LiveSnapshotting);
1672 else
1673 i_setMachineState(MachineState_OnlineSnapshotting);
1674 i_updateMachineStateOnClient();
1675 }
1676 else
1677 i_setMachineState(MachineState_Snapshotting);
1678
1679 aId = snapshotId;
1680 pProgress.queryInterfaceTo(aProgress.asOutParam());
1681
1682 return rc;
1683}
1684
1685/**
1686 * Task thread implementation for SessionMachine::TakeSnapshot(), called from
1687 * SessionMachine::taskHandler().
1688 *
1689 * @note Locks this object for writing.
1690 *
1691 * @param task
1692 * @return
1693 */
1694void SessionMachine::i_takeSnapshotHandler(TakeSnapshotTask &task)
1695{
1696 LogFlowThisFuncEnter();
1697
1698 // Taking a snapshot consists of the following:
1699 // 1) creating a Snapshot object with the current state of the machine
1700 // (hardware + storage)
1701 // 2) creating a diff image for each virtual hard disk, into which write
1702 // operations go after the snapshot has been created
1703 // 3) if the machine is online: saving the state of the virtual machine
1704 // (in the VM process)
1705 // 4) reattach the hard disks
1706 // 5) update the various snapshot/machine objects, save settings
1707
1708 HRESULT rc = S_OK;
1709 AutoCaller autoCaller(this);
1710 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
1711 if (FAILED(autoCaller.rc()))
1712 {
1713 /* we might have been uninitialized because the session was accidentally
1714 * closed by the client, so don't assert */
1715 rc = setError(E_FAIL,
1716 tr("The session has been accidentally closed"));
1717 task.m_pProgress->i_notifyComplete(rc);
1718 LogFlowThisFuncLeave();
1719 return;
1720 }
1721
1722 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1723
1724 bool fBeganTakingSnapshot = false;
1725 BOOL fSuspendedBySave = FALSE;
1726
1727 std::set<ComObjPtr<Medium> > pMediumsForNotify;
1728 std::map<Guid, DeviceType_T> uIdsForNotify;
1729
1730 try
1731 {
1732 /// @todo at this point we have to be in the right state!!!!
1733 AssertStmt( mData->mMachineState == MachineState_Snapshotting
1734 || mData->mMachineState == MachineState_OnlineSnapshotting
1735 || mData->mMachineState == MachineState_LiveSnapshotting, throw E_FAIL);
1736 AssertStmt(task.m_machineStateBackup != mData->mMachineState, throw E_FAIL);
1737 AssertStmt(task.m_pSnapshot.isNull(), throw E_FAIL);
1738
1739 if ( mData->mCurrentSnapshot
1740 && mData->mCurrentSnapshot->i_getDepth() >= SETTINGS_SNAPSHOT_DEPTH_MAX)
1741 {
1742 throw setError(VBOX_E_INVALID_OBJECT_STATE,
1743 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"),
1744 mUserData->s.strName.c_str());
1745 }
1746
1747 /* save settings to ensure current changes are committed and
1748 * hard disks are fixed up */
1749 rc = i_saveSettings(NULL);
1750 // no need to check for whether VirtualBox.xml needs changing since
1751 // we can't have a machine XML rename pending at this point
1752 if (FAILED(rc))
1753 throw rc;
1754
1755 /* task.m_strStateFilePath is "" when the machine is offline or saved */
1756 if (task.m_fTakingSnapshotOnline)
1757 {
1758 Bstr value;
1759 rc = GetExtraData(Bstr("VBoxInternal2/ForceTakeSnapshotWithoutState").raw(),
1760 value.asOutParam());
1761 if (FAILED(rc) || value != "1")
1762 // creating a new online snapshot: we need a fresh saved state file
1763 i_composeSavedStateFilename(task.m_strStateFilePath);
1764 }
1765 else if (task.m_machineStateBackup == MachineState_Saved)
1766 // taking an offline snapshot from machine in "saved" state: use existing state file
1767 task.m_strStateFilePath = mSSData->strStateFilePath;
1768
1769 if (task.m_strStateFilePath.isNotEmpty())
1770 {
1771 // ensure the directory for the saved state file exists
1772 rc = VirtualBox::i_ensureFilePathExists(task.m_strStateFilePath, true /* fCreate */);
1773 if (FAILED(rc))
1774 throw rc;
1775 }
1776
1777 /* STEP 1: create the snapshot object */
1778
1779 /* create a snapshot machine object */
1780 ComObjPtr<SnapshotMachine> pSnapshotMachine;
1781 pSnapshotMachine.createObject();
1782 rc = pSnapshotMachine->init(this, task.m_uuidSnapshot.ref(), task.m_strStateFilePath);
1783 AssertComRCThrowRC(rc);
1784
1785 /* create a snapshot object */
1786 RTTIMESPEC time;
1787 RTTimeNow(&time);
1788 task.m_pSnapshot.createObject();
1789 rc = task.m_pSnapshot->init(mParent,
1790 task.m_uuidSnapshot,
1791 task.m_strName,
1792 task.m_strDescription,
1793 time,
1794 pSnapshotMachine,
1795 mData->mCurrentSnapshot);
1796 AssertComRCThrowRC(rc);
1797
1798 /* STEP 2: create the diff images */
1799 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
1800 task.m_fTakingSnapshotOnline));
1801
1802 // Backup the media data so we can recover if something goes wrong.
1803 // The matching commit() is in fixupMedia() during SessionMachine::i_finishTakingSnapshot()
1804 i_setModified(IsModified_Storage);
1805 mMediumAttachments.backup();
1806
1807 alock.release();
1808 /* create new differencing hard disks and attach them to this machine */
1809 rc = i_createImplicitDiffs(task.m_pProgress,
1810 1, // operation weight; must be the same as in Machine::TakeSnapshot()
1811 task.m_fTakingSnapshotOnline);
1812 if (FAILED(rc))
1813 throw rc;
1814 alock.acquire();
1815
1816 // MUST NOT save the settings or the media registry here, because
1817 // this causes trouble with rolling back settings if the user cancels
1818 // taking the snapshot after the diff images have been created.
1819
1820 fBeganTakingSnapshot = true;
1821
1822 // STEP 3: save the VM state (if online)
1823 if (task.m_fTakingSnapshotOnline)
1824 {
1825 task.m_pProgress->SetNextOperation(Bstr(tr("Saving the machine state")).raw(),
1826 mHWData->mMemorySize); // operation weight, same as computed
1827 // when setting up progress object
1828
1829 if (task.m_strStateFilePath.isNotEmpty())
1830 {
1831 alock.release();
1832 task.m_pProgress->i_setCancelCallback(i_takeSnapshotProgressCancelCallback, &task);
1833 rc = task.m_pDirectControl->SaveStateWithReason(Reason_Snapshot,
1834 task.m_pProgress,
1835 task.m_pSnapshot,
1836 Bstr(task.m_strStateFilePath).raw(),
1837 task.m_fPause,
1838 &fSuspendedBySave);
1839 task.m_pProgress->i_setCancelCallback(NULL, NULL);
1840 alock.acquire();
1841 if (FAILED(rc))
1842 throw rc;
1843 }
1844 else
1845 LogRel(("Machine: skipped saving state as part of online snapshot\n"));
1846
1847 if (FAILED(task.m_pProgress->NotifyPointOfNoReturn()))
1848 throw setError(E_FAIL, tr("Canceled"));
1849
1850 // STEP 4: reattach hard disks
1851 LogFlowThisFunc(("Reattaching new differencing hard disks...\n"));
1852
1853 task.m_pProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")).raw(),
1854 1); // operation weight, same as computed when setting up progress object
1855
1856 com::SafeIfaceArray<IMediumAttachment> atts;
1857 rc = COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
1858 if (FAILED(rc))
1859 throw rc;
1860
1861 alock.release();
1862 rc = task.m_pDirectControl->ReconfigureMediumAttachments(ComSafeArrayAsInParam(atts));
1863 alock.acquire();
1864 if (FAILED(rc))
1865 throw rc;
1866 }
1867
1868 // Handle NVRAM file snapshotting
1869 Utf8Str strNVRAM = mBIOSSettings->i_getNonVolatileStorageFile();
1870 Utf8Str strNVRAMSnap = pSnapshotMachine->i_getSnapshotNVRAMFilename();
1871 if (strNVRAM.isNotEmpty() && strNVRAMSnap.isNotEmpty() && RTFileExists(strNVRAM.c_str()))
1872 {
1873 Utf8Str strNVRAMSnapAbs;
1874 i_calculateFullPath(strNVRAMSnap, strNVRAMSnapAbs);
1875 rc = VirtualBox::i_ensureFilePathExists(strNVRAMSnapAbs, true /* fCreate */);
1876 if (FAILED(rc))
1877 throw rc;
1878 int vrc = RTFileCopy(strNVRAM.c_str(), strNVRAMSnapAbs.c_str());
1879 if (RT_FAILURE(vrc))
1880 throw setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
1881 tr("Could not copy NVRAM file '%s' to '%s' (%Rrc)"),
1882 strNVRAM.c_str(), strNVRAMSnapAbs.c_str(), vrc);
1883 pSnapshotMachine->mBIOSSettings->i_updateNonVolatileStorageFile(strNVRAMSnap);
1884 }
1885
1886 // store parent of newly created diffs before commit for notify
1887 {
1888 MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
1889 for (MediumAttachmentList::const_iterator
1890 it = mMediumAttachments->begin();
1891 it != mMediumAttachments->end();
1892 ++it)
1893 {
1894 MediumAttachment *pAttach = *it;
1895 Medium *pMedium = pAttach->i_getMedium();
1896 if (!pMedium)
1897 continue;
1898
1899 bool fFound = false;
1900 /* was this medium attached before? */
1901 for (MediumAttachmentList::iterator
1902 oldIt = oldAtts.begin();
1903 oldIt != oldAtts.end();
1904 ++oldIt)
1905 {
1906 MediumAttachment *pOldAttach = *oldIt;
1907 if (pOldAttach->i_getMedium() == pMedium)
1908 {
1909 fFound = true;
1910 break;
1911 }
1912 }
1913 if (!fFound)
1914 {
1915 pMediumsForNotify.insert(pMedium->i_getParent());
1916 uIdsForNotify[pMedium->i_getId()] = pMedium->i_getDeviceType();
1917 }
1918 }
1919 }
1920
1921 /*
1922 * Finalize the requested snapshot object. This will reset the
1923 * machine state to the state it had at the beginning.
1924 */
1925 rc = i_finishTakingSnapshot(task, alock, true /*aSuccess*/);
1926 // do not throw rc here because we can't call i_finishTakingSnapshot() twice
1927 LogFlowThisFunc(("i_finishTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(mData->mMachineState)));
1928 }
1929 catch (HRESULT rcThrown)
1930 {
1931 rc = rcThrown;
1932 LogThisFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(mData->mMachineState)));
1933
1934 /// @todo r=klaus check that the implicit diffs created above are cleaned up im the relevant error cases
1935
1936 /* preserve existing error info */
1937 ErrorInfoKeeper eik;
1938
1939 if (fBeganTakingSnapshot)
1940 i_finishTakingSnapshot(task, alock, false /*aSuccess*/);
1941
1942 // have to postpone this to the end as i_finishTakingSnapshot() needs
1943 // it for various cleanup steps
1944 if (task.m_pSnapshot)
1945 {
1946 task.m_pSnapshot->uninit();
1947 task.m_pSnapshot.setNull();
1948 }
1949 }
1950 Assert(alock.isWriteLockOnCurrentThread());
1951
1952 {
1953 // Keep all error information over the cleanup steps
1954 ErrorInfoKeeper eik;
1955
1956 /*
1957 * Fix up the machine state.
1958 *
1959 * For offline snapshots we just update the local copy, for the other
1960 * variants do the entire work. This ensures that the state is in sync
1961 * with the VM process (in particular the VM execution state).
1962 */
1963 bool fNeedClientMachineStateUpdate = false;
1964 if ( mData->mMachineState == MachineState_LiveSnapshotting
1965 || mData->mMachineState == MachineState_OnlineSnapshotting
1966 || mData->mMachineState == MachineState_Snapshotting)
1967 {
1968 if (!task.m_fTakingSnapshotOnline)
1969 i_setMachineState(task.m_machineStateBackup);
1970 else
1971 {
1972 MachineState_T enmMachineState = MachineState_Null;
1973 HRESULT rc2 = task.m_pDirectControl->COMGETTER(NominalState)(&enmMachineState);
1974 if (FAILED(rc2) || enmMachineState == MachineState_Null)
1975 {
1976 AssertMsgFailed(("state=%s\n", Global::stringifyMachineState(enmMachineState)));
1977 // pure nonsense, try to continue somehow
1978 enmMachineState = MachineState_Aborted;
1979 }
1980 if (enmMachineState == MachineState_Paused)
1981 {
1982 if (fSuspendedBySave)
1983 {
1984 alock.release();
1985 rc2 = task.m_pDirectControl->ResumeWithReason(Reason_Snapshot);
1986 alock.acquire();
1987 if (SUCCEEDED(rc2))
1988 enmMachineState = task.m_machineStateBackup;
1989 }
1990 else
1991 enmMachineState = task.m_machineStateBackup;
1992 }
1993 if (enmMachineState != mData->mMachineState)
1994 {
1995 fNeedClientMachineStateUpdate = true;
1996 i_setMachineState(enmMachineState);
1997 }
1998 }
1999 }
2000
2001 /* check the remote state to see that we got it right. */
2002 MachineState_T enmMachineState = MachineState_Null;
2003 if (!task.m_pDirectControl.isNull())
2004 {
2005 ComPtr<IConsole> pConsole;
2006 task.m_pDirectControl->COMGETTER(RemoteConsole)(pConsole.asOutParam());
2007 if (!pConsole.isNull())
2008 pConsole->COMGETTER(State)(&enmMachineState);
2009 }
2010 LogFlowThisFunc(("local mMachineState=%s remote mMachineState=%s\n",
2011 Global::stringifyMachineState(mData->mMachineState),
2012 Global::stringifyMachineState(enmMachineState)));
2013
2014 if (fNeedClientMachineStateUpdate)
2015 i_updateMachineStateOnClient();
2016 }
2017
2018 task.m_pProgress->i_notifyComplete(rc);
2019
2020 if (SUCCEEDED(rc))
2021 mParent->i_onSnapshotTaken(mData->mUuid, task.m_uuidSnapshot);
2022
2023 if (SUCCEEDED(rc))
2024 {
2025 for (std::map<Guid, DeviceType_T>::const_iterator it = uIdsForNotify.begin();
2026 it != uIdsForNotify.end();
2027 ++it)
2028 {
2029 mParent->i_onMediumRegistered(it->first, it->second, TRUE);
2030 }
2031
2032 for (std::set<ComObjPtr<Medium> >::const_iterator it = pMediumsForNotify.begin();
2033 it != pMediumsForNotify.end();
2034 ++it)
2035 {
2036 if (it->isNotNull())
2037 mParent->i_onMediumConfigChanged(*it);
2038 }
2039 }
2040 LogFlowThisFuncLeave();
2041}
2042
2043
2044/**
2045 * Progress cancelation callback employed by SessionMachine::i_takeSnapshotHandler.
2046 */
2047/*static*/
2048void SessionMachine::i_takeSnapshotProgressCancelCallback(void *pvUser)
2049{
2050 TakeSnapshotTask *pTask = (TakeSnapshotTask *)pvUser;
2051 AssertPtrReturnVoid(pTask);
2052 AssertReturnVoid(!pTask->m_pDirectControl.isNull());
2053 pTask->m_pDirectControl->CancelSaveStateWithReason();
2054}
2055
2056
2057/**
2058 * Called by the Console when it's done saving the VM state into the snapshot
2059 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
2060 *
2061 * This also gets called if the console part of snapshotting failed after the
2062 * BeginTakingSnapshot() call, to clean up the server side.
2063 *
2064 * @note Locks VirtualBox and this object for writing.
2065 *
2066 * @param task
2067 * @param alock
2068 * @param aSuccess Whether Console was successful with the client-side
2069 * snapshot things.
2070 * @return
2071 */
2072HRESULT SessionMachine::i_finishTakingSnapshot(TakeSnapshotTask &task, AutoWriteLock &alock, bool aSuccess)
2073{
2074 LogFlowThisFunc(("\n"));
2075
2076 Assert(alock.isWriteLockOnCurrentThread());
2077
2078 AssertReturn( !aSuccess
2079 || mData->mMachineState == MachineState_Snapshotting
2080 || mData->mMachineState == MachineState_OnlineSnapshotting
2081 || mData->mMachineState == MachineState_LiveSnapshotting, E_FAIL);
2082
2083 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
2084 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
2085
2086 HRESULT rc = S_OK;
2087
2088 if (aSuccess)
2089 {
2090 // new snapshot becomes the current one
2091 mData->mCurrentSnapshot = task.m_pSnapshot;
2092
2093 /* memorize the first snapshot if necessary */
2094 if (!mData->mFirstSnapshot)
2095 mData->mFirstSnapshot = mData->mCurrentSnapshot;
2096
2097 int flSaveSettings = SaveS_Force; // do not do a deep compare in machine settings,
2098 // snapshots change, so we know we need to save
2099 if (!task.m_fTakingSnapshotOnline)
2100 /* the machine was powered off or saved when taking a snapshot, so
2101 * reset the mCurrentStateModified flag */
2102 flSaveSettings |= SaveS_ResetCurStateModified;
2103
2104 rc = i_saveSettings(NULL, flSaveSettings);
2105 }
2106
2107 if (aSuccess && SUCCEEDED(rc))
2108 {
2109 /* associate old hard disks with the snapshot and do locking/unlocking*/
2110 i_commitMedia(task.m_fTakingSnapshotOnline);
2111 alock.release();
2112 }
2113 else
2114 {
2115 /* delete all differencing hard disks created (this will also attach
2116 * their parents back by rolling back mMediaData) */
2117 alock.release();
2118
2119 i_rollbackMedia();
2120
2121 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
2122 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
2123
2124 // delete the saved state file (it might have been already created)
2125 if (task.m_fTakingSnapshotOnline)
2126 // no need to test for whether the saved state file is shared: an online
2127 // snapshot means that a new saved state file was created, which we must
2128 // clean up now
2129 RTFileDelete(task.m_pSnapshot->i_getStateFilePath().c_str());
2130
2131 alock.acquire();
2132
2133 task.m_pSnapshot->uninit();
2134 alock.release();
2135
2136 }
2137
2138 /* clear out the snapshot data */
2139 task.m_pSnapshot.setNull();
2140
2141 /* alock has been released already */
2142 mParent->i_saveModifiedRegistries();
2143
2144 alock.acquire();
2145
2146 return rc;
2147}
2148
2149////////////////////////////////////////////////////////////////////////////////
2150//
2151// RestoreSnapshot methods (Machine and related tasks)
2152//
2153////////////////////////////////////////////////////////////////////////////////
2154
2155HRESULT Machine::restoreSnapshot(const ComPtr<ISnapshot> &aSnapshot,
2156 ComPtr<IProgress> &aProgress)
2157{
2158 NOREF(aSnapshot);
2159 NOREF(aProgress);
2160 ReturnComNotImplemented();
2161}
2162
2163/**
2164 * Restoring a snapshot happens entirely on the server side, the machine cannot be running.
2165 *
2166 * This creates a new thread that does the work and returns a progress object to the client.
2167 * Actual work then takes place in RestoreSnapshotTask::handler().
2168 *
2169 * @note Locks this + children objects for writing!
2170 *
2171 * @param aSnapshot in: the snapshot to restore.
2172 * @param aProgress out: progress object to monitor restore thread.
2173 * @return
2174 */
2175HRESULT SessionMachine::restoreSnapshot(const ComPtr<ISnapshot> &aSnapshot,
2176 ComPtr<IProgress> &aProgress)
2177{
2178 LogFlowThisFuncEnter();
2179
2180 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2181
2182 // machine must not be running
2183 if (Global::IsOnlineOrTransient(mData->mMachineState))
2184 return setError(VBOX_E_INVALID_VM_STATE,
2185 tr("Cannot delete the current state of the running machine (machine state: %s)"),
2186 Global::stringifyMachineState(mData->mMachineState));
2187
2188 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
2189 if (FAILED(rc))
2190 return rc;
2191
2192 ISnapshot* iSnapshot = aSnapshot;
2193 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(iSnapshot));
2194 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->i_getSnapshotMachine();
2195
2196 // create a progress object. The number of operations is:
2197 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
2198 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2199
2200 ULONG ulOpCount = 1; // one for preparations
2201 ULONG ulTotalWeight = 1; // one for preparations
2202 for (MediumAttachmentList::iterator
2203 it = pSnapMachine->mMediumAttachments->begin();
2204 it != pSnapMachine->mMediumAttachments->end();
2205 ++it)
2206 {
2207 ComObjPtr<MediumAttachment> &pAttach = *it;
2208 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2209 if (pAttach->i_getType() == DeviceType_HardDisk)
2210 {
2211 ++ulOpCount;
2212 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
2213 Assert(pAttach->i_getMedium());
2214 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount,
2215 pAttach->i_getMedium()->i_getName().c_str()));
2216 }
2217 }
2218
2219 ComObjPtr<Progress> pProgress;
2220 pProgress.createObject();
2221 pProgress->init(mParent, static_cast<IMachine*>(this),
2222 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->i_getName().c_str()).raw(),
2223 FALSE /* aCancelable */,
2224 ulOpCount,
2225 ulTotalWeight,
2226 Bstr(tr("Restoring machine settings")).raw(),
2227 1);
2228
2229 /* create and start the task on a separate thread (note that it will not
2230 * start working until we release alock) */
2231 RestoreSnapshotTask *pTask = new RestoreSnapshotTask(this,
2232 pProgress,
2233 "RestoreSnap",
2234 pSnapshot);
2235 rc = pTask->createThread();
2236 pTask = NULL;
2237 if (FAILED(rc))
2238 return rc;
2239
2240 /* set the proper machine state (note: after creating a Task instance) */
2241 i_setMachineState(MachineState_RestoringSnapshot);
2242
2243 /* return the progress to the caller */
2244 pProgress.queryInterfaceTo(aProgress.asOutParam());
2245
2246 LogFlowThisFuncLeave();
2247
2248 return S_OK;
2249}
2250
2251/**
2252 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
2253 * This method gets called indirectly through SessionMachine::taskHandler() which then
2254 * calls RestoreSnapshotTask::handler().
2255 *
2256 * The RestoreSnapshotTask contains the progress object returned to the console by
2257 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
2258 *
2259 * @note Locks mParent + this object for writing.
2260 *
2261 * @param task Task data.
2262 */
2263void SessionMachine::i_restoreSnapshotHandler(RestoreSnapshotTask &task)
2264{
2265 LogFlowThisFuncEnter();
2266
2267 AutoCaller autoCaller(this);
2268
2269 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
2270 if (!autoCaller.isOk())
2271 {
2272 /* we might have been uninitialized because the session was accidentally
2273 * closed by the client, so don't assert */
2274 task.m_pProgress->i_notifyComplete(E_FAIL,
2275 COM_IIDOF(IMachine),
2276 getComponentName(),
2277 tr("The session has been accidentally closed"));
2278
2279 LogFlowThisFuncLeave();
2280 return;
2281 }
2282
2283 HRESULT rc = S_OK;
2284 Guid snapshotId;
2285 std::set<ComObjPtr<Medium> > pMediumsForNotify;
2286 std::map<Guid, std::pair<DeviceType_T, BOOL> > uIdsForNotify;
2287
2288 try
2289 {
2290 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2291
2292 /* Discard all current changes to mUserData (name, OSType etc.).
2293 * Note that the machine is powered off, so there is no need to inform
2294 * the direct session. */
2295 if (mData->flModifications)
2296 i_rollback(false /* aNotify */);
2297
2298 /* Delete the saved state file if the machine was Saved prior to this
2299 * operation */
2300 if (task.m_machineStateBackup == MachineState_Saved)
2301 {
2302 Assert(!mSSData->strStateFilePath.isEmpty());
2303
2304 // release the saved state file AFTER unsetting the member variable
2305 // so that releaseSavedStateFile() won't think it's still in use
2306 Utf8Str strStateFile(mSSData->strStateFilePath);
2307 mSSData->strStateFilePath.setNull();
2308 i_releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
2309
2310 task.modifyBackedUpState(MachineState_PoweredOff);
2311
2312 rc = i_saveStateSettings(SaveSTS_StateFilePath);
2313 if (FAILED(rc))
2314 throw rc;
2315 }
2316
2317 RTTIMESPEC snapshotTimeStamp;
2318 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
2319
2320 {
2321 AutoReadLock snapshotLock(task.m_pSnapshot COMMA_LOCKVAL_SRC_POS);
2322
2323 /* remember the timestamp of the snapshot we're restoring from */
2324 snapshotTimeStamp = task.m_pSnapshot->i_getTimeStamp();
2325
2326 // save the snapshot ID (paranoia, here we hold the lock)
2327 snapshotId = task.m_pSnapshot->i_getId();
2328
2329 ComPtr<SnapshotMachine> pSnapshotMachine(task.m_pSnapshot->i_getSnapshotMachine());
2330
2331 /* copy all hardware data from the snapshot */
2332 i_copyFrom(pSnapshotMachine);
2333
2334 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
2335
2336 // restore the attachments from the snapshot
2337 i_setModified(IsModified_Storage);
2338 mMediumAttachments.backup();
2339 mMediumAttachments->clear();
2340 for (MediumAttachmentList::const_iterator
2341 it = pSnapshotMachine->mMediumAttachments->begin();
2342 it != pSnapshotMachine->mMediumAttachments->end();
2343 ++it)
2344 {
2345 ComObjPtr<MediumAttachment> pAttach;
2346 pAttach.createObject();
2347 pAttach->initCopy(this, *it);
2348 mMediumAttachments->push_back(pAttach);
2349 }
2350
2351 /* release the locks before the potentially lengthy operation */
2352 snapshotLock.release();
2353 alock.release();
2354
2355 rc = i_createImplicitDiffs(task.m_pProgress,
2356 1,
2357 false /* aOnline */);
2358 if (FAILED(rc))
2359 throw rc;
2360
2361 alock.acquire();
2362 snapshotLock.acquire();
2363
2364 /* Note: on success, current (old) hard disks will be
2365 * deassociated/deleted on #commit() called from #i_saveSettings() at
2366 * the end. On failure, newly created implicit diffs will be
2367 * deleted by #rollback() at the end. */
2368
2369 /* should not have a saved state file associated at this point */
2370 Assert(mSSData->strStateFilePath.isEmpty());
2371
2372 const Utf8Str &strSnapshotStateFile = task.m_pSnapshot->i_getStateFilePath();
2373
2374 if (strSnapshotStateFile.isNotEmpty())
2375 // online snapshot: then share the state file
2376 mSSData->strStateFilePath = strSnapshotStateFile;
2377
2378 const Utf8Str srcNVRAM(pSnapshotMachine->mBIOSSettings->i_getNonVolatileStorageFile());
2379 const Utf8Str dstNVRAM(mBIOSSettings->i_getNonVolatileStorageFile());
2380 if (dstNVRAM.isNotEmpty() && RTFileExists(dstNVRAM.c_str()))
2381 RTFileDelete(dstNVRAM.c_str());
2382 if (srcNVRAM.isNotEmpty() && dstNVRAM.isNotEmpty() && RTFileExists(srcNVRAM.c_str()))
2383 RTFileCopy(srcNVRAM.c_str(), dstNVRAM.c_str());
2384
2385 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", task.m_pSnapshot->i_getId().raw()));
2386 /* make the snapshot we restored from the current snapshot */
2387 mData->mCurrentSnapshot = task.m_pSnapshot;
2388 }
2389
2390 // store parent of newly created diffs for notify
2391 {
2392 MediumAttachmentList &oldAtts = *mMediumAttachments.backedUpData();
2393 for (MediumAttachmentList::const_iterator
2394 it = mMediumAttachments->begin();
2395 it != mMediumAttachments->end();
2396 ++it)
2397 {
2398 MediumAttachment *pAttach = *it;
2399 Medium *pMedium = pAttach->i_getMedium();
2400 if (!pMedium)
2401 continue;
2402
2403 bool fFound = false;
2404 /* was this medium attached before? */
2405 for (MediumAttachmentList::iterator
2406 oldIt = oldAtts.begin();
2407 oldIt != oldAtts.end();
2408 ++oldIt)
2409 {
2410 MediumAttachment *pOldAttach = *oldIt;
2411 if (pOldAttach->i_getMedium() == pMedium)
2412 {
2413 fFound = true;
2414 break;
2415 }
2416 }
2417 if (!fFound)
2418 {
2419 pMediumsForNotify.insert(pMedium->i_getParent());
2420 uIdsForNotify[pMedium->i_getId()] = std::pair<DeviceType_T, BOOL>(pMedium->i_getDeviceType(), TRUE);
2421 }
2422 }
2423 }
2424
2425 /* grab differencing hard disks from the old attachments that will
2426 * become unused and need to be auto-deleted */
2427 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
2428
2429 for (MediumAttachmentList::const_iterator
2430 it = mMediumAttachments.backedUpData()->begin();
2431 it != mMediumAttachments.backedUpData()->end();
2432 ++it)
2433 {
2434 ComObjPtr<MediumAttachment> pAttach = *it;
2435 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
2436
2437 /* while the hard disk is attached, the number of children or the
2438 * parent cannot change, so no lock */
2439 if ( !pMedium.isNull()
2440 && pAttach->i_getType() == DeviceType_HardDisk
2441 && !pMedium->i_getParent().isNull()
2442 && pMedium->i_getChildren().size() == 0
2443 )
2444 {
2445 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->i_getName().c_str()));
2446
2447 llDiffAttachmentsToDelete.push_back(pAttach);
2448 }
2449 }
2450
2451 /* we have already deleted the current state, so set the execution
2452 * state accordingly no matter of the delete snapshot result */
2453 if (mSSData->strStateFilePath.isNotEmpty())
2454 task.modifyBackedUpState(MachineState_Saved);
2455 else
2456 task.modifyBackedUpState(MachineState_PoweredOff);
2457
2458 /* Paranoia: no one must have saved the settings in the mean time. If
2459 * it happens nevertheless we'll close our eyes and continue below. */
2460 Assert(mMediumAttachments.isBackedUp());
2461
2462 /* assign the timestamp from the snapshot */
2463 Assert(RTTimeSpecGetMilli(&snapshotTimeStamp) != 0);
2464 mData->mLastStateChange = snapshotTimeStamp;
2465
2466 // detach the current-state diffs that we detected above and build a list of
2467 // image files to delete _after_ i_saveSettings()
2468
2469 MediaList llDiffsToDelete;
2470
2471 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
2472 it != llDiffAttachmentsToDelete.end();
2473 ++it)
2474 {
2475 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
2476 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
2477
2478 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2479
2480 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->i_getName().c_str()));
2481
2482 // Normally we "detach" the medium by removing the attachment object
2483 // from the current machine data; i_saveSettings() below would then
2484 // compare the current machine data with the one in the backup
2485 // and actually call Medium::removeBackReference(). But that works only half
2486 // the time in our case so instead we force a detachment here:
2487 // remove from machine data
2488 mMediumAttachments->remove(pAttach);
2489 // Remove it from the backup or else i_saveSettings will try to detach
2490 // it again and assert. The paranoia check avoids crashes (see
2491 // assert above) if this code is buggy and saves settings in the
2492 // wrong place.
2493 if (mMediumAttachments.isBackedUp())
2494 mMediumAttachments.backedUpData()->remove(pAttach);
2495 // then clean up backrefs
2496 pMedium->i_removeBackReference(mData->mUuid);
2497
2498 llDiffsToDelete.push_back(pMedium);
2499 }
2500
2501 // save machine settings, reset the modified flag and commit;
2502 bool fNeedsGlobalSaveSettings = false;
2503 rc = i_saveSettings(&fNeedsGlobalSaveSettings,
2504 SaveS_ResetCurStateModified);
2505 if (FAILED(rc))
2506 throw rc;
2507
2508 // release the locks before updating registry and deleting image files
2509 alock.release();
2510
2511 // unconditionally add the parent registry.
2512 mParent->i_markRegistryModified(mParent->i_getGlobalRegistryId());
2513
2514 // from here on we cannot roll back on failure any more
2515
2516 for (MediaList::iterator it = llDiffsToDelete.begin();
2517 it != llDiffsToDelete.end();
2518 ++it)
2519 {
2520 ComObjPtr<Medium> &pMedium = *it;
2521 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->i_getName().c_str()));
2522
2523 ComObjPtr<Medium> pParent = pMedium->i_getParent();
2524 // store the id here because it becomes NULL after deleting storage.
2525 com::Guid id = pMedium->i_getId();
2526 HRESULT rc2 = pMedium->i_deleteStorage(NULL /* aProgress */,
2527 true /* aWait */,
2528 false /* aNotify */);
2529 // ignore errors here because we cannot roll back after i_saveSettings() above
2530 if (SUCCEEDED(rc2))
2531 {
2532 pMediumsForNotify.insert(pParent);
2533 uIdsForNotify[id] = std::pair<DeviceType_T, BOOL>(pMedium->i_getDeviceType(), FALSE);
2534 pMedium->uninit();
2535 }
2536 }
2537 }
2538 catch (HRESULT aRC)
2539 {
2540 rc = aRC;
2541 }
2542
2543 if (FAILED(rc))
2544 {
2545 /* preserve existing error info */
2546 ErrorInfoKeeper eik;
2547
2548 /* undo all changes on failure */
2549 i_rollback(false /* aNotify */);
2550
2551 }
2552
2553 mParent->i_saveModifiedRegistries();
2554
2555 /* restore the machine state */
2556 i_setMachineState(task.m_machineStateBackup);
2557
2558 /* set the result (this will try to fetch current error info on failure) */
2559 task.m_pProgress->i_notifyComplete(rc);
2560
2561 if (SUCCEEDED(rc))
2562 {
2563 mParent->i_onSnapshotRestored(mData->mUuid, snapshotId);
2564 for (std::map<Guid, std::pair<DeviceType_T, BOOL> >::const_iterator it = uIdsForNotify.begin();
2565 it != uIdsForNotify.end();
2566 ++it)
2567 {
2568 mParent->i_onMediumRegistered(it->first, it->second.first, it->second.second);
2569 }
2570 for (std::set<ComObjPtr<Medium> >::const_iterator it = pMediumsForNotify.begin();
2571 it != pMediumsForNotify.end();
2572 ++it)
2573 {
2574 if (it->isNotNull())
2575 mParent->i_onMediumConfigChanged(*it);
2576 }
2577 }
2578
2579 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
2580
2581 LogFlowThisFuncLeave();
2582}
2583
2584////////////////////////////////////////////////////////////////////////////////
2585//
2586// DeleteSnapshot methods (SessionMachine and related tasks)
2587//
2588////////////////////////////////////////////////////////////////////////////////
2589
2590HRESULT Machine::deleteSnapshot(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2591{
2592 NOREF(aId);
2593 NOREF(aProgress);
2594 ReturnComNotImplemented();
2595}
2596
2597HRESULT SessionMachine::deleteSnapshot(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2598{
2599 return i_deleteSnapshot(aId, aId,
2600 FALSE /* fDeleteAllChildren */,
2601 aProgress);
2602}
2603
2604HRESULT Machine::deleteSnapshotAndAllChildren(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2605{
2606 NOREF(aId);
2607 NOREF(aProgress);
2608 ReturnComNotImplemented();
2609}
2610
2611HRESULT SessionMachine::deleteSnapshotAndAllChildren(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2612{
2613 return i_deleteSnapshot(aId, aId,
2614 TRUE /* fDeleteAllChildren */,
2615 aProgress);
2616}
2617
2618HRESULT Machine::deleteSnapshotRange(const com::Guid &aStartId, const com::Guid &aEndId, ComPtr<IProgress> &aProgress)
2619{
2620 NOREF(aStartId);
2621 NOREF(aEndId);
2622 NOREF(aProgress);
2623 ReturnComNotImplemented();
2624}
2625
2626HRESULT SessionMachine::deleteSnapshotRange(const com::Guid &aStartId, const com::Guid &aEndId, ComPtr<IProgress> &aProgress)
2627{
2628 return i_deleteSnapshot(aStartId, aEndId,
2629 FALSE /* fDeleteAllChildren */,
2630 aProgress);
2631}
2632
2633
2634/**
2635 * Implementation for SessionMachine::i_deleteSnapshot().
2636 *
2637 * Gets called from SessionMachine::DeleteSnapshot(). Deleting a snapshot
2638 * happens entirely on the server side if the machine is not running, and
2639 * if it is running then the merges are done via internal session callbacks.
2640 *
2641 * This creates a new thread that does the work and returns a progress
2642 * object to the client.
2643 *
2644 * Actual work then takes place in SessionMachine::i_deleteSnapshotHandler().
2645 *
2646 * @note Locks mParent + this + children objects for writing!
2647 */
2648HRESULT SessionMachine::i_deleteSnapshot(const com::Guid &aStartId,
2649 const com::Guid &aEndId,
2650 BOOL aDeleteAllChildren,
2651 ComPtr<IProgress> &aProgress)
2652{
2653 LogFlowThisFuncEnter();
2654
2655 AssertReturn(!aStartId.isZero() && !aEndId.isZero() && aStartId.isValid() && aEndId.isValid(), E_INVALIDARG);
2656
2657 /** @todo implement the "and all children" and "range" variants */
2658 if (aDeleteAllChildren || aStartId != aEndId)
2659 ReturnComNotImplemented();
2660
2661 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2662
2663 if (Global::IsTransient(mData->mMachineState))
2664 return setError(VBOX_E_INVALID_VM_STATE,
2665 tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
2666 Global::stringifyMachineState(mData->mMachineState));
2667
2668 // be very picky about machine states
2669 if ( Global::IsOnlineOrTransient(mData->mMachineState)
2670 && mData->mMachineState != MachineState_PoweredOff
2671 && mData->mMachineState != MachineState_Saved
2672 && mData->mMachineState != MachineState_Teleported
2673 && mData->mMachineState != MachineState_Aborted
2674 && mData->mMachineState != MachineState_Running
2675 && mData->mMachineState != MachineState_Paused)
2676 return setError(VBOX_E_INVALID_VM_STATE,
2677 tr("Invalid machine state: %s"),
2678 Global::stringifyMachineState(mData->mMachineState));
2679
2680 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
2681 if (FAILED(rc))
2682 return rc;
2683
2684 ComObjPtr<Snapshot> pSnapshot;
2685 rc = i_findSnapshotById(aStartId, pSnapshot, true /* aSetError */);
2686 if (FAILED(rc))
2687 return rc;
2688
2689 AutoWriteLock snapshotLock(pSnapshot COMMA_LOCKVAL_SRC_POS);
2690 Utf8Str str;
2691
2692 size_t childrenCount = pSnapshot->i_getChildrenCount();
2693 if (childrenCount > 1)
2694 return setError(VBOX_E_INVALID_OBJECT_STATE,
2695 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"),
2696 pSnapshot->i_getName().c_str(),
2697 mUserData->s.strName.c_str(),
2698 childrenCount);
2699
2700 if (pSnapshot == mData->mCurrentSnapshot && childrenCount >= 1)
2701 return setError(VBOX_E_INVALID_OBJECT_STATE,
2702 tr("Snapshot '%s' of the machine '%s' cannot be deleted, because it is the current snapshot and has one child snapshot"),
2703 pSnapshot->i_getName().c_str(),
2704 mUserData->s.strName.c_str());
2705
2706 /* If the snapshot being deleted is the current one, ensure current
2707 * settings are committed and saved.
2708 */
2709 if (pSnapshot == mData->mCurrentSnapshot)
2710 {
2711 if (mData->flModifications)
2712 {
2713 rc = i_saveSettings(NULL);
2714 // no need to change for whether VirtualBox.xml needs saving since
2715 // we can't have a machine XML rename pending at this point
2716 if (FAILED(rc)) return rc;
2717 }
2718 }
2719
2720 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->i_getSnapshotMachine();
2721
2722 /* create a progress object. The number of operations is:
2723 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
2724 */
2725 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2726
2727 ULONG ulOpCount = 1; // one for preparations
2728 ULONG ulTotalWeight = 1; // one for preparations
2729
2730 if (pSnapshot->i_getStateFilePath().isNotEmpty())
2731 {
2732 ++ulOpCount;
2733 ++ulTotalWeight; // assume 1 MB for deleting the state file
2734 }
2735
2736 bool fDeleteOnline = mData->mMachineState == MachineState_Running || mData->mMachineState == MachineState_Paused;
2737
2738 // count normal hard disks and add their sizes to the weight
2739 for (MediumAttachmentList::iterator
2740 it = pSnapMachine->mMediumAttachments->begin();
2741 it != pSnapMachine->mMediumAttachments->end();
2742 ++it)
2743 {
2744 ComObjPtr<MediumAttachment> &pAttach = *it;
2745 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2746 if (pAttach->i_getType() == DeviceType_HardDisk)
2747 {
2748 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
2749 Assert(pHD);
2750 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2751
2752 MediumType_T type = pHD->i_getType();
2753 // writethrough and shareable images are unaffected by snapshots,
2754 // so do nothing for them
2755 if ( type != MediumType_Writethrough
2756 && type != MediumType_Shareable
2757 && type != MediumType_Readonly)
2758 {
2759 // normal or immutable media need attention
2760 ++ulOpCount;
2761 // offline merge includes medium resizing
2762 if (!fDeleteOnline)
2763 ++ulOpCount;
2764 ulTotalWeight += (ULONG)(pHD->i_getSize() / _1M);
2765 }
2766 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->i_getName().c_str()));
2767 }
2768 }
2769
2770 ComObjPtr<Progress> pProgress;
2771 pProgress.createObject();
2772 pProgress->init(mParent, static_cast<IMachine*>(this),
2773 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->i_getName().c_str()).raw(),
2774 FALSE /* aCancelable */,
2775 ulOpCount,
2776 ulTotalWeight,
2777 Bstr(tr("Setting up")).raw(),
2778 1);
2779
2780 /* create and start the task on a separate thread */
2781 DeleteSnapshotTask *pTask = new DeleteSnapshotTask(this, pProgress,
2782 "DeleteSnap",
2783 fDeleteOnline,
2784 pSnapshot);
2785 rc = pTask->createThread();
2786 pTask = NULL;
2787 if (FAILED(rc))
2788 return rc;
2789
2790 // the task might start running but will block on acquiring the machine's write lock
2791 // which we acquired above; once this function leaves, the task will be unblocked;
2792 // set the proper machine state here now (note: after creating a Task instance)
2793 if (mData->mMachineState == MachineState_Running)
2794 {
2795 i_setMachineState(MachineState_DeletingSnapshotOnline);
2796 i_updateMachineStateOnClient();
2797 }
2798 else if (mData->mMachineState == MachineState_Paused)
2799 {
2800 i_setMachineState(MachineState_DeletingSnapshotPaused);
2801 i_updateMachineStateOnClient();
2802 }
2803 else
2804 i_setMachineState(MachineState_DeletingSnapshot);
2805
2806 /* return the progress to the caller */
2807 pProgress.queryInterfaceTo(aProgress.asOutParam());
2808
2809 LogFlowThisFuncLeave();
2810
2811 return S_OK;
2812}
2813
2814/**
2815 * Helper struct for SessionMachine::deleteSnapshotHandler().
2816 */
2817struct MediumDeleteRec
2818{
2819 MediumDeleteRec()
2820 : mfNeedsOnlineMerge(false),
2821 mpMediumLockList(NULL)
2822 {}
2823
2824 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2825 const ComObjPtr<Medium> &aSource,
2826 const ComObjPtr<Medium> &aTarget,
2827 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2828 bool fMergeForward,
2829 const ComObjPtr<Medium> &aParentForTarget,
2830 MediumLockList *aChildrenToReparent,
2831 bool fNeedsOnlineMerge,
2832 MediumLockList *aMediumLockList,
2833 const ComPtr<IToken> &aHDLockToken)
2834 : mpHD(aHd),
2835 mpSource(aSource),
2836 mpTarget(aTarget),
2837 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2838 mfMergeForward(fMergeForward),
2839 mpParentForTarget(aParentForTarget),
2840 mpChildrenToReparent(aChildrenToReparent),
2841 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2842 mpMediumLockList(aMediumLockList),
2843 mpHDLockToken(aHDLockToken)
2844 {}
2845
2846 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2847 const ComObjPtr<Medium> &aSource,
2848 const ComObjPtr<Medium> &aTarget,
2849 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2850 bool fMergeForward,
2851 const ComObjPtr<Medium> &aParentForTarget,
2852 MediumLockList *aChildrenToReparent,
2853 bool fNeedsOnlineMerge,
2854 MediumLockList *aMediumLockList,
2855 const ComPtr<IToken> &aHDLockToken,
2856 const Guid &aMachineId,
2857 const Guid &aSnapshotId)
2858 : mpHD(aHd),
2859 mpSource(aSource),
2860 mpTarget(aTarget),
2861 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2862 mfMergeForward(fMergeForward),
2863 mpParentForTarget(aParentForTarget),
2864 mpChildrenToReparent(aChildrenToReparent),
2865 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2866 mpMediumLockList(aMediumLockList),
2867 mpHDLockToken(aHDLockToken),
2868 mMachineId(aMachineId),
2869 mSnapshotId(aSnapshotId)
2870 {}
2871
2872 ComObjPtr<Medium> mpHD;
2873 ComObjPtr<Medium> mpSource;
2874 ComObjPtr<Medium> mpTarget;
2875 ComObjPtr<MediumAttachment> mpOnlineMediumAttachment;
2876 bool mfMergeForward;
2877 ComObjPtr<Medium> mpParentForTarget;
2878 MediumLockList *mpChildrenToReparent;
2879 bool mfNeedsOnlineMerge;
2880 MediumLockList *mpMediumLockList;
2881 /** optional lock token, used only in case mpHD is not merged/deleted */
2882 ComPtr<IToken> mpHDLockToken;
2883 /* these are for reattaching the hard disk in case of a failure: */
2884 Guid mMachineId;
2885 Guid mSnapshotId;
2886};
2887
2888typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2889
2890/**
2891 * Worker method for the delete snapshot thread created by
2892 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2893 * through SessionMachine::taskHandler() which then calls
2894 * DeleteSnapshotTask::handler().
2895 *
2896 * The DeleteSnapshotTask contains the progress object returned to the console
2897 * by SessionMachine::DeleteSnapshot, through which progress and results are
2898 * reported.
2899 *
2900 * SessionMachine::DeleteSnapshot() has set the machine state to
2901 * MachineState_DeletingSnapshot right after creating this task. Since we block
2902 * on the machine write lock at the beginning, once that has been acquired, we
2903 * can assume that the machine state is indeed that.
2904 *
2905 * @note Locks the machine + the snapshot + the media tree for writing!
2906 *
2907 * @param task Task data.
2908 */
2909void SessionMachine::i_deleteSnapshotHandler(DeleteSnapshotTask &task)
2910{
2911 LogFlowThisFuncEnter();
2912
2913 MultiResult mrc(S_OK);
2914 AutoCaller autoCaller(this);
2915 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
2916 if (FAILED(autoCaller.rc()))
2917 {
2918 /* we might have been uninitialized because the session was accidentally
2919 * closed by the client, so don't assert */
2920 mrc = setError(E_FAIL,
2921 tr("The session has been accidentally closed"));
2922 task.m_pProgress->i_notifyComplete(mrc);
2923 LogFlowThisFuncLeave();
2924 return;
2925 }
2926
2927 MediumDeleteRecList toDelete;
2928 Guid snapshotId;
2929 std::set<ComObjPtr<Medium> > pMediumsForNotify;
2930 std::map<Guid,DeviceType_T> uIdsForNotify;
2931
2932 try
2933 {
2934 HRESULT rc = S_OK;
2935
2936 /* Locking order: */
2937 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2938 task.m_pSnapshot->lockHandle() // snapshot
2939 COMMA_LOCKVAL_SRC_POS);
2940 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2941 // has exited after setting the machine state to MachineState_DeletingSnapshot
2942
2943 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle()
2944 COMMA_LOCKVAL_SRC_POS);
2945
2946 ComObjPtr<SnapshotMachine> pSnapMachine = task.m_pSnapshot->i_getSnapshotMachine();
2947 // no need to lock the snapshot machine since it is const by definition
2948 Guid machineId = pSnapMachine->i_getId();
2949
2950 // save the snapshot ID (for callbacks)
2951 snapshotId = task.m_pSnapshot->i_getId();
2952
2953 // first pass:
2954 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2955
2956 // Go thru the attachments of the snapshot machine (the media in here
2957 // point to the disk states _before_ the snapshot was taken, i.e. the
2958 // state we're restoring to; for each such medium, we will need to
2959 // merge it with its one and only child (the diff image holding the
2960 // changes written after the snapshot was taken).
2961 for (MediumAttachmentList::iterator
2962 it = pSnapMachine->mMediumAttachments->begin();
2963 it != pSnapMachine->mMediumAttachments->end();
2964 ++it)
2965 {
2966 ComObjPtr<MediumAttachment> &pAttach = *it;
2967 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2968 if (pAttach->i_getType() != DeviceType_HardDisk)
2969 continue;
2970
2971 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
2972 Assert(!pHD.isNull());
2973
2974 {
2975 // writethrough, shareable and readonly images are
2976 // unaffected by snapshots, skip them
2977 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
2978 MediumType_T type = pHD->i_getType();
2979 if ( type == MediumType_Writethrough
2980 || type == MediumType_Shareable
2981 || type == MediumType_Readonly)
2982 continue;
2983 }
2984
2985#ifdef DEBUG
2986 pHD->i_dumpBackRefs();
2987#endif
2988
2989 // needs to be merged with child or deleted, check prerequisites
2990 ComObjPtr<Medium> pTarget;
2991 ComObjPtr<Medium> pSource;
2992 bool fMergeForward = false;
2993 ComObjPtr<Medium> pParentForTarget;
2994 MediumLockList *pChildrenToReparent = NULL;
2995 bool fNeedsOnlineMerge = false;
2996 bool fOnlineMergePossible = task.m_fDeleteOnline;
2997 MediumLockList *pMediumLockList = NULL;
2998 MediumLockList *pVMMALockList = NULL;
2999 ComPtr<IToken> pHDLockToken;
3000 ComObjPtr<MediumAttachment> pOnlineMediumAttachment;
3001 if (fOnlineMergePossible)
3002 {
3003 // Look up the corresponding medium attachment in the currently
3004 // running VM. Any failure prevents a live merge. Could be made
3005 // a tad smarter by trying a few candidates, so that e.g. disks
3006 // which are simply moved to a different controller slot do not
3007 // prevent online merging in general.
3008 pOnlineMediumAttachment =
3009 i_findAttachment(*mMediumAttachments.data(),
3010 pAttach->i_getControllerName(),
3011 pAttach->i_getPort(),
3012 pAttach->i_getDevice());
3013 if (pOnlineMediumAttachment)
3014 {
3015 rc = mData->mSession.mLockedMedia.Get(pOnlineMediumAttachment,
3016 pVMMALockList);
3017 if (FAILED(rc))
3018 fOnlineMergePossible = false;
3019 }
3020 else
3021 fOnlineMergePossible = false;
3022 }
3023
3024 // no need to hold the lock any longer
3025 attachLock.release();
3026
3027 treeLock.release();
3028 rc = i_prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
3029 fOnlineMergePossible,
3030 pVMMALockList, pSource, pTarget,
3031 fMergeForward, pParentForTarget,
3032 pChildrenToReparent,
3033 fNeedsOnlineMerge,
3034 pMediumLockList,
3035 pHDLockToken);
3036 treeLock.acquire();
3037 if (FAILED(rc))
3038 throw rc;
3039
3040 // For simplicity, prepareDeleteSnapshotMedium selects the merge
3041 // direction in the following way: we merge pHD onto its child
3042 // (forward merge), not the other way round, because that saves us
3043 // from unnecessarily shuffling around the attachments for the
3044 // machine that follows the snapshot (next snapshot or current
3045 // state), unless it's a base image. Backwards merges of the first
3046 // snapshot into the base image is essential, as it ensures that
3047 // when all snapshots are deleted the only remaining image is a
3048 // base image. Important e.g. for medium formats which do not have
3049 // a file representation such as iSCSI.
3050
3051 // not going to merge a big source into a small target on online merge. Otherwise it will be resized
3052 if (fNeedsOnlineMerge && pSource->i_getLogicalSize() > pTarget->i_getLogicalSize())
3053 {
3054 rc = setError(E_FAIL,
3055 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"),
3056 pTarget->i_getLocationFull().c_str(), pSource->i_getLogicalSize());
3057 throw rc;
3058 }
3059
3060 // a couple paranoia checks for backward merges
3061 if (pMediumLockList != NULL && !fMergeForward)
3062 {
3063 // parent is null -> this disk is a base hard disk: we will
3064 // then do a backward merge, i.e. merge its only child onto the
3065 // base disk. Here we need then to update the attachment that
3066 // refers to the child and have it point to the parent instead
3067 Assert(pHD->i_getChildren().size() == 1);
3068
3069 ComObjPtr<Medium> pReplaceHD = pHD->i_getChildren().front();
3070
3071 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
3072 }
3073
3074 Guid replaceMachineId;
3075 Guid replaceSnapshotId;
3076
3077 const Guid *pReplaceMachineId = pSource->i_getFirstMachineBackrefId();
3078 // minimal sanity checking
3079 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
3080 if (pReplaceMachineId)
3081 replaceMachineId = *pReplaceMachineId;
3082
3083 const Guid *pSnapshotId = pSource->i_getFirstMachineBackrefSnapshotId();
3084 if (pSnapshotId)
3085 replaceSnapshotId = *pSnapshotId;
3086
3087 if (replaceMachineId.isValid() && !replaceMachineId.isZero())
3088 {
3089 // Adjust the backreferences, otherwise merging will assert.
3090 // Note that the medium attachment object stays associated
3091 // with the snapshot until the merge was successful.
3092 HRESULT rc2 = S_OK;
3093 rc2 = pSource->i_removeBackReference(replaceMachineId, replaceSnapshotId);
3094 AssertComRC(rc2);
3095
3096 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
3097 pOnlineMediumAttachment,
3098 fMergeForward,
3099 pParentForTarget,
3100 pChildrenToReparent,
3101 fNeedsOnlineMerge,
3102 pMediumLockList,
3103 pHDLockToken,
3104 replaceMachineId,
3105 replaceSnapshotId));
3106 }
3107 else
3108 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
3109 pOnlineMediumAttachment,
3110 fMergeForward,
3111 pParentForTarget,
3112 pChildrenToReparent,
3113 fNeedsOnlineMerge,
3114 pMediumLockList,
3115 pHDLockToken));
3116 }
3117
3118 {
3119 /* check available space on the storage */
3120 RTFOFF pcbTotal = 0;
3121 RTFOFF pcbFree = 0;
3122 uint32_t pcbBlock = 0;
3123 uint32_t pcbSector = 0;
3124 std::multimap<uint32_t, uint64_t> neededStorageFreeSpace;
3125 std::map<uint32_t, const char*> serialMapToStoragePath;
3126
3127 for (MediumDeleteRecList::const_iterator
3128 it = toDelete.begin();
3129 it != toDelete.end();
3130 ++it)
3131 {
3132 uint64_t diskSize = 0;
3133 uint32_t pu32Serial = 0;
3134 ComObjPtr<Medium> pSource_local = it->mpSource;
3135 ComObjPtr<Medium> pTarget_local = it->mpTarget;
3136 ComPtr<IMediumFormat> pTargetFormat;
3137
3138 {
3139 if ( pSource_local.isNull()
3140 || pSource_local == pTarget_local)
3141 continue;
3142 }
3143
3144 rc = pTarget_local->COMGETTER(MediumFormat)(pTargetFormat.asOutParam());
3145 if (FAILED(rc))
3146 throw rc;
3147
3148 if (pTarget_local->i_isMediumFormatFile())
3149 {
3150 int vrc = RTFsQuerySerial(pTarget_local->i_getLocationFull().c_str(), &pu32Serial);
3151 if (RT_FAILURE(vrc))
3152 {
3153 rc = setError(E_FAIL,
3154 tr("Unable to merge storage '%s'. Can't get storage UID"),
3155 pTarget_local->i_getLocationFull().c_str());
3156 throw rc;
3157 }
3158
3159 pSource_local->COMGETTER(Size)((LONG64*)&diskSize);
3160
3161 /** @todo r=klaus this is too pessimistic... should take
3162 * the current size and maximum size of the target image
3163 * into account, because a X GB image with Y GB capacity
3164 * can only grow by Y-X GB (ignoring overhead, which
3165 * unfortunately is hard to estimate, some have next to
3166 * nothing, some have a certain percentage...) */
3167 /* store needed free space in multimap */
3168 neededStorageFreeSpace.insert(std::make_pair(pu32Serial, diskSize));
3169 /* linking storage UID with snapshot path, it is a helper container (just for easy finding needed path) */
3170 serialMapToStoragePath.insert(std::make_pair(pu32Serial, pTarget_local->i_getLocationFull().c_str()));
3171 }
3172 }
3173
3174 while (!neededStorageFreeSpace.empty())
3175 {
3176 std::pair<std::multimap<uint32_t,uint64_t>::iterator,std::multimap<uint32_t,uint64_t>::iterator> ret;
3177 uint64_t commonSourceStoragesSize = 0;
3178
3179 /* find all records in multimap with identical storage UID */
3180 ret = neededStorageFreeSpace.equal_range(neededStorageFreeSpace.begin()->first);
3181 std::multimap<uint32_t,uint64_t>::const_iterator it_ns = ret.first;
3182
3183 for (; it_ns != ret.second ; ++it_ns)
3184 {
3185 commonSourceStoragesSize += it_ns->second;
3186 }
3187
3188 /* find appropriate path by storage UID */
3189 std::map<uint32_t,const char*>::const_iterator it_sm = serialMapToStoragePath.find(ret.first->first);
3190 /* get info about a storage */
3191 if (it_sm == serialMapToStoragePath.end())
3192 {
3193 LogFlowThisFunc(("Path to the storage wasn't found...\n"));
3194
3195 rc = setError(E_INVALIDARG,
3196 tr("Unable to merge storage '%s'. Path to the storage wasn't found"),
3197 it_sm->second);
3198 throw rc;
3199 }
3200
3201 int vrc = RTFsQuerySizes(it_sm->second, &pcbTotal, &pcbFree, &pcbBlock, &pcbSector);
3202 if (RT_FAILURE(vrc))
3203 {
3204 rc = setError(E_FAIL,
3205 tr("Unable to merge storage '%s'. Can't get the storage size"),
3206 it_sm->second);
3207 throw rc;
3208 }
3209
3210 if (commonSourceStoragesSize > (uint64_t)pcbFree)
3211 {
3212 LogFlowThisFunc(("Not enough free space to merge...\n"));
3213
3214 rc = setError(E_OUTOFMEMORY,
3215 tr("Unable to merge storage '%s'. Not enough free storage space"),
3216 it_sm->second);
3217 throw rc;
3218 }
3219
3220 neededStorageFreeSpace.erase(ret.first, ret.second);
3221 }
3222
3223 serialMapToStoragePath.clear();
3224 }
3225
3226 // we can release the locks now since the machine state is MachineState_DeletingSnapshot
3227 treeLock.release();
3228 multiLock.release();
3229
3230 /* Now we checked that we can successfully merge all normal hard disks
3231 * (unless a runtime error like end-of-disc happens). Now get rid of
3232 * the saved state (if present), as that will free some disk space.
3233 * The snapshot itself will be deleted as late as possible, so that
3234 * the user can repeat the delete operation if he runs out of disk
3235 * space or cancels the delete operation. */
3236
3237 /* second pass: */
3238 LogFlowThisFunc(("2: Deleting saved state...\n"));
3239
3240 {
3241 // saveAllSnapshots() needs a machine lock, and the snapshots
3242 // tree is protected by the machine lock as well
3243 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
3244
3245 Utf8Str stateFilePath = task.m_pSnapshot->i_getStateFilePath();
3246 if (!stateFilePath.isEmpty())
3247 {
3248 task.m_pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")).raw(),
3249 1); // weight
3250
3251 i_releaseSavedStateFile(stateFilePath, task.m_pSnapshot /* pSnapshotToIgnore */);
3252
3253 // machine will need saving now
3254 machineLock.release();
3255 mParent->i_markRegistryModified(i_getId());
3256 }
3257 }
3258
3259 /* third pass: */
3260 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
3261
3262 /// @todo NEWMEDIA turn the following errors into warnings because the
3263 /// snapshot itself has been already deleted (and interpret these
3264 /// warnings properly on the GUI side)
3265 for (MediumDeleteRecList::iterator it = toDelete.begin();
3266 it != toDelete.end();)
3267 {
3268 const ComObjPtr<Medium> &pMedium(it->mpHD);
3269 ULONG ulWeight;
3270
3271 {
3272 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3273 ulWeight = (ULONG)(pMedium->i_getSize() / _1M);
3274 }
3275
3276 const char *pszOperationText = it->mfNeedsOnlineMerge ?
3277 tr("Merging differencing image '%s'")
3278 : tr("Resizing before merge differencing image '%s'");
3279
3280 task.m_pProgress->SetNextOperation(BstrFmt(pszOperationText,
3281 pMedium->i_getName().c_str()).raw(),
3282 ulWeight);
3283
3284 bool fNeedSourceUninit = false;
3285 bool fReparentTarget = false;
3286 if (it->mpMediumLockList == NULL)
3287 {
3288 /* no real merge needed, just updating state and delete
3289 * diff files if necessary */
3290 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
3291
3292 Assert( !it->mfMergeForward
3293 || pMedium->i_getChildren().size() == 0);
3294
3295 /* Delete the differencing hard disk (has no children). Two
3296 * exceptions: if it's the last medium in the chain or if it's
3297 * a backward merge we don't want to handle due to complexity.
3298 * In both cases leave the image in place. If it's the first
3299 * exception the user can delete it later if he wants. */
3300 if (!pMedium->i_getParent().isNull())
3301 {
3302 Assert(pMedium->i_getState() == MediumState_Deleting);
3303 /* No need to hold the lock any longer. */
3304 mLock.release();
3305 ComObjPtr<Medium> pParent = pMedium->i_getParent();
3306 Guid uMedium = pMedium->i_getId();
3307 DeviceType_T uMediumType = pMedium->i_getDeviceType();
3308 rc = pMedium->i_deleteStorage(&task.m_pProgress,
3309 true /* aWait */,
3310 false /* aNotify */);
3311 if (FAILED(rc))
3312 throw rc;
3313
3314 pMediumsForNotify.insert(pParent);
3315 uIdsForNotify[uMedium] = uMediumType;
3316
3317 // need to uninit the deleted medium
3318 fNeedSourceUninit = true;
3319 }
3320 }
3321 else
3322 {
3323 {
3324 //store ids before merging for notify
3325 pMediumsForNotify.insert(it->mpTarget);
3326 if (it->mfMergeForward)
3327 pMediumsForNotify.insert(it->mpSource->i_getParent());
3328 else
3329 {
3330 //children which will be reparented to target
3331 for (MediaList::const_iterator iit = it->mpSource->i_getChildren().begin();
3332 iit != it->mpSource->i_getChildren().end();
3333 ++iit)
3334 {
3335 pMediumsForNotify.insert(*iit);
3336 }
3337 }
3338 if (it->mfMergeForward)
3339 {
3340 for (ComObjPtr<Medium> pTmpMedium = it->mpTarget->i_getParent();
3341 pTmpMedium && pTmpMedium != it->mpSource;
3342 pTmpMedium = pTmpMedium->i_getParent())
3343 {
3344 uIdsForNotify[pTmpMedium->i_getId()] = pTmpMedium->i_getDeviceType();
3345 }
3346 uIdsForNotify[it->mpSource->i_getId()] = it->mpSource->i_getDeviceType();
3347 }
3348 else
3349 {
3350 for (ComObjPtr<Medium> pTmpMedium = it->mpSource;
3351 pTmpMedium && pTmpMedium != it->mpTarget;
3352 pTmpMedium = pTmpMedium->i_getParent())
3353 {
3354 uIdsForNotify[pTmpMedium->i_getId()] = pTmpMedium->i_getDeviceType();
3355 }
3356 }
3357 }
3358
3359 bool fNeedsSave = false;
3360 if (it->mfNeedsOnlineMerge)
3361 {
3362 // Put the medium merge information (MediumDeleteRec) where
3363 // SessionMachine::FinishOnlineMergeMedium can get at it.
3364 // This callback will arrive while onlineMergeMedium is
3365 // still executing, and there can't be two tasks.
3366 /// @todo r=klaus this hack needs to go, and the logic needs to be "unconvoluted", putting SessionMachine in charge of coordinating the reconfig/resume.
3367 mConsoleTaskData.mDeleteSnapshotInfo = (void *)&(*it);
3368 // online medium merge, in the direction decided earlier
3369 rc = i_onlineMergeMedium(it->mpOnlineMediumAttachment,
3370 it->mpSource,
3371 it->mpTarget,
3372 it->mfMergeForward,
3373 it->mpParentForTarget,
3374 it->mpChildrenToReparent,
3375 it->mpMediumLockList,
3376 task.m_pProgress,
3377 &fNeedsSave);
3378 mConsoleTaskData.mDeleteSnapshotInfo = NULL;
3379 }
3380 else
3381 {
3382 // normal medium merge, in the direction decided earlier
3383 rc = it->mpSource->i_mergeTo(it->mpTarget,
3384 it->mfMergeForward,
3385 it->mpParentForTarget,
3386 it->mpChildrenToReparent,
3387 it->mpMediumLockList,
3388 &task.m_pProgress,
3389 true /* aWait */,
3390 false /* aNotify */);
3391 }
3392
3393 // If the merge failed, we need to do our best to have a usable
3394 // VM configuration afterwards. The return code doesn't tell
3395 // whether the merge completed and so we have to check if the
3396 // source medium (diff images are always file based at the
3397 // moment) is still there or not. Be careful not to lose the
3398 // error code below, before the "Delayed failure exit".
3399 if (FAILED(rc))
3400 {
3401 AutoReadLock mlock(it->mpSource COMMA_LOCKVAL_SRC_POS);
3402 if (!it->mpSource->i_isMediumFormatFile())
3403 // Diff medium not backed by a file - cannot get status so
3404 // be pessimistic.
3405 throw rc;
3406 const Utf8Str &loc = it->mpSource->i_getLocationFull();
3407 // Source medium is still there, so merge failed early.
3408 if (RTFileExists(loc.c_str()))
3409 throw rc;
3410
3411 // Source medium is gone. Assume the merge succeeded and
3412 // thus it's safe to remove the attachment. We use the
3413 // "Delayed failure exit" below.
3414 }
3415
3416 // need to change the medium attachment for backward merges
3417 fReparentTarget = !it->mfMergeForward;
3418
3419 if (!it->mfNeedsOnlineMerge)
3420 {
3421 // need to uninit the medium deleted by the merge
3422 fNeedSourceUninit = true;
3423
3424 // delete the no longer needed medium lock list, which
3425 // implicitly handled the unlocking
3426 delete it->mpMediumLockList;
3427 it->mpMediumLockList = NULL;
3428 }
3429 }
3430
3431 // Now that the medium is successfully merged/deleted/whatever,
3432 // remove the medium attachment from the snapshot. For a backwards
3433 // merge the target attachment needs to be removed from the
3434 // snapshot, as the VM will take it over. For forward merges the
3435 // source medium attachment needs to be removed.
3436 ComObjPtr<MediumAttachment> pAtt;
3437 if (fReparentTarget)
3438 {
3439 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3440 it->mpTarget);
3441 it->mpTarget->i_removeBackReference(machineId, snapshotId);
3442 }
3443 else
3444 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3445 it->mpSource);
3446 pSnapMachine->mMediumAttachments->remove(pAtt);
3447
3448 if (fReparentTarget)
3449 {
3450 // Search for old source attachment and replace with target.
3451 // There can be only one child snapshot in this case.
3452 ComObjPtr<Machine> pMachine = this;
3453 Guid childSnapshotId;
3454 ComObjPtr<Snapshot> pChildSnapshot = task.m_pSnapshot->i_getFirstChild();
3455 if (pChildSnapshot)
3456 {
3457 pMachine = pChildSnapshot->i_getSnapshotMachine();
3458 childSnapshotId = pChildSnapshot->i_getId();
3459 }
3460 pAtt = i_findAttachment(*(pMachine->mMediumAttachments).data(), it->mpSource);
3461 if (pAtt)
3462 {
3463 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
3464 pAtt->i_updateMedium(it->mpTarget);
3465 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3466 }
3467 else
3468 {
3469 // If no attachment is found do not change anything. Maybe
3470 // the source medium was not attached to the snapshot.
3471 // If this is an online deletion the attachment was updated
3472 // already to allow the VM continue execution immediately.
3473 // Needs a bit of special treatment due to this difference.
3474 if (it->mfNeedsOnlineMerge)
3475 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3476 }
3477 }
3478
3479 if (fNeedSourceUninit)
3480 {
3481 // make sure that the diff image to be deleted has no parent,
3482 // even in error cases (where the deparenting may be missing)
3483 if (it->mpSource->i_getParent())
3484 it->mpSource->i_deparent();
3485 it->mpSource->uninit();
3486 }
3487
3488 // One attachment is merged, must save the settings
3489 mParent->i_markRegistryModified(i_getId());
3490
3491 // prevent calling cancelDeleteSnapshotMedium() for this attachment
3492 it = toDelete.erase(it);
3493
3494 // Delayed failure exit when the merge cleanup failed but the
3495 // merge actually succeeded.
3496 if (FAILED(rc))
3497 throw rc;
3498 }
3499
3500 /* 3a: delete NVRAM file if present. */
3501 {
3502 Utf8Str NVRAMPath = pSnapMachine->mBIOSSettings->i_getNonVolatileStorageFile();
3503 if (NVRAMPath.isNotEmpty() && RTFileExists(NVRAMPath.c_str()))
3504 RTFileDelete(NVRAMPath.c_str());
3505 }
3506
3507 /* third pass: */
3508 {
3509 // beginSnapshotDelete() needs the machine lock, and the snapshots
3510 // tree is protected by the machine lock as well
3511 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
3512
3513 task.m_pSnapshot->i_beginSnapshotDelete();
3514 task.m_pSnapshot->uninit();
3515
3516 machineLock.release();
3517 mParent->i_markRegistryModified(i_getId());
3518 }
3519 }
3520 catch (HRESULT aRC) {
3521 mrc = aRC;
3522 }
3523
3524 if (FAILED(mrc))
3525 {
3526 // preserve existing error info so that the result can
3527 // be properly reported to the progress object below
3528 ErrorInfoKeeper eik;
3529
3530 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
3531 &mParent->i_getMediaTreeLockHandle() // media tree
3532 COMMA_LOCKVAL_SRC_POS);
3533
3534 // un-prepare the remaining hard disks
3535 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
3536 it != toDelete.end();
3537 ++it)
3538 i_cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
3539 it->mpChildrenToReparent,
3540 it->mfNeedsOnlineMerge,
3541 it->mpMediumLockList, it->mpHDLockToken,
3542 it->mMachineId, it->mSnapshotId);
3543 }
3544
3545 // whether we were successful or not, we need to set the machine
3546 // state and save the machine settings;
3547 {
3548 // preserve existing error info so that the result can
3549 // be properly reported to the progress object below
3550 ErrorInfoKeeper eik;
3551
3552 // restore the machine state that was saved when the
3553 // task was started
3554 i_setMachineState(task.m_machineStateBackup);
3555 if (Global::IsOnline(mData->mMachineState))
3556 i_updateMachineStateOnClient();
3557
3558 mParent->i_saveModifiedRegistries();
3559 }
3560
3561 // report the result (this will try to fetch current error info on failure)
3562 task.m_pProgress->i_notifyComplete(mrc);
3563
3564 if (SUCCEEDED(mrc))
3565 {
3566 mParent->i_onSnapshotDeleted(mData->mUuid, snapshotId);
3567 for (std::map<Guid, DeviceType_T>::const_iterator it = uIdsForNotify.begin();
3568 it != uIdsForNotify.end();
3569 ++it)
3570 {
3571 mParent->i_onMediumRegistered(it->first, it->second, FALSE);
3572 }
3573 for (std::set<ComObjPtr<Medium> >::const_iterator it = pMediumsForNotify.begin();
3574 it != pMediumsForNotify.end();
3575 ++it)
3576 {
3577 if (it->isNotNull())
3578 mParent->i_onMediumConfigChanged(*it);
3579 }
3580 }
3581
3582 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", (HRESULT)mrc));
3583 LogFlowThisFuncLeave();
3584}
3585
3586/**
3587 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
3588 * performs necessary state changes. Must not be called for writethrough disks
3589 * because there is nothing to delete/merge then.
3590 *
3591 * This method is to be called prior to calling #deleteSnapshotMedium().
3592 * If #deleteSnapshotMedium() is not called or fails, the state modifications
3593 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
3594 *
3595 * @return COM status code
3596 * @param aHD Hard disk which is connected to the snapshot.
3597 * @param aMachineId UUID of machine this hard disk is attached to.
3598 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
3599 * be a zero UUID if no snapshot is applicable.
3600 * @param fOnlineMergePossible Flag whether an online merge is possible.
3601 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
3602 * Only used if @a fOnlineMergePossible is @c true, and
3603 * must be non-NULL in this case.
3604 * @param aSource Source hard disk for merge (out).
3605 * @param aTarget Target hard disk for merge (out).
3606 * @param aMergeForward Merge direction decision (out).
3607 * @param aParentForTarget New parent if target needs to be reparented (out).
3608 * @param aChildrenToReparent MediumLockList with children which have to be
3609 * reparented to the target (out).
3610 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
3611 * If this is set to @a true then the @a aVMMALockList
3612 * parameter has been modified and is returned as
3613 * @a aMediumLockList.
3614 * @param aMediumLockList Where to store the created medium lock list (may
3615 * return NULL if no real merge is necessary).
3616 * @param aHDLockToken Where to store the write lock token for aHD, in case
3617 * it is not merged or deleted (out).
3618 *
3619 * @note Caller must hold media tree lock for writing. This locks this object
3620 * and every medium object on the merge chain for writing.
3621 */
3622HRESULT SessionMachine::i_prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3623 const Guid &aMachineId,
3624 const Guid &aSnapshotId,
3625 bool fOnlineMergePossible,
3626 MediumLockList *aVMMALockList,
3627 ComObjPtr<Medium> &aSource,
3628 ComObjPtr<Medium> &aTarget,
3629 bool &aMergeForward,
3630 ComObjPtr<Medium> &aParentForTarget,
3631 MediumLockList * &aChildrenToReparent,
3632 bool &fNeedsOnlineMerge,
3633 MediumLockList * &aMediumLockList,
3634 ComPtr<IToken> &aHDLockToken)
3635{
3636 Assert(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3637 Assert(!fOnlineMergePossible || RT_VALID_PTR(aVMMALockList));
3638
3639 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
3640
3641 // Medium must not be writethrough/shareable/readonly at this point
3642 MediumType_T type = aHD->i_getType();
3643 AssertReturn( type != MediumType_Writethrough
3644 && type != MediumType_Shareable
3645 && type != MediumType_Readonly, E_FAIL);
3646
3647 aChildrenToReparent = NULL;
3648 aMediumLockList = NULL;
3649 fNeedsOnlineMerge = false;
3650
3651 if (aHD->i_getChildren().size() == 0)
3652 {
3653 /* This technically is no merge, set those values nevertheless.
3654 * Helps with updating the medium attachments. */
3655 aSource = aHD;
3656 aTarget = aHD;
3657
3658 /* special treatment of the last hard disk in the chain: */
3659 if (aHD->i_getParent().isNull())
3660 {
3661 /* lock only, to prevent any usage until the snapshot deletion
3662 * is completed */
3663 alock.release();
3664 return aHD->LockWrite(aHDLockToken.asOutParam());
3665 }
3666
3667 /* the differencing hard disk w/o children will be deleted, protect it
3668 * from attaching to other VMs (this is why Deleting) */
3669 return aHD->i_markForDeletion();
3670 }
3671
3672 /* not going multi-merge as it's too expensive */
3673 if (aHD->i_getChildren().size() > 1)
3674 return setError(E_FAIL,
3675 tr("Hard disk '%s' has more than one child hard disk (%d)"),
3676 aHD->i_getLocationFull().c_str(),
3677 aHD->i_getChildren().size());
3678
3679 ComObjPtr<Medium> pChild = aHD->i_getChildren().front();
3680
3681 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
3682
3683 /* the rest is a normal merge setup */
3684 if (aHD->i_getParent().isNull())
3685 {
3686 /* base hard disk, backward merge */
3687 const Guid *pMachineId1 = pChild->i_getFirstMachineBackrefId();
3688 const Guid *pMachineId2 = aHD->i_getFirstMachineBackrefId();
3689 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
3690 {
3691 /* backward merge is too tricky, we'll just detach on snapshot
3692 * deletion, so lock only, to prevent any usage */
3693 childLock.release();
3694 alock.release();
3695 return aHD->LockWrite(aHDLockToken.asOutParam());
3696 }
3697
3698 aSource = pChild;
3699 aTarget = aHD;
3700 }
3701 else
3702 {
3703 /* Determine best merge direction. */
3704 bool fMergeForward = true;
3705
3706 childLock.release();
3707 alock.release();
3708 HRESULT rc = aHD->i_queryPreferredMergeDirection(pChild, fMergeForward);
3709 alock.acquire();
3710 childLock.acquire();
3711
3712 if (FAILED(rc) && rc != E_FAIL)
3713 return rc;
3714
3715 if (fMergeForward)
3716 {
3717 aSource = aHD;
3718 aTarget = pChild;
3719 LogFlowThisFunc(("Forward merging selected\n"));
3720 }
3721 else
3722 {
3723 aSource = pChild;
3724 aTarget = aHD;
3725 LogFlowThisFunc(("Backward merging selected\n"));
3726 }
3727 }
3728
3729 HRESULT rc;
3730 childLock.release();
3731 alock.release();
3732 rc = aSource->i_prepareMergeTo(aTarget, &aMachineId, &aSnapshotId,
3733 !fOnlineMergePossible /* fLockMedia */,
3734 aMergeForward, aParentForTarget,
3735 aChildrenToReparent, aMediumLockList);
3736 alock.acquire();
3737 childLock.acquire();
3738 if (SUCCEEDED(rc) && fOnlineMergePossible)
3739 {
3740 /* Try to lock the newly constructed medium lock list. If it succeeds
3741 * this can be handled as an offline merge, i.e. without the need of
3742 * asking the VM to do the merging. Only continue with the online
3743 * merging preparation if applicable. */
3744 childLock.release();
3745 alock.release();
3746 rc = aMediumLockList->Lock();
3747 alock.acquire();
3748 childLock.acquire();
3749 if (FAILED(rc))
3750 {
3751 /* Locking failed, this cannot be done as an offline merge. Try to
3752 * combine the locking information into the lock list of the medium
3753 * attachment in the running VM. If that fails or locking the
3754 * resulting lock list fails then the merge cannot be done online.
3755 * It can be repeated by the user when the VM is shut down. */
3756 MediumLockList::Base::iterator lockListVMMABegin =
3757 aVMMALockList->GetBegin();
3758 MediumLockList::Base::iterator lockListVMMAEnd =
3759 aVMMALockList->GetEnd();
3760 MediumLockList::Base::iterator lockListBegin =
3761 aMediumLockList->GetBegin();
3762 MediumLockList::Base::iterator lockListEnd =
3763 aMediumLockList->GetEnd();
3764 for (MediumLockList::Base::iterator it = lockListVMMABegin,
3765 it2 = lockListBegin;
3766 it2 != lockListEnd;
3767 ++it, ++it2)
3768 {
3769 if ( it == lockListVMMAEnd
3770 || it->GetMedium() != it2->GetMedium())
3771 {
3772 fOnlineMergePossible = false;
3773 break;
3774 }
3775 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
3776 childLock.release();
3777 alock.release();
3778 rc = it->UpdateLock(fLockReq);
3779 alock.acquire();
3780 childLock.acquire();
3781 if (FAILED(rc))
3782 {
3783 // could not update the lock, trigger cleanup below
3784 fOnlineMergePossible = false;
3785 break;
3786 }
3787 }
3788
3789 if (fOnlineMergePossible)
3790 {
3791 /* we will lock the children of the source for reparenting */
3792 if (aChildrenToReparent && !aChildrenToReparent->IsEmpty())
3793 {
3794 /* Cannot just call aChildrenToReparent->Lock(), as one of
3795 * the children is the one under which the current state of
3796 * the VM is located, and this means it is already locked
3797 * (for reading). Note that no special unlocking is needed,
3798 * because cancelMergeTo will unlock everything locked in
3799 * its context (using the unlock on destruction), and both
3800 * cancelDeleteSnapshotMedium (in case something fails) and
3801 * FinishOnlineMergeMedium re-define the read/write lock
3802 * state of everything which the VM need, search for the
3803 * UpdateLock method calls. */
3804 childLock.release();
3805 alock.release();
3806 rc = aChildrenToReparent->Lock(true /* fSkipOverLockedMedia */);
3807 alock.acquire();
3808 childLock.acquire();
3809 MediumLockList::Base::iterator childrenToReparentBegin = aChildrenToReparent->GetBegin();
3810 MediumLockList::Base::iterator childrenToReparentEnd = aChildrenToReparent->GetEnd();
3811 for (MediumLockList::Base::iterator it = childrenToReparentBegin;
3812 it != childrenToReparentEnd;
3813 ++it)
3814 {
3815 ComObjPtr<Medium> pMedium = it->GetMedium();
3816 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3817 if (!it->IsLocked())
3818 {
3819 mediumLock.release();
3820 childLock.release();
3821 alock.release();
3822 rc = aVMMALockList->Update(pMedium, true);
3823 alock.acquire();
3824 childLock.acquire();
3825 mediumLock.acquire();
3826 if (FAILED(rc))
3827 throw rc;
3828 }
3829 }
3830 }
3831 }
3832
3833 if (fOnlineMergePossible)
3834 {
3835 childLock.release();
3836 alock.release();
3837 rc = aVMMALockList->Lock();
3838 alock.acquire();
3839 childLock.acquire();
3840 if (FAILED(rc))
3841 {
3842 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3843 rc = setError(rc,
3844 tr("Cannot lock hard disk '%s' for a live merge"),
3845 aHD->i_getLocationFull().c_str());
3846 }
3847 else
3848 {
3849 delete aMediumLockList;
3850 aMediumLockList = aVMMALockList;
3851 fNeedsOnlineMerge = true;
3852 }
3853 }
3854 else
3855 {
3856 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3857 rc = setError(rc,
3858 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
3859 aHD->i_getLocationFull().c_str());
3860 }
3861
3862 // fix the VM's lock list if anything failed
3863 if (FAILED(rc))
3864 {
3865 lockListVMMABegin = aVMMALockList->GetBegin();
3866 lockListVMMAEnd = aVMMALockList->GetEnd();
3867 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
3868 --lockListLast;
3869 for (MediumLockList::Base::iterator it = lockListVMMABegin;
3870 it != lockListVMMAEnd;
3871 ++it)
3872 {
3873 childLock.release();
3874 alock.release();
3875 it->UpdateLock(it == lockListLast);
3876 alock.acquire();
3877 childLock.acquire();
3878 ComObjPtr<Medium> pMedium = it->GetMedium();
3879 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3880 // blindly apply this, only needed for medium objects which
3881 // would be deleted as part of the merge
3882 pMedium->i_unmarkLockedForDeletion();
3883 }
3884 }
3885 }
3886 }
3887 else if (FAILED(rc))
3888 {
3889 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3890 rc = setError(rc,
3891 tr("Cannot lock hard disk '%s' when deleting a snapshot"),
3892 aHD->i_getLocationFull().c_str());
3893 }
3894
3895 return rc;
3896}
3897
3898/**
3899 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
3900 * what #prepareDeleteSnapshotMedium() did. Must be called if
3901 * #deleteSnapshotMedium() is not called or fails.
3902 *
3903 * @param aHD Hard disk which is connected to the snapshot.
3904 * @param aSource Source hard disk for merge.
3905 * @param aChildrenToReparent Children to unlock.
3906 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
3907 * @param aMediumLockList Medium locks to cancel.
3908 * @param aHDLockToken Optional write lock token for aHD.
3909 * @param aMachineId Machine id to attach the medium to.
3910 * @param aSnapshotId Snapshot id to attach the medium to.
3911 *
3912 * @note Locks the medium tree and the hard disks in the chain for writing.
3913 */
3914void SessionMachine::i_cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3915 const ComObjPtr<Medium> &aSource,
3916 MediumLockList *aChildrenToReparent,
3917 bool fNeedsOnlineMerge,
3918 MediumLockList *aMediumLockList,
3919 const ComPtr<IToken> &aHDLockToken,
3920 const Guid &aMachineId,
3921 const Guid &aSnapshotId)
3922{
3923 if (aMediumLockList == NULL)
3924 {
3925 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
3926
3927 Assert(aHD->i_getChildren().size() == 0);
3928
3929 if (aHD->i_getParent().isNull())
3930 {
3931 Assert(!aHDLockToken.isNull());
3932 if (!aHDLockToken.isNull())
3933 {
3934 HRESULT rc = aHDLockToken->Abandon();
3935 AssertComRC(rc);
3936 }
3937 }
3938 else
3939 {
3940 HRESULT rc = aHD->i_unmarkForDeletion();
3941 AssertComRC(rc);
3942 }
3943 }
3944 else
3945 {
3946 if (fNeedsOnlineMerge)
3947 {
3948 // Online merge uses the medium lock list of the VM, so give
3949 // an empty list to cancelMergeTo so that it works as designed.
3950 aSource->i_cancelMergeTo(aChildrenToReparent, new MediumLockList());
3951
3952 // clean up the VM medium lock list ourselves
3953 MediumLockList::Base::iterator lockListBegin =
3954 aMediumLockList->GetBegin();
3955 MediumLockList::Base::iterator lockListEnd =
3956 aMediumLockList->GetEnd();
3957 MediumLockList::Base::iterator lockListLast = lockListEnd;
3958 --lockListLast;
3959 for (MediumLockList::Base::iterator it = lockListBegin;
3960 it != lockListEnd;
3961 ++it)
3962 {
3963 ComObjPtr<Medium> pMedium = it->GetMedium();
3964 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3965 if (pMedium->i_getState() == MediumState_Deleting)
3966 pMedium->i_unmarkForDeletion();
3967 else
3968 {
3969 // blindly apply this, only needed for medium objects which
3970 // would be deleted as part of the merge
3971 pMedium->i_unmarkLockedForDeletion();
3972 }
3973 mediumLock.release();
3974 it->UpdateLock(it == lockListLast);
3975 mediumLock.acquire();
3976 }
3977 }
3978 else
3979 {
3980 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3981 }
3982 }
3983
3984 if (aMachineId.isValid() && !aMachineId.isZero())
3985 {
3986 // reattach the source media to the snapshot
3987 HRESULT rc = aSource->i_addBackReference(aMachineId, aSnapshotId);
3988 AssertComRC(rc);
3989 }
3990}
3991
3992/**
3993 * Perform an online merge of a hard disk, i.e. the equivalent of
3994 * Medium::mergeTo(), just for running VMs. If this fails you need to call
3995 * #cancelDeleteSnapshotMedium().
3996 *
3997 * @return COM status code
3998 * @param aMediumAttachment Identify where the disk is attached in the VM.
3999 * @param aSource Source hard disk for merge.
4000 * @param aTarget Target hard disk for merge.
4001 * @param fMergeForward Merge direction.
4002 * @param aParentForTarget New parent if target needs to be reparented.
4003 * @param aChildrenToReparent Medium lock list with children which have to be
4004 * reparented to the target.
4005 * @param aMediumLockList Where to store the created medium lock list (may
4006 * return NULL if no real merge is necessary).
4007 * @param aProgress Progress indicator.
4008 * @param pfNeedsMachineSaveSettings Whether the VM settings need to be saved (out).
4009 */
4010HRESULT SessionMachine::i_onlineMergeMedium(const ComObjPtr<MediumAttachment> &aMediumAttachment,
4011 const ComObjPtr<Medium> &aSource,
4012 const ComObjPtr<Medium> &aTarget,
4013 bool fMergeForward,
4014 const ComObjPtr<Medium> &aParentForTarget,
4015 MediumLockList *aChildrenToReparent,
4016 MediumLockList *aMediumLockList,
4017 ComObjPtr<Progress> &aProgress,
4018 bool *pfNeedsMachineSaveSettings)
4019{
4020 AssertReturn(aSource != NULL, E_FAIL);
4021 AssertReturn(aTarget != NULL, E_FAIL);
4022 AssertReturn(aSource != aTarget, E_FAIL);
4023 AssertReturn(aMediumLockList != NULL, E_FAIL);
4024 NOREF(fMergeForward);
4025 NOREF(aParentForTarget);
4026 NOREF(aChildrenToReparent);
4027
4028 HRESULT rc = S_OK;
4029
4030 try
4031 {
4032 // Similar code appears in Medium::taskMergeHandle, so
4033 // if you make any changes below check whether they are applicable
4034 // in that context as well.
4035
4036 unsigned uTargetIdx = (unsigned)-1;
4037 unsigned uSourceIdx = (unsigned)-1;
4038 /* Sanity check all hard disks in the chain. */
4039 MediumLockList::Base::iterator lockListBegin =
4040 aMediumLockList->GetBegin();
4041 MediumLockList::Base::iterator lockListEnd =
4042 aMediumLockList->GetEnd();
4043 unsigned i = 0;
4044 for (MediumLockList::Base::iterator it = lockListBegin;
4045 it != lockListEnd;
4046 ++it)
4047 {
4048 MediumLock &mediumLock = *it;
4049 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4050
4051 if (pMedium == aSource)
4052 uSourceIdx = i;
4053 else if (pMedium == aTarget)
4054 uTargetIdx = i;
4055
4056 // In Medium::taskMergeHandler there is lots of consistency
4057 // checking which we cannot do here, as the state details are
4058 // impossible to get outside the Medium class. The locking should
4059 // have done the checks already.
4060
4061 i++;
4062 }
4063
4064 ComAssertThrow( uSourceIdx != (unsigned)-1
4065 && uTargetIdx != (unsigned)-1, E_FAIL);
4066
4067 ComPtr<IInternalSessionControl> directControl;
4068 {
4069 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4070
4071 if (mData->mSession.mState != SessionState_Locked)
4072 throw setError(VBOX_E_INVALID_VM_STATE,
4073 tr("Machine is not locked by a session (session state: %s)"),
4074 Global::stringifySessionState(mData->mSession.mState));
4075 directControl = mData->mSession.mDirectControl;
4076 }
4077
4078 // Must not hold any locks here, as this will call back to finish
4079 // updating the medium attachment, chain linking and state.
4080 rc = directControl->OnlineMergeMedium(aMediumAttachment,
4081 uSourceIdx, uTargetIdx,
4082 aProgress);
4083 if (FAILED(rc))
4084 throw rc;
4085 }
4086 catch (HRESULT aRC) { rc = aRC; }
4087
4088 // The callback mentioned above takes care of update the medium state
4089
4090 if (pfNeedsMachineSaveSettings)
4091 *pfNeedsMachineSaveSettings = true;
4092
4093 return rc;
4094}
4095
4096/**
4097 * Implementation for IInternalMachineControl::finishOnlineMergeMedium().
4098 *
4099 * Gets called after the successful completion of an online merge from
4100 * Console::onlineMergeMedium(), which gets invoked indirectly above in
4101 * the call to IInternalSessionControl::onlineMergeMedium.
4102 *
4103 * This updates the medium information and medium state so that the VM
4104 * can continue with the updated state of the medium chain.
4105 */
4106HRESULT SessionMachine::finishOnlineMergeMedium()
4107{
4108 HRESULT rc = S_OK;
4109 MediumDeleteRec *pDeleteRec = (MediumDeleteRec *)mConsoleTaskData.mDeleteSnapshotInfo;
4110 AssertReturn(pDeleteRec, E_FAIL);
4111 bool fSourceHasChildren = false;
4112
4113 // all hard disks but the target were successfully deleted by
4114 // the merge; reparent target if necessary and uninitialize media
4115
4116 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4117
4118 // Declare this here to make sure the object does not get uninitialized
4119 // before this method completes. Would normally happen as halfway through
4120 // we delete the last reference to the no longer existing medium object.
4121 ComObjPtr<Medium> targetChild;
4122
4123 if (pDeleteRec->mfMergeForward)
4124 {
4125 // first, unregister the target since it may become a base
4126 // hard disk which needs re-registration
4127 rc = mParent->i_unregisterMedium(pDeleteRec->mpTarget);
4128 AssertComRC(rc);
4129
4130 // then, reparent it and disconnect the deleted branch at
4131 // both ends (chain->parent() is source's parent)
4132 pDeleteRec->mpTarget->i_deparent();
4133 pDeleteRec->mpTarget->i_setParent(pDeleteRec->mpParentForTarget);
4134 if (pDeleteRec->mpParentForTarget)
4135 pDeleteRec->mpSource->i_deparent();
4136
4137 // then, register again
4138 rc = mParent->i_registerMedium(pDeleteRec->mpTarget, &pDeleteRec->mpTarget, treeLock);
4139 AssertComRC(rc);
4140 }
4141 else
4142 {
4143 Assert(pDeleteRec->mpTarget->i_getChildren().size() == 1);
4144 targetChild = pDeleteRec->mpTarget->i_getChildren().front();
4145
4146 // disconnect the deleted branch at the elder end
4147 targetChild->i_deparent();
4148
4149 // Update parent UUIDs of the source's children, reparent them and
4150 // disconnect the deleted branch at the younger end
4151 if (pDeleteRec->mpChildrenToReparent && !pDeleteRec->mpChildrenToReparent->IsEmpty())
4152 {
4153 fSourceHasChildren = true;
4154 // Fix the parent UUID of the images which needs to be moved to
4155 // underneath target. The running machine has the images opened,
4156 // but only for reading since the VM is paused. If anything fails
4157 // we must continue. The worst possible result is that the images
4158 // need manual fixing via VBoxManage to adjust the parent UUID.
4159 treeLock.release();
4160 pDeleteRec->mpTarget->i_fixParentUuidOfChildren(pDeleteRec->mpChildrenToReparent);
4161 // The childen are still write locked, unlock them now and don't
4162 // rely on the destructor doing it very late.
4163 pDeleteRec->mpChildrenToReparent->Unlock();
4164 treeLock.acquire();
4165
4166 // obey {parent,child} lock order
4167 AutoWriteLock sourceLock(pDeleteRec->mpSource COMMA_LOCKVAL_SRC_POS);
4168
4169 MediumLockList::Base::iterator childrenBegin = pDeleteRec->mpChildrenToReparent->GetBegin();
4170 MediumLockList::Base::iterator childrenEnd = pDeleteRec->mpChildrenToReparent->GetEnd();
4171 for (MediumLockList::Base::iterator it = childrenBegin;
4172 it != childrenEnd;
4173 ++it)
4174 {
4175 Medium *pMedium = it->GetMedium();
4176 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
4177
4178 pMedium->i_deparent(); // removes pMedium from source
4179 pMedium->i_setParent(pDeleteRec->mpTarget);
4180 }
4181 }
4182 }
4183
4184 /* unregister and uninitialize all hard disks removed by the merge */
4185 MediumLockList *pMediumLockList = NULL;
4186 rc = mData->mSession.mLockedMedia.Get(pDeleteRec->mpOnlineMediumAttachment, pMediumLockList);
4187 const ComObjPtr<Medium> &pLast = pDeleteRec->mfMergeForward ? pDeleteRec->mpTarget : pDeleteRec->mpSource;
4188 AssertReturn(SUCCEEDED(rc) && pMediumLockList, E_FAIL);
4189 MediumLockList::Base::iterator lockListBegin =
4190 pMediumLockList->GetBegin();
4191 MediumLockList::Base::iterator lockListEnd =
4192 pMediumLockList->GetEnd();
4193 for (MediumLockList::Base::iterator it = lockListBegin;
4194 it != lockListEnd;
4195 )
4196 {
4197 MediumLock &mediumLock = *it;
4198 /* Create a real copy of the medium pointer, as the medium
4199 * lock deletion below would invalidate the referenced object. */
4200 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
4201
4202 /* The target and all images not merged (readonly) are skipped */
4203 if ( pMedium == pDeleteRec->mpTarget
4204 || pMedium->i_getState() == MediumState_LockedRead)
4205 {
4206 ++it;
4207 }
4208 else
4209 {
4210 rc = mParent->i_unregisterMedium(pMedium);
4211 AssertComRC(rc);
4212
4213 /* now, uninitialize the deleted hard disk (note that
4214 * due to the Deleting state, uninit() will not touch
4215 * the parent-child relationship so we need to
4216 * uninitialize each disk individually) */
4217
4218 /* note that the operation initiator hard disk (which is
4219 * normally also the source hard disk) is a special case
4220 * -- there is one more caller added by Task to it which
4221 * we must release. Also, if we are in sync mode, the
4222 * caller may still hold an AutoCaller instance for it
4223 * and therefore we cannot uninit() it (it's therefore
4224 * the caller's responsibility) */
4225 if (pMedium == pDeleteRec->mpSource)
4226 {
4227 Assert(pDeleteRec->mpSource->i_getChildren().size() == 0);
4228 Assert(pDeleteRec->mpSource->i_getFirstMachineBackrefId() == NULL);
4229 }
4230
4231 /* Delete the medium lock list entry, which also releases the
4232 * caller added by MergeChain before uninit() and updates the
4233 * iterator to point to the right place. */
4234 rc = pMediumLockList->RemoveByIterator(it);
4235 AssertComRC(rc);
4236
4237 treeLock.release();
4238 pMedium->uninit();
4239 treeLock.acquire();
4240 }
4241
4242 /* Stop as soon as we reached the last medium affected by the merge.
4243 * The remaining images must be kept unchanged. */
4244 if (pMedium == pLast)
4245 break;
4246 }
4247
4248 /* Could be in principle folded into the previous loop, but let's keep
4249 * things simple. Update the medium locking to be the standard state:
4250 * all parent images locked for reading, just the last diff for writing. */
4251 lockListBegin = pMediumLockList->GetBegin();
4252 lockListEnd = pMediumLockList->GetEnd();
4253 MediumLockList::Base::iterator lockListLast = lockListEnd;
4254 --lockListLast;
4255 for (MediumLockList::Base::iterator it = lockListBegin;
4256 it != lockListEnd;
4257 ++it)
4258 {
4259 it->UpdateLock(it == lockListLast);
4260 }
4261
4262 /* If this is a backwards merge of the only remaining snapshot (i.e. the
4263 * source has no children) then update the medium associated with the
4264 * attachment, as the previously associated one (source) is now deleted.
4265 * Without the immediate update the VM could not continue running. */
4266 if (!pDeleteRec->mfMergeForward && !fSourceHasChildren)
4267 {
4268 AutoWriteLock attLock(pDeleteRec->mpOnlineMediumAttachment COMMA_LOCKVAL_SRC_POS);
4269 pDeleteRec->mpOnlineMediumAttachment->i_updateMedium(pDeleteRec->mpTarget);
4270 }
4271
4272 return S_OK;
4273}
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