VirtualBox

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

Last change on this file since 72395 was 70236, checked in by vboxsync, 7 years ago

Main/Snapshot: coding style whitespace cleanup, adding a todo explaining why the current disk space estimate for image merging is too pessimistic

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