VirtualBox

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

Last change on this file since 96407 was 96407, checked in by vboxsync, 3 years ago

scm copyright and license note update

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

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