VirtualBox

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

Last change on this file since 36580 was 36289, checked in by vboxsync, 14 years ago

Main/SnapshotImpl: when restoring a snapshot always save the global registry, see xtracker 5578

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