VirtualBox

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

Last change on this file since 79812 was 79154, checked in by vboxsync, 6 years ago

Main: bugref:6913: Fixed the NULL id in the MediumRegisteredEvent during snapshot restoring

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

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