VirtualBox

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

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

Main/Snapshot: block deleting of current snapshot if it has child snapshots, as this would lead to VM config corruption, plus safety belts in the GUI and settings reader

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