VirtualBox

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

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

Main: bugref:6598: Added ability to merge mediums with different sizes in the offline mode

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 147.3 KB
Line 
1/* $Id: SnapshotImpl.cpp 75373 2018-11-09 18:12:30Z 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(mRecordingSettings).createObject();
1085 rc = mRecordingSettings->initCopy(this, pMachine->mRecordingSettings);
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(mRecordingSettings).createObject();
1211 mRecordingSettings->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 bool fDeleteOnline = mData->mMachineState == MachineState_Running || mData->mMachineState == MachineState_Paused;
2507
2508 // count normal hard disks and add their sizes to the weight
2509 for (MediumAttachmentList::iterator
2510 it = pSnapMachine->mMediumAttachments->begin();
2511 it != pSnapMachine->mMediumAttachments->end();
2512 ++it)
2513 {
2514 ComObjPtr<MediumAttachment> &pAttach = *it;
2515 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2516 if (pAttach->i_getType() == DeviceType_HardDisk)
2517 {
2518 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
2519 Assert(pHD);
2520 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2521
2522 MediumType_T type = pHD->i_getType();
2523 // writethrough and shareable images are unaffected by snapshots,
2524 // so do nothing for them
2525 if ( type != MediumType_Writethrough
2526 && type != MediumType_Shareable
2527 && type != MediumType_Readonly)
2528 {
2529 // normal or immutable media need attention
2530 ++ulOpCount;
2531 // offline merge includes medium resizing
2532 if (!fDeleteOnline)
2533 ++ulOpCount;
2534 ulTotalWeight += (ULONG)(pHD->i_getSize() / _1M);
2535 }
2536 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->i_getName().c_str()));
2537 }
2538 }
2539
2540 ComObjPtr<Progress> pProgress;
2541 pProgress.createObject();
2542 pProgress->init(mParent, static_cast<IMachine*>(this),
2543 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->i_getName().c_str()).raw(),
2544 FALSE /* aCancelable */,
2545 ulOpCount,
2546 ulTotalWeight,
2547 Bstr(tr("Setting up")).raw(),
2548 1);
2549
2550 /* create and start the task on a separate thread */
2551 DeleteSnapshotTask *pTask = new DeleteSnapshotTask(this, pProgress,
2552 "DeleteSnap",
2553 fDeleteOnline,
2554 pSnapshot);
2555 rc = pTask->createThread();
2556 if (FAILED(rc))
2557 return rc;
2558
2559 // the task might start running but will block on acquiring the machine's write lock
2560 // which we acquired above; once this function leaves, the task will be unblocked;
2561 // set the proper machine state here now (note: after creating a Task instance)
2562 if (mData->mMachineState == MachineState_Running)
2563 {
2564 i_setMachineState(MachineState_DeletingSnapshotOnline);
2565 i_updateMachineStateOnClient();
2566 }
2567 else if (mData->mMachineState == MachineState_Paused)
2568 {
2569 i_setMachineState(MachineState_DeletingSnapshotPaused);
2570 i_updateMachineStateOnClient();
2571 }
2572 else
2573 i_setMachineState(MachineState_DeletingSnapshot);
2574
2575 /* return the progress to the caller */
2576 pProgress.queryInterfaceTo(aProgress.asOutParam());
2577
2578 LogFlowThisFuncLeave();
2579
2580 return S_OK;
2581}
2582
2583/**
2584 * Helper struct for SessionMachine::deleteSnapshotHandler().
2585 */
2586struct MediumDeleteRec
2587{
2588 MediumDeleteRec()
2589 : mfNeedsOnlineMerge(false),
2590 mpMediumLockList(NULL)
2591 {}
2592
2593 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2594 const ComObjPtr<Medium> &aSource,
2595 const ComObjPtr<Medium> &aTarget,
2596 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2597 bool fMergeForward,
2598 const ComObjPtr<Medium> &aParentForTarget,
2599 MediumLockList *aChildrenToReparent,
2600 bool fNeedsOnlineMerge,
2601 MediumLockList *aMediumLockList,
2602 const ComPtr<IToken> &aHDLockToken)
2603 : mpHD(aHd),
2604 mpSource(aSource),
2605 mpTarget(aTarget),
2606 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2607 mfMergeForward(fMergeForward),
2608 mpParentForTarget(aParentForTarget),
2609 mpChildrenToReparent(aChildrenToReparent),
2610 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2611 mpMediumLockList(aMediumLockList),
2612 mpHDLockToken(aHDLockToken)
2613 {}
2614
2615 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2616 const ComObjPtr<Medium> &aSource,
2617 const ComObjPtr<Medium> &aTarget,
2618 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2619 bool fMergeForward,
2620 const ComObjPtr<Medium> &aParentForTarget,
2621 MediumLockList *aChildrenToReparent,
2622 bool fNeedsOnlineMerge,
2623 MediumLockList *aMediumLockList,
2624 const ComPtr<IToken> &aHDLockToken,
2625 const Guid &aMachineId,
2626 const Guid &aSnapshotId)
2627 : mpHD(aHd),
2628 mpSource(aSource),
2629 mpTarget(aTarget),
2630 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2631 mfMergeForward(fMergeForward),
2632 mpParentForTarget(aParentForTarget),
2633 mpChildrenToReparent(aChildrenToReparent),
2634 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2635 mpMediumLockList(aMediumLockList),
2636 mpHDLockToken(aHDLockToken),
2637 mMachineId(aMachineId),
2638 mSnapshotId(aSnapshotId)
2639 {}
2640
2641 ComObjPtr<Medium> mpHD;
2642 ComObjPtr<Medium> mpSource;
2643 ComObjPtr<Medium> mpTarget;
2644 ComObjPtr<MediumAttachment> mpOnlineMediumAttachment;
2645 bool mfMergeForward;
2646 ComObjPtr<Medium> mpParentForTarget;
2647 MediumLockList *mpChildrenToReparent;
2648 bool mfNeedsOnlineMerge;
2649 MediumLockList *mpMediumLockList;
2650 /** optional lock token, used only in case mpHD is not merged/deleted */
2651 ComPtr<IToken> mpHDLockToken;
2652 /* these are for reattaching the hard disk in case of a failure: */
2653 Guid mMachineId;
2654 Guid mSnapshotId;
2655};
2656
2657typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2658
2659/**
2660 * Worker method for the delete snapshot thread created by
2661 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2662 * through SessionMachine::taskHandler() which then calls
2663 * DeleteSnapshotTask::handler().
2664 *
2665 * The DeleteSnapshotTask contains the progress object returned to the console
2666 * by SessionMachine::DeleteSnapshot, through which progress and results are
2667 * reported.
2668 *
2669 * SessionMachine::DeleteSnapshot() has set the machine state to
2670 * MachineState_DeletingSnapshot right after creating this task. Since we block
2671 * on the machine write lock at the beginning, once that has been acquired, we
2672 * can assume that the machine state is indeed that.
2673 *
2674 * @note Locks the machine + the snapshot + the media tree for writing!
2675 *
2676 * @param task Task data.
2677 */
2678void SessionMachine::i_deleteSnapshotHandler(DeleteSnapshotTask &task)
2679{
2680 LogFlowThisFuncEnter();
2681
2682 MultiResult mrc(S_OK);
2683 AutoCaller autoCaller(this);
2684 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
2685 if (FAILED(autoCaller.rc()))
2686 {
2687 /* we might have been uninitialized because the session was accidentally
2688 * closed by the client, so don't assert */
2689 mrc = setError(E_FAIL,
2690 tr("The session has been accidentally closed"));
2691 task.m_pProgress->i_notifyComplete(mrc);
2692 LogFlowThisFuncLeave();
2693 return;
2694 }
2695
2696 MediumDeleteRecList toDelete;
2697 Guid snapshotId;
2698
2699 try
2700 {
2701 HRESULT rc = S_OK;
2702
2703 /* Locking order: */
2704 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2705 task.m_pSnapshot->lockHandle() // snapshot
2706 COMMA_LOCKVAL_SRC_POS);
2707 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2708 // has exited after setting the machine state to MachineState_DeletingSnapshot
2709
2710 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle()
2711 COMMA_LOCKVAL_SRC_POS);
2712
2713 ComObjPtr<SnapshotMachine> pSnapMachine = task.m_pSnapshot->i_getSnapshotMachine();
2714 // no need to lock the snapshot machine since it is const by definition
2715 Guid machineId = pSnapMachine->i_getId();
2716
2717 // save the snapshot ID (for callbacks)
2718 snapshotId = task.m_pSnapshot->i_getId();
2719
2720 // first pass:
2721 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2722
2723 // Go thru the attachments of the snapshot machine (the media in here
2724 // point to the disk states _before_ the snapshot was taken, i.e. the
2725 // state we're restoring to; for each such medium, we will need to
2726 // merge it with its one and only child (the diff image holding the
2727 // changes written after the snapshot was taken).
2728 for (MediumAttachmentList::iterator
2729 it = pSnapMachine->mMediumAttachments->begin();
2730 it != pSnapMachine->mMediumAttachments->end();
2731 ++it)
2732 {
2733 ComObjPtr<MediumAttachment> &pAttach = *it;
2734 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2735 if (pAttach->i_getType() != DeviceType_HardDisk)
2736 continue;
2737
2738 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
2739 Assert(!pHD.isNull());
2740
2741 {
2742 // writethrough, shareable and readonly images are
2743 // unaffected by snapshots, skip them
2744 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
2745 MediumType_T type = pHD->i_getType();
2746 if ( type == MediumType_Writethrough
2747 || type == MediumType_Shareable
2748 || type == MediumType_Readonly)
2749 continue;
2750 }
2751
2752#ifdef DEBUG
2753 pHD->i_dumpBackRefs();
2754#endif
2755
2756 // needs to be merged with child or deleted, check prerequisites
2757 ComObjPtr<Medium> pTarget;
2758 ComObjPtr<Medium> pSource;
2759 bool fMergeForward = false;
2760 ComObjPtr<Medium> pParentForTarget;
2761 MediumLockList *pChildrenToReparent = NULL;
2762 bool fNeedsOnlineMerge = false;
2763 bool fOnlineMergePossible = task.m_fDeleteOnline;
2764 MediumLockList *pMediumLockList = NULL;
2765 MediumLockList *pVMMALockList = NULL;
2766 ComPtr<IToken> pHDLockToken;
2767 ComObjPtr<MediumAttachment> pOnlineMediumAttachment;
2768 if (fOnlineMergePossible)
2769 {
2770 // Look up the corresponding medium attachment in the currently
2771 // running VM. Any failure prevents a live merge. Could be made
2772 // a tad smarter by trying a few candidates, so that e.g. disks
2773 // which are simply moved to a different controller slot do not
2774 // prevent online merging in general.
2775 pOnlineMediumAttachment =
2776 i_findAttachment(*mMediumAttachments.data(),
2777 pAttach->i_getControllerName(),
2778 pAttach->i_getPort(),
2779 pAttach->i_getDevice());
2780 if (pOnlineMediumAttachment)
2781 {
2782 rc = mData->mSession.mLockedMedia.Get(pOnlineMediumAttachment,
2783 pVMMALockList);
2784 if (FAILED(rc))
2785 fOnlineMergePossible = false;
2786 }
2787 else
2788 fOnlineMergePossible = false;
2789 }
2790
2791 // no need to hold the lock any longer
2792 attachLock.release();
2793
2794 treeLock.release();
2795 rc = i_prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
2796 fOnlineMergePossible,
2797 pVMMALockList, pSource, pTarget,
2798 fMergeForward, pParentForTarget,
2799 pChildrenToReparent,
2800 fNeedsOnlineMerge,
2801 pMediumLockList,
2802 pHDLockToken);
2803 treeLock.acquire();
2804 if (FAILED(rc))
2805 throw rc;
2806
2807 // For simplicity, prepareDeleteSnapshotMedium selects the merge
2808 // direction in the following way: we merge pHD onto its child
2809 // (forward merge), not the other way round, because that saves us
2810 // from unnecessarily shuffling around the attachments for the
2811 // machine that follows the snapshot (next snapshot or current
2812 // state), unless it's a base image. Backwards merges of the first
2813 // snapshot into the base image is essential, as it ensures that
2814 // when all snapshots are deleted the only remaining image is a
2815 // base image. Important e.g. for medium formats which do not have
2816 // a file representation such as iSCSI.
2817
2818 // not going to merge a big source into a small target on online merge. Otherwise it will be resized
2819 if (fNeedsOnlineMerge && pSource->i_getLogicalSize() > pTarget->i_getLogicalSize())
2820 {
2821 rc = setError(E_FAIL,
2822 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"),
2823 pTarget->i_getLocationFull().c_str(), pSource->i_getLogicalSize());
2824 throw rc;
2825 }
2826
2827 // a couple paranoia checks for backward merges
2828 if (pMediumLockList != NULL && !fMergeForward)
2829 {
2830 // parent is null -> this disk is a base hard disk: we will
2831 // then do a backward merge, i.e. merge its only child onto the
2832 // base disk. Here we need then to update the attachment that
2833 // refers to the child and have it point to the parent instead
2834 Assert(pHD->i_getChildren().size() == 1);
2835
2836 ComObjPtr<Medium> pReplaceHD = pHD->i_getChildren().front();
2837
2838 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
2839 }
2840
2841 Guid replaceMachineId;
2842 Guid replaceSnapshotId;
2843
2844 const Guid *pReplaceMachineId = pSource->i_getFirstMachineBackrefId();
2845 // minimal sanity checking
2846 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
2847 if (pReplaceMachineId)
2848 replaceMachineId = *pReplaceMachineId;
2849
2850 const Guid *pSnapshotId = pSource->i_getFirstMachineBackrefSnapshotId();
2851 if (pSnapshotId)
2852 replaceSnapshotId = *pSnapshotId;
2853
2854 if (replaceMachineId.isValid() && !replaceMachineId.isZero())
2855 {
2856 // Adjust the backreferences, otherwise merging will assert.
2857 // Note that the medium attachment object stays associated
2858 // with the snapshot until the merge was successful.
2859 HRESULT rc2 = S_OK;
2860 rc2 = pSource->i_removeBackReference(replaceMachineId, replaceSnapshotId);
2861 AssertComRC(rc2);
2862
2863 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2864 pOnlineMediumAttachment,
2865 fMergeForward,
2866 pParentForTarget,
2867 pChildrenToReparent,
2868 fNeedsOnlineMerge,
2869 pMediumLockList,
2870 pHDLockToken,
2871 replaceMachineId,
2872 replaceSnapshotId));
2873 }
2874 else
2875 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2876 pOnlineMediumAttachment,
2877 fMergeForward,
2878 pParentForTarget,
2879 pChildrenToReparent,
2880 fNeedsOnlineMerge,
2881 pMediumLockList,
2882 pHDLockToken));
2883 }
2884
2885 {
2886 /* check available space on the storage */
2887 RTFOFF pcbTotal = 0;
2888 RTFOFF pcbFree = 0;
2889 uint32_t pcbBlock = 0;
2890 uint32_t pcbSector = 0;
2891 std::multimap<uint32_t, uint64_t> neededStorageFreeSpace;
2892 std::map<uint32_t, const char*> serialMapToStoragePath;
2893
2894 for (MediumDeleteRecList::const_iterator
2895 it = toDelete.begin();
2896 it != toDelete.end();
2897 ++it)
2898 {
2899 uint64_t diskSize = 0;
2900 uint32_t pu32Serial = 0;
2901 ComObjPtr<Medium> pSource_local = it->mpSource;
2902 ComObjPtr<Medium> pTarget_local = it->mpTarget;
2903 ComPtr<IMediumFormat> pTargetFormat;
2904
2905 {
2906 if ( pSource_local.isNull()
2907 || pSource_local == pTarget_local)
2908 continue;
2909 }
2910
2911 rc = pTarget_local->COMGETTER(MediumFormat)(pTargetFormat.asOutParam());
2912 if (FAILED(rc))
2913 throw rc;
2914
2915 if (pTarget_local->i_isMediumFormatFile())
2916 {
2917 int vrc = RTFsQuerySerial(pTarget_local->i_getLocationFull().c_str(), &pu32Serial);
2918 if (RT_FAILURE(vrc))
2919 {
2920 rc = setError(E_FAIL,
2921 tr("Unable to merge storage '%s'. Can't get storage UID"),
2922 pTarget_local->i_getLocationFull().c_str());
2923 throw rc;
2924 }
2925
2926 pSource_local->COMGETTER(Size)((LONG64*)&diskSize);
2927
2928 /** @todo r=klaus this is too pessimistic... should take
2929 * the current size and maximum size of the target image
2930 * into account, because a X GB image with Y GB capacity
2931 * can only grow by Y-X GB (ignoring overhead, which
2932 * unfortunately is hard to estimate, some have next to
2933 * nothing, some have a certain percentage...) */
2934 /* store needed free space in multimap */
2935 neededStorageFreeSpace.insert(std::make_pair(pu32Serial, diskSize));
2936 /* linking storage UID with snapshot path, it is a helper container (just for easy finding needed path) */
2937 serialMapToStoragePath.insert(std::make_pair(pu32Serial, pTarget_local->i_getLocationFull().c_str()));
2938 }
2939 }
2940
2941 while (!neededStorageFreeSpace.empty())
2942 {
2943 std::pair<std::multimap<uint32_t,uint64_t>::iterator,std::multimap<uint32_t,uint64_t>::iterator> ret;
2944 uint64_t commonSourceStoragesSize = 0;
2945
2946 /* find all records in multimap with identical storage UID */
2947 ret = neededStorageFreeSpace.equal_range(neededStorageFreeSpace.begin()->first);
2948 std::multimap<uint32_t,uint64_t>::const_iterator it_ns = ret.first;
2949
2950 for (; it_ns != ret.second ; ++it_ns)
2951 {
2952 commonSourceStoragesSize += it_ns->second;
2953 }
2954
2955 /* find appropriate path by storage UID */
2956 std::map<uint32_t,const char*>::const_iterator it_sm = serialMapToStoragePath.find(ret.first->first);
2957 /* get info about a storage */
2958 if (it_sm == serialMapToStoragePath.end())
2959 {
2960 LogFlowThisFunc(("Path to the storage wasn't found...\n"));
2961
2962 rc = setError(E_INVALIDARG,
2963 tr("Unable to merge storage '%s'. Path to the storage wasn't found"),
2964 it_sm->second);
2965 throw rc;
2966 }
2967
2968 int vrc = RTFsQuerySizes(it_sm->second, &pcbTotal, &pcbFree, &pcbBlock, &pcbSector);
2969 if (RT_FAILURE(vrc))
2970 {
2971 rc = setError(E_FAIL,
2972 tr("Unable to merge storage '%s'. Can't get the storage size"),
2973 it_sm->second);
2974 throw rc;
2975 }
2976
2977 if (commonSourceStoragesSize > (uint64_t)pcbFree)
2978 {
2979 LogFlowThisFunc(("Not enough free space to merge...\n"));
2980
2981 rc = setError(E_OUTOFMEMORY,
2982 tr("Unable to merge storage '%s'. Not enough free storage space"),
2983 it_sm->second);
2984 throw rc;
2985 }
2986
2987 neededStorageFreeSpace.erase(ret.first, ret.second);
2988 }
2989
2990 serialMapToStoragePath.clear();
2991 }
2992
2993 // we can release the locks now since the machine state is MachineState_DeletingSnapshot
2994 treeLock.release();
2995 multiLock.release();
2996
2997 /* Now we checked that we can successfully merge all normal hard disks
2998 * (unless a runtime error like end-of-disc happens). Now get rid of
2999 * the saved state (if present), as that will free some disk space.
3000 * The snapshot itself will be deleted as late as possible, so that
3001 * the user can repeat the delete operation if he runs out of disk
3002 * space or cancels the delete operation. */
3003
3004 /* second pass: */
3005 LogFlowThisFunc(("2: Deleting saved state...\n"));
3006
3007 {
3008 // saveAllSnapshots() needs a machine lock, and the snapshots
3009 // tree is protected by the machine lock as well
3010 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
3011
3012 Utf8Str stateFilePath = task.m_pSnapshot->i_getStateFilePath();
3013 if (!stateFilePath.isEmpty())
3014 {
3015 task.m_pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")).raw(),
3016 1); // weight
3017
3018 i_releaseSavedStateFile(stateFilePath, task.m_pSnapshot /* pSnapshotToIgnore */);
3019
3020 // machine will need saving now
3021 machineLock.release();
3022 mParent->i_markRegistryModified(i_getId());
3023 }
3024 }
3025
3026 /* third pass: */
3027 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
3028
3029 /// @todo NEWMEDIA turn the following errors into warnings because the
3030 /// snapshot itself has been already deleted (and interpret these
3031 /// warnings properly on the GUI side)
3032 for (MediumDeleteRecList::iterator it = toDelete.begin();
3033 it != toDelete.end();)
3034 {
3035 const ComObjPtr<Medium> &pMedium(it->mpHD);
3036 ULONG ulWeight;
3037
3038 {
3039 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3040 ulWeight = (ULONG)(pMedium->i_getSize() / _1M);
3041 }
3042
3043 const char *pszOperationText = it->mfNeedsOnlineMerge ?
3044 tr("Merging differencing image '%s'")
3045 : tr("Resizing before merge differencing image '%s'");
3046
3047 task.m_pProgress->SetNextOperation(BstrFmt(pszOperationText,
3048 pMedium->i_getName().c_str()).raw(),
3049 ulWeight);
3050
3051 bool fNeedSourceUninit = false;
3052 bool fReparentTarget = false;
3053 if (it->mpMediumLockList == NULL)
3054 {
3055 /* no real merge needed, just updating state and delete
3056 * diff files if necessary */
3057 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
3058
3059 Assert( !it->mfMergeForward
3060 || pMedium->i_getChildren().size() == 0);
3061
3062 /* Delete the differencing hard disk (has no children). Two
3063 * exceptions: if it's the last medium in the chain or if it's
3064 * a backward merge we don't want to handle due to complexity.
3065 * In both cases leave the image in place. If it's the first
3066 * exception the user can delete it later if he wants. */
3067 if (!pMedium->i_getParent().isNull())
3068 {
3069 Assert(pMedium->i_getState() == MediumState_Deleting);
3070 /* No need to hold the lock any longer. */
3071 mLock.release();
3072 rc = pMedium->i_deleteStorage(&task.m_pProgress,
3073 true /* aWait */);
3074 if (FAILED(rc))
3075 throw rc;
3076
3077 // need to uninit the deleted medium
3078 fNeedSourceUninit = true;
3079 }
3080 }
3081 else
3082 {
3083 bool fNeedsSave = false;
3084 if (it->mfNeedsOnlineMerge)
3085 {
3086 // Put the medium merge information (MediumDeleteRec) where
3087 // SessionMachine::FinishOnlineMergeMedium can get at it.
3088 // This callback will arrive while onlineMergeMedium is
3089 // still executing, and there can't be two tasks.
3090 /// @todo r=klaus this hack needs to go, and the logic needs to be "unconvoluted", putting SessionMachine in charge of coordinating the reconfig/resume.
3091 mConsoleTaskData.mDeleteSnapshotInfo = (void *)&(*it);
3092 // online medium merge, in the direction decided earlier
3093 rc = i_onlineMergeMedium(it->mpOnlineMediumAttachment,
3094 it->mpSource,
3095 it->mpTarget,
3096 it->mfMergeForward,
3097 it->mpParentForTarget,
3098 it->mpChildrenToReparent,
3099 it->mpMediumLockList,
3100 task.m_pProgress,
3101 &fNeedsSave);
3102 mConsoleTaskData.mDeleteSnapshotInfo = NULL;
3103 }
3104 else
3105 {
3106 // normal medium merge, in the direction decided earlier
3107 rc = it->mpSource->i_mergeTo(it->mpTarget,
3108 it->mfMergeForward,
3109 it->mpParentForTarget,
3110 it->mpChildrenToReparent,
3111 it->mpMediumLockList,
3112 &task.m_pProgress,
3113 true /* aWait */);
3114 }
3115
3116 // If the merge failed, we need to do our best to have a usable
3117 // VM configuration afterwards. The return code doesn't tell
3118 // whether the merge completed and so we have to check if the
3119 // source medium (diff images are always file based at the
3120 // moment) is still there or not. Be careful not to lose the
3121 // error code below, before the "Delayed failure exit".
3122 if (FAILED(rc))
3123 {
3124 AutoReadLock mlock(it->mpSource COMMA_LOCKVAL_SRC_POS);
3125 if (!it->mpSource->i_isMediumFormatFile())
3126 // Diff medium not backed by a file - cannot get status so
3127 // be pessimistic.
3128 throw rc;
3129 const Utf8Str &loc = it->mpSource->i_getLocationFull();
3130 // Source medium is still there, so merge failed early.
3131 if (RTFileExists(loc.c_str()))
3132 throw rc;
3133
3134 // Source medium is gone. Assume the merge succeeded and
3135 // thus it's safe to remove the attachment. We use the
3136 // "Delayed failure exit" below.
3137 }
3138
3139 // need to change the medium attachment for backward merges
3140 fReparentTarget = !it->mfMergeForward;
3141
3142 if (!it->mfNeedsOnlineMerge)
3143 {
3144 // need to uninit the medium deleted by the merge
3145 fNeedSourceUninit = true;
3146
3147 // delete the no longer needed medium lock list, which
3148 // implicitly handled the unlocking
3149 delete it->mpMediumLockList;
3150 it->mpMediumLockList = NULL;
3151 }
3152 }
3153
3154 // Now that the medium is successfully merged/deleted/whatever,
3155 // remove the medium attachment from the snapshot. For a backwards
3156 // merge the target attachment needs to be removed from the
3157 // snapshot, as the VM will take it over. For forward merges the
3158 // source medium attachment needs to be removed.
3159 ComObjPtr<MediumAttachment> pAtt;
3160 if (fReparentTarget)
3161 {
3162 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3163 it->mpTarget);
3164 it->mpTarget->i_removeBackReference(machineId, snapshotId);
3165 }
3166 else
3167 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3168 it->mpSource);
3169 pSnapMachine->mMediumAttachments->remove(pAtt);
3170
3171 if (fReparentTarget)
3172 {
3173 // Search for old source attachment and replace with target.
3174 // There can be only one child snapshot in this case.
3175 ComObjPtr<Machine> pMachine = this;
3176 Guid childSnapshotId;
3177 ComObjPtr<Snapshot> pChildSnapshot = task.m_pSnapshot->i_getFirstChild();
3178 if (pChildSnapshot)
3179 {
3180 pMachine = pChildSnapshot->i_getSnapshotMachine();
3181 childSnapshotId = pChildSnapshot->i_getId();
3182 }
3183 pAtt = i_findAttachment(*(pMachine->mMediumAttachments).data(), it->mpSource);
3184 if (pAtt)
3185 {
3186 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
3187 pAtt->i_updateMedium(it->mpTarget);
3188 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3189 }
3190 else
3191 {
3192 // If no attachment is found do not change anything. Maybe
3193 // the source medium was not attached to the snapshot.
3194 // If this is an online deletion the attachment was updated
3195 // already to allow the VM continue execution immediately.
3196 // Needs a bit of special treatment due to this difference.
3197 if (it->mfNeedsOnlineMerge)
3198 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3199 }
3200 }
3201
3202 if (fNeedSourceUninit)
3203 {
3204 // make sure that the diff image to be deleted has no parent,
3205 // even in error cases (where the deparenting may be missing)
3206 if (it->mpSource->i_getParent())
3207 it->mpSource->i_deparent();
3208 it->mpSource->uninit();
3209 }
3210
3211 // One attachment is merged, must save the settings
3212 mParent->i_markRegistryModified(i_getId());
3213
3214 // prevent calling cancelDeleteSnapshotMedium() for this attachment
3215 it = toDelete.erase(it);
3216
3217 // Delayed failure exit when the merge cleanup failed but the
3218 // merge actually succeeded.
3219 if (FAILED(rc))
3220 throw rc;
3221 }
3222
3223 {
3224 // beginSnapshotDelete() needs the machine lock, and the snapshots
3225 // tree is protected by the machine lock as well
3226 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
3227
3228 task.m_pSnapshot->i_beginSnapshotDelete();
3229 task.m_pSnapshot->uninit();
3230
3231 machineLock.release();
3232 mParent->i_markRegistryModified(i_getId());
3233 }
3234 }
3235 catch (HRESULT aRC) {
3236 mrc = aRC;
3237 }
3238
3239 if (FAILED(mrc))
3240 {
3241 // preserve existing error info so that the result can
3242 // be properly reported to the progress object below
3243 ErrorInfoKeeper eik;
3244
3245 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
3246 &mParent->i_getMediaTreeLockHandle() // media tree
3247 COMMA_LOCKVAL_SRC_POS);
3248
3249 // un-prepare the remaining hard disks
3250 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
3251 it != toDelete.end();
3252 ++it)
3253 i_cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
3254 it->mpChildrenToReparent,
3255 it->mfNeedsOnlineMerge,
3256 it->mpMediumLockList, it->mpHDLockToken,
3257 it->mMachineId, it->mSnapshotId);
3258 }
3259
3260 // whether we were successful or not, we need to set the machine
3261 // state and save the machine settings;
3262 {
3263 // preserve existing error info so that the result can
3264 // be properly reported to the progress object below
3265 ErrorInfoKeeper eik;
3266
3267 // restore the machine state that was saved when the
3268 // task was started
3269 i_setMachineState(task.m_machineStateBackup);
3270 if (Global::IsOnline(mData->mMachineState))
3271 i_updateMachineStateOnClient();
3272
3273 mParent->i_saveModifiedRegistries();
3274 }
3275
3276 // report the result (this will try to fetch current error info on failure)
3277 task.m_pProgress->i_notifyComplete(mrc);
3278
3279 if (SUCCEEDED(mrc))
3280 mParent->i_onSnapshotDeleted(mData->mUuid, snapshotId);
3281
3282 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", (HRESULT)mrc));
3283 LogFlowThisFuncLeave();
3284}
3285
3286/**
3287 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
3288 * performs necessary state changes. Must not be called for writethrough disks
3289 * because there is nothing to delete/merge then.
3290 *
3291 * This method is to be called prior to calling #deleteSnapshotMedium().
3292 * If #deleteSnapshotMedium() is not called or fails, the state modifications
3293 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
3294 *
3295 * @return COM status code
3296 * @param aHD Hard disk which is connected to the snapshot.
3297 * @param aMachineId UUID of machine this hard disk is attached to.
3298 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
3299 * be a zero UUID if no snapshot is applicable.
3300 * @param fOnlineMergePossible Flag whether an online merge is possible.
3301 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
3302 * Only used if @a fOnlineMergePossible is @c true, and
3303 * must be non-NULL in this case.
3304 * @param aSource Source hard disk for merge (out).
3305 * @param aTarget Target hard disk for merge (out).
3306 * @param aMergeForward Merge direction decision (out).
3307 * @param aParentForTarget New parent if target needs to be reparented (out).
3308 * @param aChildrenToReparent MediumLockList with children which have to be
3309 * reparented to the target (out).
3310 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
3311 * If this is set to @a true then the @a aVMMALockList
3312 * parameter has been modified and is returned as
3313 * @a aMediumLockList.
3314 * @param aMediumLockList Where to store the created medium lock list (may
3315 * return NULL if no real merge is necessary).
3316 * @param aHDLockToken Where to store the write lock token for aHD, in case
3317 * it is not merged or deleted (out).
3318 *
3319 * @note Caller must hold media tree lock for writing. This locks this object
3320 * and every medium object on the merge chain for writing.
3321 */
3322HRESULT SessionMachine::i_prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3323 const Guid &aMachineId,
3324 const Guid &aSnapshotId,
3325 bool fOnlineMergePossible,
3326 MediumLockList *aVMMALockList,
3327 ComObjPtr<Medium> &aSource,
3328 ComObjPtr<Medium> &aTarget,
3329 bool &aMergeForward,
3330 ComObjPtr<Medium> &aParentForTarget,
3331 MediumLockList * &aChildrenToReparent,
3332 bool &fNeedsOnlineMerge,
3333 MediumLockList * &aMediumLockList,
3334 ComPtr<IToken> &aHDLockToken)
3335{
3336 Assert(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3337 Assert(!fOnlineMergePossible || VALID_PTR(aVMMALockList));
3338
3339 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
3340
3341 // Medium must not be writethrough/shareable/readonly at this point
3342 MediumType_T type = aHD->i_getType();
3343 AssertReturn( type != MediumType_Writethrough
3344 && type != MediumType_Shareable
3345 && type != MediumType_Readonly, E_FAIL);
3346
3347 aChildrenToReparent = NULL;
3348 aMediumLockList = NULL;
3349 fNeedsOnlineMerge = false;
3350
3351 if (aHD->i_getChildren().size() == 0)
3352 {
3353 /* This technically is no merge, set those values nevertheless.
3354 * Helps with updating the medium attachments. */
3355 aSource = aHD;
3356 aTarget = aHD;
3357
3358 /* special treatment of the last hard disk in the chain: */
3359 if (aHD->i_getParent().isNull())
3360 {
3361 /* lock only, to prevent any usage until the snapshot deletion
3362 * is completed */
3363 alock.release();
3364 return aHD->LockWrite(aHDLockToken.asOutParam());
3365 }
3366
3367 /* the differencing hard disk w/o children will be deleted, protect it
3368 * from attaching to other VMs (this is why Deleting) */
3369 return aHD->i_markForDeletion();
3370 }
3371
3372 /* not going multi-merge as it's too expensive */
3373 if (aHD->i_getChildren().size() > 1)
3374 return setError(E_FAIL,
3375 tr("Hard disk '%s' has more than one child hard disk (%d)"),
3376 aHD->i_getLocationFull().c_str(),
3377 aHD->i_getChildren().size());
3378
3379 ComObjPtr<Medium> pChild = aHD->i_getChildren().front();
3380
3381 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
3382
3383 /* the rest is a normal merge setup */
3384 if (aHD->i_getParent().isNull())
3385 {
3386 /* base hard disk, backward merge */
3387 const Guid *pMachineId1 = pChild->i_getFirstMachineBackrefId();
3388 const Guid *pMachineId2 = aHD->i_getFirstMachineBackrefId();
3389 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
3390 {
3391 /* backward merge is too tricky, we'll just detach on snapshot
3392 * deletion, so lock only, to prevent any usage */
3393 childLock.release();
3394 alock.release();
3395 return aHD->LockWrite(aHDLockToken.asOutParam());
3396 }
3397
3398 aSource = pChild;
3399 aTarget = aHD;
3400 }
3401 else
3402 {
3403 /* Determine best merge direction. */
3404 bool fMergeForward = true;
3405
3406 childLock.release();
3407 alock.release();
3408 HRESULT rc = aHD->i_queryPreferredMergeDirection(pChild, fMergeForward);
3409 alock.acquire();
3410 childLock.acquire();
3411
3412 if (FAILED(rc) && rc != E_FAIL)
3413 return rc;
3414
3415 if (fMergeForward)
3416 {
3417 aSource = aHD;
3418 aTarget = pChild;
3419 LogFlowThisFunc(("Forward merging selected\n"));
3420 }
3421 else
3422 {
3423 aSource = pChild;
3424 aTarget = aHD;
3425 LogFlowThisFunc(("Backward merging selected\n"));
3426 }
3427 }
3428
3429 HRESULT rc;
3430 childLock.release();
3431 alock.release();
3432 rc = aSource->i_prepareMergeTo(aTarget, &aMachineId, &aSnapshotId,
3433 !fOnlineMergePossible /* fLockMedia */,
3434 aMergeForward, aParentForTarget,
3435 aChildrenToReparent, aMediumLockList);
3436 alock.acquire();
3437 childLock.acquire();
3438 if (SUCCEEDED(rc) && fOnlineMergePossible)
3439 {
3440 /* Try to lock the newly constructed medium lock list. If it succeeds
3441 * this can be handled as an offline merge, i.e. without the need of
3442 * asking the VM to do the merging. Only continue with the online
3443 * merging preparation if applicable. */
3444 childLock.release();
3445 alock.release();
3446 rc = aMediumLockList->Lock();
3447 alock.acquire();
3448 childLock.acquire();
3449 if (FAILED(rc))
3450 {
3451 /* Locking failed, this cannot be done as an offline merge. Try to
3452 * combine the locking information into the lock list of the medium
3453 * attachment in the running VM. If that fails or locking the
3454 * resulting lock list fails then the merge cannot be done online.
3455 * It can be repeated by the user when the VM is shut down. */
3456 MediumLockList::Base::iterator lockListVMMABegin =
3457 aVMMALockList->GetBegin();
3458 MediumLockList::Base::iterator lockListVMMAEnd =
3459 aVMMALockList->GetEnd();
3460 MediumLockList::Base::iterator lockListBegin =
3461 aMediumLockList->GetBegin();
3462 MediumLockList::Base::iterator lockListEnd =
3463 aMediumLockList->GetEnd();
3464 for (MediumLockList::Base::iterator it = lockListVMMABegin,
3465 it2 = lockListBegin;
3466 it2 != lockListEnd;
3467 ++it, ++it2)
3468 {
3469 if ( it == lockListVMMAEnd
3470 || it->GetMedium() != it2->GetMedium())
3471 {
3472 fOnlineMergePossible = false;
3473 break;
3474 }
3475 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
3476 childLock.release();
3477 alock.release();
3478 rc = it->UpdateLock(fLockReq);
3479 alock.acquire();
3480 childLock.acquire();
3481 if (FAILED(rc))
3482 {
3483 // could not update the lock, trigger cleanup below
3484 fOnlineMergePossible = false;
3485 break;
3486 }
3487 }
3488
3489 if (fOnlineMergePossible)
3490 {
3491 /* we will lock the children of the source for reparenting */
3492 if (aChildrenToReparent && !aChildrenToReparent->IsEmpty())
3493 {
3494 /* Cannot just call aChildrenToReparent->Lock(), as one of
3495 * the children is the one under which the current state of
3496 * the VM is located, and this means it is already locked
3497 * (for reading). Note that no special unlocking is needed,
3498 * because cancelMergeTo will unlock everything locked in
3499 * its context (using the unlock on destruction), and both
3500 * cancelDeleteSnapshotMedium (in case something fails) and
3501 * FinishOnlineMergeMedium re-define the read/write lock
3502 * state of everything which the VM need, search for the
3503 * UpdateLock method calls. */
3504 childLock.release();
3505 alock.release();
3506 rc = aChildrenToReparent->Lock(true /* fSkipOverLockedMedia */);
3507 alock.acquire();
3508 childLock.acquire();
3509 MediumLockList::Base::iterator childrenToReparentBegin = aChildrenToReparent->GetBegin();
3510 MediumLockList::Base::iterator childrenToReparentEnd = aChildrenToReparent->GetEnd();
3511 for (MediumLockList::Base::iterator it = childrenToReparentBegin;
3512 it != childrenToReparentEnd;
3513 ++it)
3514 {
3515 ComObjPtr<Medium> pMedium = it->GetMedium();
3516 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3517 if (!it->IsLocked())
3518 {
3519 mediumLock.release();
3520 childLock.release();
3521 alock.release();
3522 rc = aVMMALockList->Update(pMedium, true);
3523 alock.acquire();
3524 childLock.acquire();
3525 mediumLock.acquire();
3526 if (FAILED(rc))
3527 throw rc;
3528 }
3529 }
3530 }
3531 }
3532
3533 if (fOnlineMergePossible)
3534 {
3535 childLock.release();
3536 alock.release();
3537 rc = aVMMALockList->Lock();
3538 alock.acquire();
3539 childLock.acquire();
3540 if (FAILED(rc))
3541 {
3542 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3543 rc = setError(rc,
3544 tr("Cannot lock hard disk '%s' for a live merge"),
3545 aHD->i_getLocationFull().c_str());
3546 }
3547 else
3548 {
3549 delete aMediumLockList;
3550 aMediumLockList = aVMMALockList;
3551 fNeedsOnlineMerge = true;
3552 }
3553 }
3554 else
3555 {
3556 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3557 rc = setError(rc,
3558 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
3559 aHD->i_getLocationFull().c_str());
3560 }
3561
3562 // fix the VM's lock list if anything failed
3563 if (FAILED(rc))
3564 {
3565 lockListVMMABegin = aVMMALockList->GetBegin();
3566 lockListVMMAEnd = aVMMALockList->GetEnd();
3567 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
3568 --lockListLast;
3569 for (MediumLockList::Base::iterator it = lockListVMMABegin;
3570 it != lockListVMMAEnd;
3571 ++it)
3572 {
3573 childLock.release();
3574 alock.release();
3575 it->UpdateLock(it == lockListLast);
3576 alock.acquire();
3577 childLock.acquire();
3578 ComObjPtr<Medium> pMedium = it->GetMedium();
3579 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3580 // blindly apply this, only needed for medium objects which
3581 // would be deleted as part of the merge
3582 pMedium->i_unmarkLockedForDeletion();
3583 }
3584 }
3585 }
3586 }
3587 else if (FAILED(rc))
3588 {
3589 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3590 rc = setError(rc,
3591 tr("Cannot lock hard disk '%s' when deleting a snapshot"),
3592 aHD->i_getLocationFull().c_str());
3593 }
3594
3595 return rc;
3596}
3597
3598/**
3599 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
3600 * what #prepareDeleteSnapshotMedium() did. Must be called if
3601 * #deleteSnapshotMedium() is not called or fails.
3602 *
3603 * @param aHD Hard disk which is connected to the snapshot.
3604 * @param aSource Source hard disk for merge.
3605 * @param aChildrenToReparent Children to unlock.
3606 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
3607 * @param aMediumLockList Medium locks to cancel.
3608 * @param aHDLockToken Optional write lock token for aHD.
3609 * @param aMachineId Machine id to attach the medium to.
3610 * @param aSnapshotId Snapshot id to attach the medium to.
3611 *
3612 * @note Locks the medium tree and the hard disks in the chain for writing.
3613 */
3614void SessionMachine::i_cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3615 const ComObjPtr<Medium> &aSource,
3616 MediumLockList *aChildrenToReparent,
3617 bool fNeedsOnlineMerge,
3618 MediumLockList *aMediumLockList,
3619 const ComPtr<IToken> &aHDLockToken,
3620 const Guid &aMachineId,
3621 const Guid &aSnapshotId)
3622{
3623 if (aMediumLockList == NULL)
3624 {
3625 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
3626
3627 Assert(aHD->i_getChildren().size() == 0);
3628
3629 if (aHD->i_getParent().isNull())
3630 {
3631 Assert(!aHDLockToken.isNull());
3632 if (!aHDLockToken.isNull())
3633 {
3634 HRESULT rc = aHDLockToken->Abandon();
3635 AssertComRC(rc);
3636 }
3637 }
3638 else
3639 {
3640 HRESULT rc = aHD->i_unmarkForDeletion();
3641 AssertComRC(rc);
3642 }
3643 }
3644 else
3645 {
3646 if (fNeedsOnlineMerge)
3647 {
3648 // Online merge uses the medium lock list of the VM, so give
3649 // an empty list to cancelMergeTo so that it works as designed.
3650 aSource->i_cancelMergeTo(aChildrenToReparent, new MediumLockList());
3651
3652 // clean up the VM medium lock list ourselves
3653 MediumLockList::Base::iterator lockListBegin =
3654 aMediumLockList->GetBegin();
3655 MediumLockList::Base::iterator lockListEnd =
3656 aMediumLockList->GetEnd();
3657 MediumLockList::Base::iterator lockListLast = lockListEnd;
3658 --lockListLast;
3659 for (MediumLockList::Base::iterator it = lockListBegin;
3660 it != lockListEnd;
3661 ++it)
3662 {
3663 ComObjPtr<Medium> pMedium = it->GetMedium();
3664 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3665 if (pMedium->i_getState() == MediumState_Deleting)
3666 pMedium->i_unmarkForDeletion();
3667 else
3668 {
3669 // blindly apply this, only needed for medium objects which
3670 // would be deleted as part of the merge
3671 pMedium->i_unmarkLockedForDeletion();
3672 }
3673 mediumLock.release();
3674 it->UpdateLock(it == lockListLast);
3675 mediumLock.acquire();
3676 }
3677 }
3678 else
3679 {
3680 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3681 }
3682 }
3683
3684 if (aMachineId.isValid() && !aMachineId.isZero())
3685 {
3686 // reattach the source media to the snapshot
3687 HRESULT rc = aSource->i_addBackReference(aMachineId, aSnapshotId);
3688 AssertComRC(rc);
3689 }
3690}
3691
3692/**
3693 * Perform an online merge of a hard disk, i.e. the equivalent of
3694 * Medium::mergeTo(), just for running VMs. If this fails you need to call
3695 * #cancelDeleteSnapshotMedium().
3696 *
3697 * @return COM status code
3698 * @param aMediumAttachment Identify where the disk is attached in the VM.
3699 * @param aSource Source hard disk for merge.
3700 * @param aTarget Target hard disk for merge.
3701 * @param fMergeForward Merge direction.
3702 * @param aParentForTarget New parent if target needs to be reparented.
3703 * @param aChildrenToReparent Medium lock list with children which have to be
3704 * reparented to the target.
3705 * @param aMediumLockList Where to store the created medium lock list (may
3706 * return NULL if no real merge is necessary).
3707 * @param aProgress Progress indicator.
3708 * @param pfNeedsMachineSaveSettings Whether the VM settings need to be saved (out).
3709 */
3710HRESULT SessionMachine::i_onlineMergeMedium(const ComObjPtr<MediumAttachment> &aMediumAttachment,
3711 const ComObjPtr<Medium> &aSource,
3712 const ComObjPtr<Medium> &aTarget,
3713 bool fMergeForward,
3714 const ComObjPtr<Medium> &aParentForTarget,
3715 MediumLockList *aChildrenToReparent,
3716 MediumLockList *aMediumLockList,
3717 ComObjPtr<Progress> &aProgress,
3718 bool *pfNeedsMachineSaveSettings)
3719{
3720 AssertReturn(aSource != NULL, E_FAIL);
3721 AssertReturn(aTarget != NULL, E_FAIL);
3722 AssertReturn(aSource != aTarget, E_FAIL);
3723 AssertReturn(aMediumLockList != NULL, E_FAIL);
3724 NOREF(fMergeForward);
3725 NOREF(aParentForTarget);
3726 NOREF(aChildrenToReparent);
3727
3728 HRESULT rc = S_OK;
3729
3730 try
3731 {
3732 // Similar code appears in Medium::taskMergeHandle, so
3733 // if you make any changes below check whether they are applicable
3734 // in that context as well.
3735
3736 unsigned uTargetIdx = (unsigned)-1;
3737 unsigned uSourceIdx = (unsigned)-1;
3738 /* Sanity check all hard disks in the chain. */
3739 MediumLockList::Base::iterator lockListBegin =
3740 aMediumLockList->GetBegin();
3741 MediumLockList::Base::iterator lockListEnd =
3742 aMediumLockList->GetEnd();
3743 unsigned i = 0;
3744 for (MediumLockList::Base::iterator it = lockListBegin;
3745 it != lockListEnd;
3746 ++it)
3747 {
3748 MediumLock &mediumLock = *it;
3749 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
3750
3751 if (pMedium == aSource)
3752 uSourceIdx = i;
3753 else if (pMedium == aTarget)
3754 uTargetIdx = i;
3755
3756 // In Medium::taskMergeHandler there is lots of consistency
3757 // checking which we cannot do here, as the state details are
3758 // impossible to get outside the Medium class. The locking should
3759 // have done the checks already.
3760
3761 i++;
3762 }
3763
3764 ComAssertThrow( uSourceIdx != (unsigned)-1
3765 && uTargetIdx != (unsigned)-1, E_FAIL);
3766
3767 ComPtr<IInternalSessionControl> directControl;
3768 {
3769 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3770
3771 if (mData->mSession.mState != SessionState_Locked)
3772 throw setError(VBOX_E_INVALID_VM_STATE,
3773 tr("Machine is not locked by a session (session state: %s)"),
3774 Global::stringifySessionState(mData->mSession.mState));
3775 directControl = mData->mSession.mDirectControl;
3776 }
3777
3778 // Must not hold any locks here, as this will call back to finish
3779 // updating the medium attachment, chain linking and state.
3780 rc = directControl->OnlineMergeMedium(aMediumAttachment,
3781 uSourceIdx, uTargetIdx,
3782 aProgress);
3783 if (FAILED(rc))
3784 throw rc;
3785 }
3786 catch (HRESULT aRC) { rc = aRC; }
3787
3788 // The callback mentioned above takes care of update the medium state
3789
3790 if (pfNeedsMachineSaveSettings)
3791 *pfNeedsMachineSaveSettings = true;
3792
3793 return rc;
3794}
3795
3796/**
3797 * Implementation for IInternalMachineControl::finishOnlineMergeMedium().
3798 *
3799 * Gets called after the successful completion of an online merge from
3800 * Console::onlineMergeMedium(), which gets invoked indirectly above in
3801 * the call to IInternalSessionControl::onlineMergeMedium.
3802 *
3803 * This updates the medium information and medium state so that the VM
3804 * can continue with the updated state of the medium chain.
3805 */
3806HRESULT SessionMachine::finishOnlineMergeMedium()
3807{
3808 HRESULT rc = S_OK;
3809 MediumDeleteRec *pDeleteRec = (MediumDeleteRec *)mConsoleTaskData.mDeleteSnapshotInfo;
3810 AssertReturn(pDeleteRec, E_FAIL);
3811 bool fSourceHasChildren = false;
3812
3813 // all hard disks but the target were successfully deleted by
3814 // the merge; reparent target if necessary and uninitialize media
3815
3816 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3817
3818 // Declare this here to make sure the object does not get uninitialized
3819 // before this method completes. Would normally happen as halfway through
3820 // we delete the last reference to the no longer existing medium object.
3821 ComObjPtr<Medium> targetChild;
3822
3823 if (pDeleteRec->mfMergeForward)
3824 {
3825 // first, unregister the target since it may become a base
3826 // hard disk which needs re-registration
3827 rc = mParent->i_unregisterMedium(pDeleteRec->mpTarget);
3828 AssertComRC(rc);
3829
3830 // then, reparent it and disconnect the deleted branch at
3831 // both ends (chain->parent() is source's parent)
3832 pDeleteRec->mpTarget->i_deparent();
3833 pDeleteRec->mpTarget->i_setParent(pDeleteRec->mpParentForTarget);
3834 if (pDeleteRec->mpParentForTarget)
3835 pDeleteRec->mpSource->i_deparent();
3836
3837 // then, register again
3838 rc = mParent->i_registerMedium(pDeleteRec->mpTarget, &pDeleteRec->mpTarget, treeLock);
3839 AssertComRC(rc);
3840 }
3841 else
3842 {
3843 Assert(pDeleteRec->mpTarget->i_getChildren().size() == 1);
3844 targetChild = pDeleteRec->mpTarget->i_getChildren().front();
3845
3846 // disconnect the deleted branch at the elder end
3847 targetChild->i_deparent();
3848
3849 // Update parent UUIDs of the source's children, reparent them and
3850 // disconnect the deleted branch at the younger end
3851 if (pDeleteRec->mpChildrenToReparent && !pDeleteRec->mpChildrenToReparent->IsEmpty())
3852 {
3853 fSourceHasChildren = true;
3854 // Fix the parent UUID of the images which needs to be moved to
3855 // underneath target. The running machine has the images opened,
3856 // but only for reading since the VM is paused. If anything fails
3857 // we must continue. The worst possible result is that the images
3858 // need manual fixing via VBoxManage to adjust the parent UUID.
3859 treeLock.release();
3860 pDeleteRec->mpTarget->i_fixParentUuidOfChildren(pDeleteRec->mpChildrenToReparent);
3861 // The childen are still write locked, unlock them now and don't
3862 // rely on the destructor doing it very late.
3863 pDeleteRec->mpChildrenToReparent->Unlock();
3864 treeLock.acquire();
3865
3866 // obey {parent,child} lock order
3867 AutoWriteLock sourceLock(pDeleteRec->mpSource COMMA_LOCKVAL_SRC_POS);
3868
3869 MediumLockList::Base::iterator childrenBegin = pDeleteRec->mpChildrenToReparent->GetBegin();
3870 MediumLockList::Base::iterator childrenEnd = pDeleteRec->mpChildrenToReparent->GetEnd();
3871 for (MediumLockList::Base::iterator it = childrenBegin;
3872 it != childrenEnd;
3873 ++it)
3874 {
3875 Medium *pMedium = it->GetMedium();
3876 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
3877
3878 pMedium->i_deparent(); // removes pMedium from source
3879 pMedium->i_setParent(pDeleteRec->mpTarget);
3880 }
3881 }
3882 }
3883
3884 /* unregister and uninitialize all hard disks removed by the merge */
3885 MediumLockList *pMediumLockList = NULL;
3886 rc = mData->mSession.mLockedMedia.Get(pDeleteRec->mpOnlineMediumAttachment, pMediumLockList);
3887 const ComObjPtr<Medium> &pLast = pDeleteRec->mfMergeForward ? pDeleteRec->mpTarget : pDeleteRec->mpSource;
3888 AssertReturn(SUCCEEDED(rc) && pMediumLockList, E_FAIL);
3889 MediumLockList::Base::iterator lockListBegin =
3890 pMediumLockList->GetBegin();
3891 MediumLockList::Base::iterator lockListEnd =
3892 pMediumLockList->GetEnd();
3893 for (MediumLockList::Base::iterator it = lockListBegin;
3894 it != lockListEnd;
3895 )
3896 {
3897 MediumLock &mediumLock = *it;
3898 /* Create a real copy of the medium pointer, as the medium
3899 * lock deletion below would invalidate the referenced object. */
3900 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
3901
3902 /* The target and all images not merged (readonly) are skipped */
3903 if ( pMedium == pDeleteRec->mpTarget
3904 || pMedium->i_getState() == MediumState_LockedRead)
3905 {
3906 ++it;
3907 }
3908 else
3909 {
3910 rc = mParent->i_unregisterMedium(pMedium);
3911 AssertComRC(rc);
3912
3913 /* now, uninitialize the deleted hard disk (note that
3914 * due to the Deleting state, uninit() will not touch
3915 * the parent-child relationship so we need to
3916 * uninitialize each disk individually) */
3917
3918 /* note that the operation initiator hard disk (which is
3919 * normally also the source hard disk) is a special case
3920 * -- there is one more caller added by Task to it which
3921 * we must release. Also, if we are in sync mode, the
3922 * caller may still hold an AutoCaller instance for it
3923 * and therefore we cannot uninit() it (it's therefore
3924 * the caller's responsibility) */
3925 if (pMedium == pDeleteRec->mpSource)
3926 {
3927 Assert(pDeleteRec->mpSource->i_getChildren().size() == 0);
3928 Assert(pDeleteRec->mpSource->i_getFirstMachineBackrefId() == NULL);
3929 }
3930
3931 /* Delete the medium lock list entry, which also releases the
3932 * caller added by MergeChain before uninit() and updates the
3933 * iterator to point to the right place. */
3934 rc = pMediumLockList->RemoveByIterator(it);
3935 AssertComRC(rc);
3936
3937 treeLock.release();
3938 pMedium->uninit();
3939 treeLock.acquire();
3940 }
3941
3942 /* Stop as soon as we reached the last medium affected by the merge.
3943 * The remaining images must be kept unchanged. */
3944 if (pMedium == pLast)
3945 break;
3946 }
3947
3948 /* Could be in principle folded into the previous loop, but let's keep
3949 * things simple. Update the medium locking to be the standard state:
3950 * all parent images locked for reading, just the last diff for writing. */
3951 lockListBegin = pMediumLockList->GetBegin();
3952 lockListEnd = pMediumLockList->GetEnd();
3953 MediumLockList::Base::iterator lockListLast = lockListEnd;
3954 --lockListLast;
3955 for (MediumLockList::Base::iterator it = lockListBegin;
3956 it != lockListEnd;
3957 ++it)
3958 {
3959 it->UpdateLock(it == lockListLast);
3960 }
3961
3962 /* If this is a backwards merge of the only remaining snapshot (i.e. the
3963 * source has no children) then update the medium associated with the
3964 * attachment, as the previously associated one (source) is now deleted.
3965 * Without the immediate update the VM could not continue running. */
3966 if (!pDeleteRec->mfMergeForward && !fSourceHasChildren)
3967 {
3968 AutoWriteLock attLock(pDeleteRec->mpOnlineMediumAttachment COMMA_LOCKVAL_SRC_POS);
3969 pDeleteRec->mpOnlineMediumAttachment->i_updateMedium(pDeleteRec->mpTarget);
3970 }
3971
3972 return S_OK;
3973}
3974
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