VirtualBox

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

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

Main: bugref:6913: Fixed macos compiler errors

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