VirtualBox

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

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

Main: fix setting the current state modification flag in some circumstances

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