VirtualBox

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

Last change on this file since 40487 was 40487, checked in by vboxsync, 13 years ago

Main/VirtualBox+Machine+Snapshot+Medium: fix lock order issues introduced by new style of medium registry updates

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