VirtualBox

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

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

Main: fix broken snapshots when disk images are shared between several machines

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

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