VirtualBox

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

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

Main/SnapshotImpl: progressCallback not used anymore since r70196

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 121.1 KB
Line 
1/* $Id: SnapshotImpl.cpp 36188 2011-03-07 15:12:47Z 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.215389.xyz. 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 if (fNeedsGlobalSaveSettings)
1928 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, mParent->getGlobalRegistryId());
1929
1930 // let go of the locks while we're deleting image files below
1931 alock.leave();
1932 // from here on we cannot roll back on failure any more
1933
1934 for (MediaList::iterator it = llDiffsToDelete.begin();
1935 it != llDiffsToDelete.end();
1936 ++it)
1937 {
1938 ComObjPtr<Medium> &pMedium = *it;
1939 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->getName().c_str()));
1940
1941 HRESULT rc2 = pMedium->deleteStorage(NULL /* aProgress */,
1942 true /* aWait */,
1943 &llRegistriesThatNeedSaving);
1944 // ignore errors here because we cannot roll back after saveSettings() above
1945 if (SUCCEEDED(rc2))
1946 pMedium->uninit();
1947 }
1948 }
1949 catch (HRESULT aRC)
1950 {
1951 rc = aRC;
1952 }
1953
1954 if (FAILED(rc))
1955 {
1956 /* preserve existing error info */
1957 ErrorInfoKeeper eik;
1958
1959 /* undo all changes on failure */
1960 rollback(false /* aNotify */);
1961
1962 if (!stateRestored)
1963 {
1964 /* restore the machine state */
1965 setMachineState(aTask.machineStateBackup);
1966 updateMachineStateOnClient();
1967 }
1968 }
1969
1970 mParent->saveRegistries(llRegistriesThatNeedSaving);
1971
1972 /* set the result (this will try to fetch current error info on failure) */
1973 aTask.pProgress->notifyComplete(rc);
1974
1975 if (SUCCEEDED(rc))
1976 mParent->onSnapshotDeleted(mData->mUuid, Guid());
1977
1978 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
1979
1980 LogFlowThisFuncLeave();
1981}
1982
1983////////////////////////////////////////////////////////////////////////////////
1984//
1985// DeleteSnapshot methods (SessionMachine and related tasks)
1986//
1987////////////////////////////////////////////////////////////////////////////////
1988
1989/**
1990 * Implementation for IInternalMachineControl::deleteSnapshot().
1991 *
1992 * Gets called from Console::DeleteSnapshot(), and that's basically the
1993 * only thing Console does initially. Deleting a snapshot happens entirely on
1994 * the server side if the machine is not running, and if it is running then
1995 * the individual merges are done via internal session callbacks.
1996 *
1997 * This creates a new thread that does the work and returns a progress
1998 * object to the client which is then returned to the caller of
1999 * Console::DeleteSnapshot().
2000 *
2001 * Actual work then takes place in DeleteSnapshotTask::handler().
2002 *
2003 * @note Locks mParent + this + children objects for writing!
2004 */
2005STDMETHODIMP SessionMachine::DeleteSnapshot(IConsole *aInitiator,
2006 IN_BSTR aId,
2007 MachineState_T *aMachineState,
2008 IProgress **aProgress)
2009{
2010 LogFlowThisFuncEnter();
2011
2012 Guid id(aId);
2013 AssertReturn(aInitiator && !id.isEmpty(), E_INVALIDARG);
2014 AssertReturn(aMachineState && aProgress, E_POINTER);
2015
2016 AutoCaller autoCaller(this);
2017 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2018
2019 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2020
2021 // be very picky about machine states
2022 if ( Global::IsOnlineOrTransient(mData->mMachineState)
2023 && mData->mMachineState != MachineState_PoweredOff
2024 && mData->mMachineState != MachineState_Saved
2025 && mData->mMachineState != MachineState_Teleported
2026 && mData->mMachineState != MachineState_Aborted
2027 && mData->mMachineState != MachineState_Running
2028 && mData->mMachineState != MachineState_Paused)
2029 return setError(VBOX_E_INVALID_VM_STATE,
2030 tr("Invalid machine state: %s"),
2031 Global::stringifyMachineState(mData->mMachineState));
2032
2033 ComObjPtr<Snapshot> pSnapshot;
2034 HRESULT rc = findSnapshotById(id, pSnapshot, true /* aSetError */);
2035 if (FAILED(rc)) return rc;
2036
2037 AutoWriteLock snapshotLock(pSnapshot COMMA_LOCKVAL_SRC_POS);
2038
2039 size_t childrenCount = pSnapshot->getChildrenCount();
2040 if (childrenCount > 1)
2041 return setError(VBOX_E_INVALID_OBJECT_STATE,
2042 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"),
2043 pSnapshot->getName().c_str(),
2044 mUserData->s.strName.c_str(),
2045 childrenCount);
2046
2047 /* If the snapshot being deleted is the current one, ensure current
2048 * settings are committed and saved.
2049 */
2050 if (pSnapshot == mData->mCurrentSnapshot)
2051 {
2052 if (mData->flModifications)
2053 {
2054 rc = saveSettings(NULL);
2055 // no need to change for whether VirtualBox.xml needs saving since
2056 // we can't have a machine XML rename pending at this point
2057 if (FAILED(rc)) return rc;
2058 }
2059 }
2060
2061 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
2062
2063 /* create a progress object. The number of operations is:
2064 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
2065 */
2066 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2067
2068 ULONG ulOpCount = 1; // one for preparations
2069 ULONG ulTotalWeight = 1; // one for preparations
2070
2071 if (pSnapshot->getStateFilePath().length())
2072 {
2073 ++ulOpCount;
2074 ++ulTotalWeight; // assume 1 MB for deleting the state file
2075 }
2076
2077 // count normal hard disks and add their sizes to the weight
2078 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2079 it != pSnapMachine->mMediaData->mAttachments.end();
2080 ++it)
2081 {
2082 ComObjPtr<MediumAttachment> &pAttach = *it;
2083 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2084 if (pAttach->getType() == DeviceType_HardDisk)
2085 {
2086 ComObjPtr<Medium> pHD = pAttach->getMedium();
2087 Assert(pHD);
2088 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2089
2090 MediumType_T type = pHD->getType();
2091 // writethrough and shareable images are unaffected by snapshots,
2092 // so do nothing for them
2093 if ( type != MediumType_Writethrough
2094 && type != MediumType_Shareable
2095 && type != MediumType_Readonly)
2096 {
2097 // normal or immutable media need attention
2098 ++ulOpCount;
2099 ulTotalWeight += (ULONG)(pHD->getSize() / _1M);
2100 }
2101 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->getName().c_str()));
2102 }
2103 }
2104
2105 ComObjPtr<Progress> pProgress;
2106 pProgress.createObject();
2107 pProgress->init(mParent, aInitiator,
2108 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->getName().c_str()).raw(),
2109 FALSE /* aCancelable */,
2110 ulOpCount,
2111 ulTotalWeight,
2112 Bstr(tr("Setting up")).raw(),
2113 1);
2114
2115 bool fDeleteOnline = ( (mData->mMachineState == MachineState_Running)
2116 || (mData->mMachineState == MachineState_Paused));
2117
2118 /* create and start the task on a separate thread */
2119 DeleteSnapshotTask *task = new DeleteSnapshotTask(this, pProgress,
2120 fDeleteOnline, pSnapshot);
2121 int vrc = RTThreadCreate(NULL,
2122 taskHandler,
2123 (void*)task,
2124 0,
2125 RTTHREADTYPE_MAIN_WORKER,
2126 0,
2127 "DeleteSnapshot");
2128 if (RT_FAILURE(vrc))
2129 {
2130 delete task;
2131 return E_FAIL;
2132 }
2133
2134 // the task might start running but will block on acquiring the machine's write lock
2135 // which we acquired above; once this function leaves, the task will be unblocked;
2136 // set the proper machine state here now (note: after creating a Task instance)
2137 if (mData->mMachineState == MachineState_Running)
2138 setMachineState(MachineState_DeletingSnapshotOnline);
2139 else if (mData->mMachineState == MachineState_Paused)
2140 setMachineState(MachineState_DeletingSnapshotPaused);
2141 else
2142 setMachineState(MachineState_DeletingSnapshot);
2143
2144 /* return the progress to the caller */
2145 pProgress.queryInterfaceTo(aProgress);
2146
2147 /* return the new state to the caller */
2148 *aMachineState = mData->mMachineState;
2149
2150 LogFlowThisFuncLeave();
2151
2152 return S_OK;
2153}
2154
2155/**
2156 * Helper struct for SessionMachine::deleteSnapshotHandler().
2157 */
2158struct MediumDeleteRec
2159{
2160 MediumDeleteRec()
2161 : mfNeedsOnlineMerge(false),
2162 mpMediumLockList(NULL)
2163 {}
2164
2165 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2166 const ComObjPtr<Medium> &aSource,
2167 const ComObjPtr<Medium> &aTarget,
2168 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2169 bool fMergeForward,
2170 const ComObjPtr<Medium> &aParentForTarget,
2171 const MediaList &aChildrenToReparent,
2172 bool fNeedsOnlineMerge,
2173 MediumLockList *aMediumLockList)
2174 : mpHD(aHd),
2175 mpSource(aSource),
2176 mpTarget(aTarget),
2177 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2178 mfMergeForward(fMergeForward),
2179 mpParentForTarget(aParentForTarget),
2180 mChildrenToReparent(aChildrenToReparent),
2181 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2182 mpMediumLockList(aMediumLockList)
2183 {}
2184
2185 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2186 const ComObjPtr<Medium> &aSource,
2187 const ComObjPtr<Medium> &aTarget,
2188 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2189 bool fMergeForward,
2190 const ComObjPtr<Medium> &aParentForTarget,
2191 const MediaList &aChildrenToReparent,
2192 bool fNeedsOnlineMerge,
2193 MediumLockList *aMediumLockList,
2194 const Guid &aMachineId,
2195 const Guid &aSnapshotId)
2196 : mpHD(aHd),
2197 mpSource(aSource),
2198 mpTarget(aTarget),
2199 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2200 mfMergeForward(fMergeForward),
2201 mpParentForTarget(aParentForTarget),
2202 mChildrenToReparent(aChildrenToReparent),
2203 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2204 mpMediumLockList(aMediumLockList),
2205 mMachineId(aMachineId),
2206 mSnapshotId(aSnapshotId)
2207 {}
2208
2209 ComObjPtr<Medium> mpHD;
2210 ComObjPtr<Medium> mpSource;
2211 ComObjPtr<Medium> mpTarget;
2212 ComObjPtr<MediumAttachment> mpOnlineMediumAttachment;
2213 bool mfMergeForward;
2214 ComObjPtr<Medium> mpParentForTarget;
2215 MediaList mChildrenToReparent;
2216 bool mfNeedsOnlineMerge;
2217 MediumLockList *mpMediumLockList;
2218 /* these are for reattaching the hard disk in case of a failure: */
2219 Guid mMachineId;
2220 Guid mSnapshotId;
2221};
2222
2223typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2224
2225/**
2226 * Worker method for the delete snapshot thread created by
2227 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2228 * through SessionMachine::taskHandler() which then calls
2229 * DeleteSnapshotTask::handler().
2230 *
2231 * The DeleteSnapshotTask contains the progress object returned to the console
2232 * by SessionMachine::DeleteSnapshot, through which progress and results are
2233 * reported.
2234 *
2235 * SessionMachine::DeleteSnapshot() has set the machine state to
2236 * MachineState_DeletingSnapshot right after creating this task. Since we block
2237 * on the machine write lock at the beginning, once that has been acquired, we
2238 * can assume that the machine state is indeed that.
2239 *
2240 * @note Locks the machine + the snapshot + the media tree for writing!
2241 *
2242 * @param aTask Task data.
2243 */
2244
2245void SessionMachine::deleteSnapshotHandler(DeleteSnapshotTask &aTask)
2246{
2247 LogFlowThisFuncEnter();
2248
2249 AutoCaller autoCaller(this);
2250
2251 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
2252 if (!autoCaller.isOk())
2253 {
2254 /* we might have been uninitialized because the session was accidentally
2255 * closed by the client, so don't assert */
2256 aTask.pProgress->notifyComplete(E_FAIL,
2257 COM_IIDOF(IMachine),
2258 getComponentName(),
2259 tr("The session has been accidentally closed"));
2260 LogFlowThisFuncLeave();
2261 return;
2262 }
2263
2264 MediumDeleteRecList toDelete;
2265
2266 HRESULT rc = S_OK;
2267
2268 GuidList llRegistriesThatNeedSaving;
2269
2270 Guid snapshotId;
2271
2272 try
2273 {
2274 /* Locking order: */
2275 AutoMultiWriteLock3 multiLock(this->lockHandle(), // machine
2276 aTask.pSnapshot->lockHandle(), // snapshot
2277 &mParent->getMediaTreeLockHandle() // media tree
2278 COMMA_LOCKVAL_SRC_POS);
2279 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2280 // has exited after setting the machine state to MachineState_DeletingSnapshot
2281
2282 ComObjPtr<SnapshotMachine> pSnapMachine = aTask.pSnapshot->getSnapshotMachine();
2283 // no need to lock the snapshot machine since it is const by definition
2284 Guid machineId = pSnapMachine->getId();
2285
2286 // save the snapshot ID (for callbacks)
2287 snapshotId = aTask.pSnapshot->getId();
2288
2289 // first pass:
2290 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2291
2292 // Go thru the attachments of the snapshot machine (the media in here
2293 // point to the disk states _before_ the snapshot was taken, i.e. the
2294 // state we're restoring to; for each such medium, we will need to
2295 // merge it with its one and only child (the diff image holding the
2296 // changes written after the snapshot was taken).
2297 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2298 it != pSnapMachine->mMediaData->mAttachments.end();
2299 ++it)
2300 {
2301 ComObjPtr<MediumAttachment> &pAttach = *it;
2302 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2303 if (pAttach->getType() != DeviceType_HardDisk)
2304 continue;
2305
2306 ComObjPtr<Medium> pHD = pAttach->getMedium();
2307 Assert(!pHD.isNull());
2308
2309 {
2310 // writethrough, shareable and readonly images are
2311 // unaffected by snapshots, skip them
2312 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
2313 MediumType_T type = pHD->getType();
2314 if ( type == MediumType_Writethrough
2315 || type == MediumType_Shareable
2316 || type == MediumType_Readonly)
2317 continue;
2318 }
2319
2320#ifdef DEBUG
2321 pHD->dumpBackRefs();
2322#endif
2323
2324 // needs to be merged with child or deleted, check prerequisites
2325 ComObjPtr<Medium> pTarget;
2326 ComObjPtr<Medium> pSource;
2327 bool fMergeForward = false;
2328 ComObjPtr<Medium> pParentForTarget;
2329 MediaList childrenToReparent;
2330 bool fNeedsOnlineMerge = false;
2331 bool fOnlineMergePossible = aTask.m_fDeleteOnline;
2332 MediumLockList *pMediumLockList = NULL;
2333 MediumLockList *pVMMALockList = NULL;
2334 ComObjPtr<MediumAttachment> pOnlineMediumAttachment;
2335 if (fOnlineMergePossible)
2336 {
2337 // Look up the corresponding medium attachment in the currently
2338 // running VM. Any failure prevents a live merge. Could be made
2339 // a tad smarter by trying a few candidates, so that e.g. disks
2340 // which are simply moved to a different controller slot do not
2341 // prevent online merging in general.
2342 pOnlineMediumAttachment =
2343 findAttachment(mMediaData->mAttachments,
2344 pAttach->getControllerName().raw(),
2345 pAttach->getPort(),
2346 pAttach->getDevice());
2347 if (pOnlineMediumAttachment)
2348 {
2349 rc = mData->mSession.mLockedMedia.Get(pOnlineMediumAttachment,
2350 pVMMALockList);
2351 if (FAILED(rc))
2352 fOnlineMergePossible = false;
2353 }
2354 else
2355 fOnlineMergePossible = false;
2356 }
2357 rc = prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
2358 fOnlineMergePossible,
2359 pVMMALockList, pSource, pTarget,
2360 fMergeForward, pParentForTarget,
2361 childrenToReparent,
2362 fNeedsOnlineMerge,
2363 pMediumLockList);
2364 if (FAILED(rc))
2365 throw rc;
2366
2367 // no need to hold the lock any longer
2368 attachLock.release();
2369
2370 // For simplicity, prepareDeleteSnapshotMedium selects the merge
2371 // direction in the following way: we merge pHD onto its child
2372 // (forward merge), not the other way round, because that saves us
2373 // from unnecessarily shuffling around the attachments for the
2374 // machine that follows the snapshot (next snapshot or current
2375 // state), unless it's a base image. Backwards merges of the first
2376 // snapshot into the base image is essential, as it ensures that
2377 // when all snapshots are deleted the only remaining image is a
2378 // base image. Important e.g. for medium formats which do not have
2379 // a file representation such as iSCSI.
2380
2381 // a couple paranoia checks for backward merges
2382 if (pMediumLockList != NULL && !fMergeForward)
2383 {
2384 // parent is null -> this disk is a base hard disk: we will
2385 // then do a backward merge, i.e. merge its only child onto the
2386 // base disk. Here we need then to update the attachment that
2387 // refers to the child and have it point to the parent instead
2388 Assert(pHD->getParent().isNull());
2389 Assert(pHD->getChildren().size() == 1);
2390
2391 ComObjPtr<Medium> pReplaceHD = pHD->getChildren().front();
2392
2393 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
2394 }
2395
2396 Guid replaceMachineId;
2397 Guid replaceSnapshotId;
2398
2399 const Guid *pReplaceMachineId = pSource->getFirstMachineBackrefId();
2400 // minimal sanity checking
2401 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
2402 if (pReplaceMachineId)
2403 replaceMachineId = *pReplaceMachineId;
2404
2405 const Guid *pSnapshotId = pSource->getFirstMachineBackrefSnapshotId();
2406 if (pSnapshotId)
2407 replaceSnapshotId = *pSnapshotId;
2408
2409 if (!replaceMachineId.isEmpty())
2410 {
2411 // Adjust the backreferences, otherwise merging will assert.
2412 // Note that the medium attachment object stays associated
2413 // with the snapshot until the merge was successful.
2414 HRESULT rc2 = S_OK;
2415 rc2 = pSource->removeBackReference(replaceMachineId, replaceSnapshotId);
2416 AssertComRC(rc2);
2417
2418 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2419 pOnlineMediumAttachment,
2420 fMergeForward,
2421 pParentForTarget,
2422 childrenToReparent,
2423 fNeedsOnlineMerge,
2424 pMediumLockList,
2425 replaceMachineId,
2426 replaceSnapshotId));
2427 }
2428 else
2429 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2430 pOnlineMediumAttachment,
2431 fMergeForward,
2432 pParentForTarget,
2433 childrenToReparent,
2434 fNeedsOnlineMerge,
2435 pMediumLockList));
2436 }
2437
2438 // we can release the lock now since the machine state is MachineState_DeletingSnapshot
2439 multiLock.release();
2440
2441 /* Now we checked that we can successfully merge all normal hard disks
2442 * (unless a runtime error like end-of-disc happens). Now get rid of
2443 * the saved state (if present), as that will free some disk space.
2444 * The snapshot itself will be deleted as late as possible, so that
2445 * the user can repeat the delete operation if he runs out of disk
2446 * space or cancels the delete operation. */
2447
2448 /* second pass: */
2449 LogFlowThisFunc(("2: Deleting saved state...\n"));
2450
2451 {
2452 // saveAllSnapshots() needs a machine lock, and the snapshots
2453 // tree is protected by the machine lock as well
2454 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2455
2456 Utf8Str stateFilePath = aTask.pSnapshot->getStateFilePath();
2457 if (!stateFilePath.isEmpty())
2458 {
2459 aTask.pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")).raw(),
2460 1); // weight
2461
2462 releaseSavedStateFile(stateFilePath, aTask.pSnapshot /* pSnapshotToIgnore */);
2463
2464 // machine will need saving now
2465 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, getId());
2466 }
2467 }
2468
2469 /* third pass: */
2470 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
2471
2472 /// @todo NEWMEDIA turn the following errors into warnings because the
2473 /// snapshot itself has been already deleted (and interpret these
2474 /// warnings properly on the GUI side)
2475 for (MediumDeleteRecList::iterator it = toDelete.begin();
2476 it != toDelete.end();)
2477 {
2478 const ComObjPtr<Medium> &pMedium(it->mpHD);
2479 ULONG ulWeight;
2480
2481 {
2482 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
2483 ulWeight = (ULONG)(pMedium->getSize() / _1M);
2484 }
2485
2486 aTask.pProgress->SetNextOperation(BstrFmt(tr("Merging differencing image '%s'"),
2487 pMedium->getName().c_str()).raw(),
2488 ulWeight);
2489
2490 bool fNeedSourceUninit = false;
2491 bool fReparentTarget = false;
2492 if (it->mpMediumLockList == NULL)
2493 {
2494 /* no real merge needed, just updating state and delete
2495 * diff files if necessary */
2496 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
2497
2498 Assert( !it->mfMergeForward
2499 || pMedium->getChildren().size() == 0);
2500
2501 /* Delete the differencing hard disk (has no children). Two
2502 * exceptions: if it's the last medium in the chain or if it's
2503 * a backward merge we don't want to handle due to complexity.
2504 * In both cases leave the image in place. If it's the first
2505 * exception the user can delete it later if he wants. */
2506 if (!pMedium->getParent().isNull())
2507 {
2508 Assert(pMedium->getState() == MediumState_Deleting);
2509 /* No need to hold the lock any longer. */
2510 mLock.release();
2511 rc = pMedium->deleteStorage(&aTask.pProgress,
2512 true /* aWait */,
2513 &llRegistriesThatNeedSaving);
2514 if (FAILED(rc))
2515 throw rc;
2516
2517 // need to uninit the deleted medium
2518 fNeedSourceUninit = true;
2519 }
2520 }
2521 else
2522 {
2523 bool fNeedsSave = false;
2524 if (it->mfNeedsOnlineMerge)
2525 {
2526 // online medium merge, in the direction decided earlier
2527 rc = onlineMergeMedium(it->mpOnlineMediumAttachment,
2528 it->mpSource,
2529 it->mpTarget,
2530 it->mfMergeForward,
2531 it->mpParentForTarget,
2532 it->mChildrenToReparent,
2533 it->mpMediumLockList,
2534 aTask.pProgress,
2535 &fNeedsSave);
2536 }
2537 else
2538 {
2539 // normal medium merge, in the direction decided earlier
2540 rc = it->mpSource->mergeTo(it->mpTarget,
2541 it->mfMergeForward,
2542 it->mpParentForTarget,
2543 it->mChildrenToReparent,
2544 it->mpMediumLockList,
2545 &aTask.pProgress,
2546 true /* aWait */,
2547 &llRegistriesThatNeedSaving);
2548 }
2549
2550 // If the merge failed, we need to do our best to have a usable
2551 // VM configuration afterwards. The return code doesn't tell
2552 // whether the merge completed and so we have to check if the
2553 // source medium (diff images are always file based at the
2554 // moment) is still there or not. Be careful not to lose the
2555 // error code below, before the "Delayed failure exit".
2556 if (FAILED(rc))
2557 {
2558 AutoReadLock mlock(it->mpSource COMMA_LOCKVAL_SRC_POS);
2559 if (!it->mpSource->isMediumFormatFile())
2560 // Diff medium not backed by a file - cannot get status so
2561 // be pessimistic.
2562 throw rc;
2563 const Utf8Str &loc = it->mpSource->getLocationFull();
2564 // Source medium is still there, so merge failed early.
2565 if (RTFileExists(loc.c_str()))
2566 throw rc;
2567
2568 // Source medium is gone. Assume the merge succeeded and
2569 // thus it's safe to remove the attachment. We use the
2570 // "Delayed failure exit" below.
2571 }
2572
2573 // need to change the medium attachment for backward merges
2574 fReparentTarget = !it->mfMergeForward;
2575
2576 if (!it->mfNeedsOnlineMerge)
2577 {
2578 // need to uninit the medium deleted by the merge
2579 fNeedSourceUninit = true;
2580
2581 // delete the no longer needed medium lock list, which
2582 // implicitly handled the unlocking
2583 delete it->mpMediumLockList;
2584 it->mpMediumLockList = NULL;
2585 }
2586 }
2587
2588 // Now that the medium is successfully merged/deleted/whatever,
2589 // remove the medium attachment from the snapshot. For a backwards
2590 // merge the target attachment needs to be removed from the
2591 // snapshot, as the VM will take it over. For forward merges the
2592 // source medium attachment needs to be removed.
2593 ComObjPtr<MediumAttachment> pAtt;
2594 if (fReparentTarget)
2595 {
2596 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2597 it->mpTarget);
2598 it->mpTarget->removeBackReference(machineId, snapshotId);
2599 }
2600 else
2601 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2602 it->mpSource);
2603 pSnapMachine->mMediaData->mAttachments.remove(pAtt);
2604
2605 if (fReparentTarget)
2606 {
2607 // Search for old source attachment and replace with target.
2608 // There can be only one child snapshot in this case.
2609 ComObjPtr<Machine> pMachine = this;
2610 Guid childSnapshotId;
2611 ComObjPtr<Snapshot> pChildSnapshot = aTask.pSnapshot->getFirstChild();
2612 if (pChildSnapshot)
2613 {
2614 pMachine = pChildSnapshot->getSnapshotMachine();
2615 childSnapshotId = pChildSnapshot->getId();
2616 }
2617 pAtt = findAttachment(pMachine->mMediaData->mAttachments, it->mpSource);
2618 if (pAtt)
2619 {
2620 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
2621 pAtt->updateMedium(it->mpTarget);
2622 it->mpTarget->addBackReference(pMachine->mData->mUuid, childSnapshotId);
2623 }
2624 else
2625 {
2626 // If no attachment is found do not change anything. Maybe
2627 // the source medium was not attached to the snapshot.
2628 // If this is an online deletion the attachment was updated
2629 // already to allow the VM continue execution immediately.
2630 // Needs a bit of special treatment due to this difference.
2631 if (it->mfNeedsOnlineMerge)
2632 it->mpTarget->addBackReference(pMachine->mData->mUuid, childSnapshotId);
2633 }
2634 }
2635
2636 if (fNeedSourceUninit)
2637 it->mpSource->uninit();
2638
2639 // One attachment is merged, must save the settings
2640 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, getId());
2641
2642 // prevent calling cancelDeleteSnapshotMedium() for this attachment
2643 it = toDelete.erase(it);
2644
2645 // Delayed failure exit when the merge cleanup failed but the
2646 // merge actually succeeded.
2647 if (FAILED(rc))
2648 throw rc;
2649 }
2650
2651 {
2652 // beginSnapshotDelete() needs the machine lock, and the snapshots
2653 // tree is protected by the machine lock as well
2654 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2655
2656 aTask.pSnapshot->beginSnapshotDelete();
2657 aTask.pSnapshot->uninit();
2658
2659 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, getId());
2660 }
2661 }
2662 catch (HRESULT aRC) { rc = aRC; }
2663
2664 if (FAILED(rc))
2665 {
2666 // preserve existing error info so that the result can
2667 // be properly reported to the progress object below
2668 ErrorInfoKeeper eik;
2669
2670 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2671 &mParent->getMediaTreeLockHandle() // media tree
2672 COMMA_LOCKVAL_SRC_POS);
2673
2674 // un-prepare the remaining hard disks
2675 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
2676 it != toDelete.end();
2677 ++it)
2678 {
2679 cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
2680 it->mChildrenToReparent,
2681 it->mfNeedsOnlineMerge,
2682 it->mpMediumLockList, it->mMachineId,
2683 it->mSnapshotId);
2684 }
2685 }
2686
2687 // whether we were successful or not, we need to set the machine
2688 // state and save the machine settings;
2689 {
2690 // preserve existing error info so that the result can
2691 // be properly reported to the progress object below
2692 ErrorInfoKeeper eik;
2693
2694 // restore the machine state that was saved when the
2695 // task was started
2696 setMachineState(aTask.machineStateBackup);
2697 updateMachineStateOnClient();
2698
2699 mParent->saveRegistries(llRegistriesThatNeedSaving);
2700 }
2701
2702 // report the result (this will try to fetch current error info on failure)
2703 aTask.pProgress->notifyComplete(rc);
2704
2705 if (SUCCEEDED(rc))
2706 mParent->onSnapshotDeleted(mData->mUuid, snapshotId);
2707
2708 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", rc));
2709 LogFlowThisFuncLeave();
2710}
2711
2712/**
2713 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
2714 * performs necessary state changes. Must not be called for writethrough disks
2715 * because there is nothing to delete/merge then.
2716 *
2717 * This method is to be called prior to calling #deleteSnapshotMedium().
2718 * If #deleteSnapshotMedium() is not called or fails, the state modifications
2719 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
2720 *
2721 * @return COM status code
2722 * @param aHD Hard disk which is connected to the snapshot.
2723 * @param aMachineId UUID of machine this hard disk is attached to.
2724 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
2725 * be a zero UUID if no snapshot is applicable.
2726 * @param fOnlineMergePossible Flag whether an online merge is possible.
2727 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
2728 * Only used if @a fOnlineMergePossible is @c true, and
2729 * must be non-NULL in this case.
2730 * @param aSource Source hard disk for merge (out).
2731 * @param aTarget Target hard disk for merge (out).
2732 * @param aMergeForward Merge direction decision (out).
2733 * @param aParentForTarget New parent if target needs to be reparented (out).
2734 * @param aChildrenToReparent Children which have to be reparented to the
2735 * target (out).
2736 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
2737 * If this is set to @a true then the @a aVMMALockList
2738 * parameter has been modified and is returned as
2739 * @a aMediumLockList.
2740 * @param aMediumLockList Where to store the created medium lock list (may
2741 * return NULL if no real merge is necessary).
2742 *
2743 * @note Caller must hold media tree lock for writing. This locks this object
2744 * and every medium object on the merge chain for writing.
2745 */
2746HRESULT SessionMachine::prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
2747 const Guid &aMachineId,
2748 const Guid &aSnapshotId,
2749 bool fOnlineMergePossible,
2750 MediumLockList *aVMMALockList,
2751 ComObjPtr<Medium> &aSource,
2752 ComObjPtr<Medium> &aTarget,
2753 bool &aMergeForward,
2754 ComObjPtr<Medium> &aParentForTarget,
2755 MediaList &aChildrenToReparent,
2756 bool &fNeedsOnlineMerge,
2757 MediumLockList * &aMediumLockList)
2758{
2759 Assert(mParent->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
2760 Assert(!fOnlineMergePossible || VALID_PTR(aVMMALockList));
2761
2762 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
2763
2764 // Medium must not be writethrough/shareable/readonly at this point
2765 MediumType_T type = aHD->getType();
2766 AssertReturn( type != MediumType_Writethrough
2767 && type != MediumType_Shareable
2768 && type != MediumType_Readonly, E_FAIL);
2769
2770 aMediumLockList = NULL;
2771 fNeedsOnlineMerge = false;
2772
2773 if (aHD->getChildren().size() == 0)
2774 {
2775 /* This technically is no merge, set those values nevertheless.
2776 * Helps with updating the medium attachments. */
2777 aSource = aHD;
2778 aTarget = aHD;
2779
2780 /* special treatment of the last hard disk in the chain: */
2781 if (aHD->getParent().isNull())
2782 {
2783 /* lock only, to prevent any usage until the snapshot deletion
2784 * is completed */
2785 return aHD->LockWrite(NULL);
2786 }
2787
2788 /* the differencing hard disk w/o children will be deleted, protect it
2789 * from attaching to other VMs (this is why Deleting) */
2790 return aHD->markForDeletion();
2791 }
2792
2793 /* not going multi-merge as it's too expensive */
2794 if (aHD->getChildren().size() > 1)
2795 return setError(E_FAIL,
2796 tr("Hard disk '%s' has more than one child hard disk (%d)"),
2797 aHD->getLocationFull().c_str(),
2798 aHD->getChildren().size());
2799
2800 ComObjPtr<Medium> pChild = aHD->getChildren().front();
2801
2802 /* we keep this locked, so lock the affected child to make sure the lock
2803 * order is correct when calling prepareMergeTo() */
2804 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
2805
2806 /* the rest is a normal merge setup */
2807 if (aHD->getParent().isNull())
2808 {
2809 /* base hard disk, backward merge */
2810 const Guid *pMachineId1 = pChild->getFirstMachineBackrefId();
2811 const Guid *pMachineId2 = aHD->getFirstMachineBackrefId();
2812 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
2813 {
2814 /* backward merge is too tricky, we'll just detach on snapshot
2815 * deletion, so lock only, to prevent any usage */
2816 return aHD->LockWrite(NULL);
2817 }
2818
2819 aSource = pChild;
2820 aTarget = aHD;
2821 }
2822 else
2823 {
2824 /* forward merge */
2825 aSource = aHD;
2826 aTarget = pChild;
2827 }
2828
2829 HRESULT rc;
2830 rc = aSource->prepareMergeTo(aTarget, &aMachineId, &aSnapshotId,
2831 !fOnlineMergePossible /* fLockMedia */,
2832 aMergeForward, aParentForTarget,
2833 aChildrenToReparent, aMediumLockList);
2834 if (SUCCEEDED(rc) && fOnlineMergePossible)
2835 {
2836 /* Try to lock the newly constructed medium lock list. If it succeeds
2837 * this can be handled as an offline merge, i.e. without the need of
2838 * asking the VM to do the merging. Only continue with the online
2839 * merging preparation if applicable. */
2840 rc = aMediumLockList->Lock();
2841 if (FAILED(rc) && fOnlineMergePossible)
2842 {
2843 /* Locking failed, this cannot be done as an offline merge. Try to
2844 * combine the locking information into the lock list of the medium
2845 * attachment in the running VM. If that fails or locking the
2846 * resulting lock list fails then the merge cannot be done online.
2847 * It can be repeated by the user when the VM is shut down. */
2848 MediumLockList::Base::iterator lockListVMMABegin =
2849 aVMMALockList->GetBegin();
2850 MediumLockList::Base::iterator lockListVMMAEnd =
2851 aVMMALockList->GetEnd();
2852 MediumLockList::Base::iterator lockListBegin =
2853 aMediumLockList->GetBegin();
2854 MediumLockList::Base::iterator lockListEnd =
2855 aMediumLockList->GetEnd();
2856 for (MediumLockList::Base::iterator it = lockListVMMABegin,
2857 it2 = lockListBegin;
2858 it2 != lockListEnd;
2859 ++it, ++it2)
2860 {
2861 if ( it == lockListVMMAEnd
2862 || it->GetMedium() != it2->GetMedium())
2863 {
2864 fOnlineMergePossible = false;
2865 break;
2866 }
2867 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
2868 rc = it->UpdateLock(fLockReq);
2869 if (FAILED(rc))
2870 {
2871 // could not update the lock, trigger cleanup below
2872 fOnlineMergePossible = false;
2873 break;
2874 }
2875 }
2876
2877 if (fOnlineMergePossible)
2878 {
2879 /* we will lock the children of the source for reparenting */
2880 for (MediaList::const_iterator it = aChildrenToReparent.begin();
2881 it != aChildrenToReparent.end();
2882 ++it)
2883 {
2884 ComObjPtr<Medium> pMedium = *it;
2885 if (pMedium->getState() == MediumState_Created)
2886 {
2887 rc = pMedium->LockWrite(NULL);
2888 if (FAILED(rc))
2889 throw rc;
2890 }
2891 else
2892 {
2893 rc = aVMMALockList->Update(pMedium, true);
2894 if (FAILED(rc))
2895 {
2896 rc = pMedium->LockWrite(NULL);
2897 if (FAILED(rc))
2898 throw rc;
2899 }
2900 }
2901 }
2902 }
2903
2904 if (fOnlineMergePossible)
2905 {
2906 rc = aVMMALockList->Lock();
2907 if (FAILED(rc))
2908 {
2909 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2910 rc = setError(rc,
2911 tr("Cannot lock hard disk '%s' for a live merge"),
2912 aHD->getLocationFull().c_str());
2913 }
2914 else
2915 {
2916 delete aMediumLockList;
2917 aMediumLockList = aVMMALockList;
2918 fNeedsOnlineMerge = true;
2919 }
2920 }
2921 else
2922 {
2923 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2924 rc = setError(rc,
2925 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
2926 aHD->getLocationFull().c_str());
2927 }
2928
2929 // fix the VM's lock list if anything failed
2930 if (FAILED(rc))
2931 {
2932 lockListVMMABegin = aVMMALockList->GetBegin();
2933 lockListVMMAEnd = aVMMALockList->GetEnd();
2934 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
2935 lockListLast--;
2936 for (MediumLockList::Base::iterator it = lockListVMMABegin;
2937 it != lockListVMMAEnd;
2938 ++it)
2939 {
2940 it->UpdateLock(it == lockListLast);
2941 ComObjPtr<Medium> pMedium = it->GetMedium();
2942 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
2943 // blindly apply this, only needed for medium objects which
2944 // would be deleted as part of the merge
2945 pMedium->unmarkLockedForDeletion();
2946 }
2947 }
2948
2949 }
2950 else
2951 {
2952 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2953 rc = setError(rc,
2954 tr("Cannot lock hard disk '%s' for an offline merge"),
2955 aHD->getLocationFull().c_str());
2956 }
2957 }
2958
2959 return rc;
2960}
2961
2962/**
2963 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
2964 * what #prepareDeleteSnapshotMedium() did. Must be called if
2965 * #deleteSnapshotMedium() is not called or fails.
2966 *
2967 * @param aHD Hard disk which is connected to the snapshot.
2968 * @param aSource Source hard disk for merge.
2969 * @param aChildrenToReparent Children to unlock.
2970 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
2971 * @param aMediumLockList Medium locks to cancel.
2972 * @param aMachineId Machine id to attach the medium to.
2973 * @param aSnapshotId Snapshot id to attach the medium to.
2974 *
2975 * @note Locks the medium tree and the hard disks in the chain for writing.
2976 */
2977void SessionMachine::cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
2978 const ComObjPtr<Medium> &aSource,
2979 const MediaList &aChildrenToReparent,
2980 bool fNeedsOnlineMerge,
2981 MediumLockList *aMediumLockList,
2982 const Guid &aMachineId,
2983 const Guid &aSnapshotId)
2984{
2985 if (aMediumLockList == NULL)
2986 {
2987 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
2988
2989 Assert(aHD->getChildren().size() == 0);
2990
2991 if (aHD->getParent().isNull())
2992 {
2993 HRESULT rc = aHD->UnlockWrite(NULL);
2994 AssertComRC(rc);
2995 }
2996 else
2997 {
2998 HRESULT rc = aHD->unmarkForDeletion();
2999 AssertComRC(rc);
3000 }
3001 }
3002 else
3003 {
3004 if (fNeedsOnlineMerge)
3005 {
3006 // Online merge uses the medium lock list of the VM, so give
3007 // an empty list to cancelMergeTo so that it works as designed.
3008 aSource->cancelMergeTo(aChildrenToReparent, new MediumLockList());
3009
3010 // clean up the VM medium lock list ourselves
3011 MediumLockList::Base::iterator lockListBegin =
3012 aMediumLockList->GetBegin();
3013 MediumLockList::Base::iterator lockListEnd =
3014 aMediumLockList->GetEnd();
3015 MediumLockList::Base::iterator lockListLast = lockListEnd;
3016 lockListLast--;
3017 for (MediumLockList::Base::iterator it = lockListBegin;
3018 it != lockListEnd;
3019 ++it)
3020 {
3021 ComObjPtr<Medium> pMedium = it->GetMedium();
3022 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3023 if (pMedium->getState() == MediumState_Deleting)
3024 pMedium->unmarkForDeletion();
3025 else
3026 {
3027 // blindly apply this, only needed for medium objects which
3028 // would be deleted as part of the merge
3029 pMedium->unmarkLockedForDeletion();
3030 }
3031 it->UpdateLock(it == lockListLast);
3032 }
3033 }
3034 else
3035 {
3036 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
3037 }
3038 }
3039
3040 if (!aMachineId.isEmpty())
3041 {
3042 // reattach the source media to the snapshot
3043 HRESULT rc = aSource->addBackReference(aMachineId, aSnapshotId);
3044 AssertComRC(rc);
3045 }
3046}
3047
3048/**
3049 * Perform an online merge of a hard disk, i.e. the equivalent of
3050 * Medium::mergeTo(), just for running VMs. If this fails you need to call
3051 * #cancelDeleteSnapshotMedium().
3052 *
3053 * @return COM status code
3054 * @param aMediumAttachment Identify where the disk is attached in the VM.
3055 * @param aSource Source hard disk for merge.
3056 * @param aTarget Target hard disk for merge.
3057 * @param aMergeForward Merge direction.
3058 * @param aParentForTarget New parent if target needs to be reparented.
3059 * @param aChildrenToReparent Children which have to be reparented to the
3060 * target.
3061 * @param aMediumLockList Where to store the created medium lock list (may
3062 * return NULL if no real merge is necessary).
3063 * @param aProgress Progress indicator.
3064 * @param pfNeedsMachineSaveSettings Whether the VM settings need to be saved (out).
3065 */
3066HRESULT SessionMachine::onlineMergeMedium(const ComObjPtr<MediumAttachment> &aMediumAttachment,
3067 const ComObjPtr<Medium> &aSource,
3068 const ComObjPtr<Medium> &aTarget,
3069 bool fMergeForward,
3070 const ComObjPtr<Medium> &aParentForTarget,
3071 const MediaList &aChildrenToReparent,
3072 MediumLockList *aMediumLockList,
3073 ComObjPtr<Progress> &aProgress,
3074 bool *pfNeedsMachineSaveSettings)
3075{
3076 AssertReturn(aSource != NULL, E_FAIL);
3077 AssertReturn(aTarget != NULL, E_FAIL);
3078 AssertReturn(aSource != aTarget, E_FAIL);
3079 AssertReturn(aMediumLockList != NULL, E_FAIL);
3080
3081 HRESULT rc = S_OK;
3082
3083 try
3084 {
3085 // Similar code appears in Medium::taskMergeHandle, so
3086 // if you make any changes below check whether they are applicable
3087 // in that context as well.
3088
3089 unsigned uTargetIdx = (unsigned)-1;
3090 unsigned uSourceIdx = (unsigned)-1;
3091 /* Sanity check all hard disks in the chain. */
3092 MediumLockList::Base::iterator lockListBegin =
3093 aMediumLockList->GetBegin();
3094 MediumLockList::Base::iterator lockListEnd =
3095 aMediumLockList->GetEnd();
3096 unsigned i = 0;
3097 for (MediumLockList::Base::iterator it = lockListBegin;
3098 it != lockListEnd;
3099 ++it)
3100 {
3101 MediumLock &mediumLock = *it;
3102 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
3103
3104 if (pMedium == aSource)
3105 uSourceIdx = i;
3106 else if (pMedium == aTarget)
3107 uTargetIdx = i;
3108
3109 // In Medium::taskMergeHandler there is lots of consistency
3110 // checking which we cannot do here, as the state details are
3111 // impossible to get outside the Medium class. The locking should
3112 // have done the checks already.
3113
3114 i++;
3115 }
3116
3117 ComAssertThrow( uSourceIdx != (unsigned)-1
3118 && uTargetIdx != (unsigned)-1, E_FAIL);
3119
3120 // For forward merges, tell the VM what images need to have their
3121 // parent UUID updated. This cannot be done in VBoxSVC, as opening
3122 // the required parent images is not safe while the VM is running.
3123 // For backward merges this will be simply an array of size 0.
3124 com::SafeIfaceArray<IMedium> childrenToReparent(aChildrenToReparent);
3125
3126 ComPtr<IInternalSessionControl> directControl;
3127 {
3128 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3129
3130 if (mData->mSession.mState != SessionState_Locked)
3131 throw setError(VBOX_E_INVALID_VM_STATE,
3132 tr("Machine is not locked by a session (session state: %s)"),
3133 Global::stringifySessionState(mData->mSession.mState));
3134 directControl = mData->mSession.mDirectControl;
3135 }
3136
3137 // Must not hold any locks here, as this will call back to finish
3138 // updating the medium attachment, chain linking and state.
3139 rc = directControl->OnlineMergeMedium(aMediumAttachment,
3140 uSourceIdx, uTargetIdx,
3141 aSource, aTarget,
3142 fMergeForward, aParentForTarget,
3143 ComSafeArrayAsInParam(childrenToReparent),
3144 aProgress);
3145 if (FAILED(rc))
3146 throw rc;
3147 }
3148 catch (HRESULT aRC) { rc = aRC; }
3149
3150 // The callback mentioned above takes care of update the medium state
3151
3152 if (pfNeedsMachineSaveSettings)
3153 *pfNeedsMachineSaveSettings = true;
3154
3155 return rc;
3156}
3157
3158/**
3159 * Implementation for IInternalMachineControl::finishOnlineMergeMedium().
3160 *
3161 * Gets called after the successful completion of an online merge from
3162 * Console::onlineMergeMedium(), which gets invoked indirectly above in
3163 * the call to IInternalSessionControl::onlineMergeMedium.
3164 *
3165 * This updates the medium information and medium state so that the VM
3166 * can continue with the updated state of the medium chain.
3167 */
3168STDMETHODIMP SessionMachine::FinishOnlineMergeMedium(IMediumAttachment *aMediumAttachment,
3169 IMedium *aSource,
3170 IMedium *aTarget,
3171 BOOL aMergeForward,
3172 IMedium *aParentForTarget,
3173 ComSafeArrayIn(IMedium *, aChildrenToReparent))
3174{
3175 HRESULT rc = S_OK;
3176 ComObjPtr<Medium> pSource(static_cast<Medium *>(aSource));
3177 ComObjPtr<Medium> pTarget(static_cast<Medium *>(aTarget));
3178 ComObjPtr<Medium> pParentForTarget(static_cast<Medium *>(aParentForTarget));
3179 bool fSourceHasChildren = false;
3180
3181 // all hard disks but the target were successfully deleted by
3182 // the merge; reparent target if necessary and uninitialize media
3183
3184 AutoWriteLock treeLock(mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3185
3186 // Declare this here to make sure the object does not get uninitialized
3187 // before this method completes. Would normally happen as halfway through
3188 // we delete the last reference to the no longer existing medium object.
3189 ComObjPtr<Medium> targetChild;
3190
3191 if (aMergeForward)
3192 {
3193 // first, unregister the target since it may become a base
3194 // hard disk which needs re-registration
3195 rc = mParent->unregisterHardDisk(pTarget, NULL /*&fNeedsGlobalSaveSettings*/);
3196 AssertComRC(rc);
3197
3198 // then, reparent it and disconnect the deleted branch at
3199 // both ends (chain->parent() is source's parent)
3200 pTarget->deparent();
3201 pTarget->setParent(pParentForTarget);
3202 if (pParentForTarget)
3203 pSource->deparent();
3204
3205 // then, register again
3206 rc = mParent->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
3207 AssertComRC(rc);
3208 }
3209 else
3210 {
3211 Assert(pTarget->getChildren().size() == 1);
3212 targetChild = pTarget->getChildren().front();
3213
3214 // disconnect the deleted branch at the elder end
3215 targetChild->deparent();
3216
3217 // Update parent UUIDs of the source's children, reparent them and
3218 // disconnect the deleted branch at the younger end
3219 com::SafeIfaceArray<IMedium> childrenToReparent(ComSafeArrayInArg(aChildrenToReparent));
3220 if (childrenToReparent.size() > 0)
3221 {
3222 fSourceHasChildren = true;
3223 // Fix the parent UUID of the images which needs to be moved to
3224 // underneath target. The running machine has the images opened,
3225 // but only for reading since the VM is paused. If anything fails
3226 // we must continue. The worst possible result is that the images
3227 // need manual fixing via VBoxManage to adjust the parent UUID.
3228 MediaList toReparent;
3229 for (size_t i = 0; i < childrenToReparent.size(); i++)
3230 {
3231 Medium *pMedium = static_cast<Medium *>(childrenToReparent[i]);
3232 toReparent.push_back(pMedium);
3233 }
3234 pTarget->fixParentUuidOfChildren(toReparent);
3235
3236 // obey {parent,child} lock order
3237 AutoWriteLock sourceLock(pSource COMMA_LOCKVAL_SRC_POS);
3238
3239 for (size_t i = 0; i < childrenToReparent.size(); i++)
3240 {
3241 Medium *pMedium = static_cast<Medium *>(childrenToReparent[i]);
3242 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
3243
3244 pMedium->deparent(); // removes pMedium from source
3245 pMedium->setParent(pTarget);
3246 }
3247 }
3248 }
3249
3250 /* unregister and uninitialize all hard disks removed by the merge */
3251 MediumLockList *pMediumLockList = NULL;
3252 MediumAttachment *pMediumAttachment = static_cast<MediumAttachment *>(aMediumAttachment);
3253 rc = mData->mSession.mLockedMedia.Get(pMediumAttachment, pMediumLockList);
3254 const ComObjPtr<Medium> &pLast = aMergeForward ? pTarget : pSource;
3255 AssertReturn(SUCCEEDED(rc) && pMediumLockList, E_FAIL);
3256 MediumLockList::Base::iterator lockListBegin =
3257 pMediumLockList->GetBegin();
3258 MediumLockList::Base::iterator lockListEnd =
3259 pMediumLockList->GetEnd();
3260 for (MediumLockList::Base::iterator it = lockListBegin;
3261 it != lockListEnd;
3262 )
3263 {
3264 MediumLock &mediumLock = *it;
3265 /* Create a real copy of the medium pointer, as the medium
3266 * lock deletion below would invalidate the referenced object. */
3267 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
3268
3269 /* The target and all images not merged (readonly) are skipped */
3270 if ( pMedium == pTarget
3271 || pMedium->getState() == MediumState_LockedRead)
3272 {
3273 ++it;
3274 }
3275 else
3276 {
3277 rc = mParent->unregisterHardDisk(pMedium,
3278 NULL /*pfNeedsGlobalSaveSettings*/);
3279 AssertComRC(rc);
3280
3281 /* now, uninitialize the deleted hard disk (note that
3282 * due to the Deleting state, uninit() will not touch
3283 * the parent-child relationship so we need to
3284 * uninitialize each disk individually) */
3285
3286 /* note that the operation initiator hard disk (which is
3287 * normally also the source hard disk) is a special case
3288 * -- there is one more caller added by Task to it which
3289 * we must release. Also, if we are in sync mode, the
3290 * caller may still hold an AutoCaller instance for it
3291 * and therefore we cannot uninit() it (it's therefore
3292 * the caller's responsibility) */
3293 if (pMedium == aSource)
3294 {
3295 Assert(pSource->getChildren().size() == 0);
3296 Assert(pSource->getFirstMachineBackrefId() == NULL);
3297 }
3298
3299 /* Delete the medium lock list entry, which also releases the
3300 * caller added by MergeChain before uninit() and updates the
3301 * iterator to point to the right place. */
3302 rc = pMediumLockList->RemoveByIterator(it);
3303 AssertComRC(rc);
3304
3305 pMedium->uninit();
3306 }
3307
3308 /* Stop as soon as we reached the last medium affected by the merge.
3309 * The remaining images must be kept unchanged. */
3310 if (pMedium == pLast)
3311 break;
3312 }
3313
3314 /* Could be in principle folded into the previous loop, but let's keep
3315 * things simple. Update the medium locking to be the standard state:
3316 * all parent images locked for reading, just the last diff for writing. */
3317 lockListBegin = pMediumLockList->GetBegin();
3318 lockListEnd = pMediumLockList->GetEnd();
3319 MediumLockList::Base::iterator lockListLast = lockListEnd;
3320 lockListLast--;
3321 for (MediumLockList::Base::iterator it = lockListBegin;
3322 it != lockListEnd;
3323 ++it)
3324 {
3325 it->UpdateLock(it == lockListLast);
3326 }
3327
3328 /* If this is a backwards merge of the only remaining snapshot (i.e. the
3329 * source has no children) then update the medium associated with the
3330 * attachment, as the previously associated one (source) is now deleted.
3331 * Without the immediate update the VM could not continue running. */
3332 if (!aMergeForward && !fSourceHasChildren)
3333 {
3334 AutoWriteLock attLock(pMediumAttachment COMMA_LOCKVAL_SRC_POS);
3335 pMediumAttachment->updateMedium(pTarget);
3336 }
3337
3338 return S_OK;
3339}
Note: See TracBrowser for help on using the repository browser.

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