VirtualBox

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

Last change on this file since 50874 was 50874, checked in by vboxsync, 11 years ago

6813 src-all/ProgressImp.cpp + some formatting/line length sorting

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

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