VirtualBox

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

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