VirtualBox

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

Last change on this file since 65929 was 65103, checked in by vboxsync, 8 years ago

Main: doxygen fixes

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