VirtualBox

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

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

Capturing: Also initialize settings copies in SnapshotMachine::init().

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