VirtualBox

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

最後變更 在這個檔案從76238是 76238,由 vboxsync 提交於 6 年 前

Main: bugref:6913: Fixed use of already NULL reference to VirtualBox object, and straighten a misplaced log statement

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette