VirtualBox

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

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

Main. QT/FE: fix long standing COM issue

  • 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 35638 2011-01-19 19:10:49Z vboxsync $ */
2
3/** @file
4 *
5 * COM class implementation for Snapshot and SnapshotMachine in VBoxSVC.
6 */
7
8/*
9 * Copyright (C) 2006-2010 Oracle Corporation
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.215389.xyz. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 */
19
20#include "Logging.h"
21#include "SnapshotImpl.h"
22
23#include "MachineImpl.h"
24#include "MediumImpl.h"
25#include "MediumFormatImpl.h"
26#include "Global.h"
27#include "ProgressImpl.h"
28
29// @todo these three includes are required for about one or two lines, try
30// to remove them and put that code in shared code in MachineImplcpp
31#include "SharedFolderImpl.h"
32#include "USBControllerImpl.h"
33#include "VirtualBoxImpl.h"
34
35#include "AutoCaller.h"
36
37#include <iprt/path.h>
38#include <iprt/cpp/utils.h>
39
40#include <VBox/param.h>
41#include <VBox/err.h>
42
43#include <VBox/settings.h>
44
45////////////////////////////////////////////////////////////////////////////////
46//
47// 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 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 catch (HRESULT hrc)
1493 {
1494 LogThisFunc(("Caught %Rhrc [%s]\n", hrc, Global::stringifyMachineState(mData->mMachineState) ));
1495 if ( mConsoleTaskData.mLastState != mData->mMachineState
1496 && ( mConsoleTaskData.mLastState == MachineState_Running
1497 ? mData->mMachineState == MachineState_LiveSnapshotting
1498 : mData->mMachineState == MachineState_Saving)
1499 )
1500 setMachineState(mConsoleTaskData.mLastState);
1501
1502 pSnapshot->uninit();
1503 pSnapshot.setNull();
1504 mConsoleTaskData.mLastState = MachineState_Null;
1505 mConsoleTaskData.mSnapshot.setNull();
1506
1507 rc = hrc;
1508
1509 // @todo r=dj what with the implicit diff that we created above? this is never cleaned up
1510 }
1511
1512 if (fTakingSnapshotOnline && SUCCEEDED(rc))
1513 strStateFilePath.cloneTo(aStateFilePath);
1514 else
1515 *aStateFilePath = NULL;
1516
1517 // @todo r=dj normally we would need to save the settings if fNeedsGlobalSaveSettings was set to true,
1518 // but since we have no error handling that cleans up the diff image that might have gotten created,
1519 // there's no point in saving the disk registry at this point either... this needs fixing.
1520
1521 LogFlowThisFunc(("LEAVE - %Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
1522 return rc;
1523}
1524
1525/**
1526 * Implementation for IInternalMachineControl::endTakingSnapshot().
1527 *
1528 * Called by the Console when it's done saving the VM state into the snapshot
1529 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
1530 *
1531 * This also gets called if the console part of snapshotting failed after the
1532 * BeginTakingSnapshot() call, to clean up the server side.
1533 *
1534 * @note Locks VirtualBox and this object for writing.
1535 *
1536 * @param aSuccess Whether Console was successful with the client-side snapshot things.
1537 * @return
1538 */
1539STDMETHODIMP SessionMachine::EndTakingSnapshot(BOOL aSuccess)
1540{
1541 LogFlowThisFunc(("\n"));
1542
1543 AutoCaller autoCaller(this);
1544 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1545
1546 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
1547
1548 AssertReturn( !aSuccess
1549 || ( ( mData->mMachineState == MachineState_Saving
1550 || mData->mMachineState == MachineState_LiveSnapshotting)
1551 && mConsoleTaskData.mLastState != MachineState_Null
1552 && !mConsoleTaskData.mSnapshot.isNull()
1553 )
1554 , E_FAIL);
1555
1556 /*
1557 * Restore the state we had when BeginTakingSnapshot() was called,
1558 * Console::fntTakeSnapshotWorker restores its local copy when we return.
1559 * If the state was Running, then let Console::fntTakeSnapshotWorker do it
1560 * all to avoid races.
1561 */
1562 if ( mData->mMachineState != mConsoleTaskData.mLastState
1563 && mConsoleTaskData.mLastState != MachineState_Running
1564 )
1565 setMachineState(mConsoleTaskData.mLastState);
1566
1567 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
1568 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
1569
1570 bool fOnline = Global::IsOnline(mConsoleTaskData.mLastState);
1571
1572 HRESULT rc = S_OK;
1573
1574 if (aSuccess)
1575 {
1576 // new snapshot becomes the current one
1577 mData->mCurrentSnapshot = mConsoleTaskData.mSnapshot;
1578
1579 /* memorize the first snapshot if necessary */
1580 if (!mData->mFirstSnapshot)
1581 mData->mFirstSnapshot = mData->mCurrentSnapshot;
1582
1583 int flSaveSettings = SaveS_Force; // do not do a deep compare in machine settings,
1584 // snapshots change, so we know we need to save
1585 if (!fOnline)
1586 /* the machine was powered off or saved when taking a snapshot, so
1587 * reset the mCurrentStateModified flag */
1588 flSaveSettings |= SaveS_ResetCurStateModified;
1589
1590 rc = saveSettings(NULL, flSaveSettings);
1591 // no need to change for whether VirtualBox.xml needs saving since
1592 // we'll save the global settings below anyway
1593 }
1594
1595 if (aSuccess && SUCCEEDED(rc))
1596 {
1597 /* associate old hard disks with the snapshot and do locking/unlocking*/
1598 commitMedia(fOnline);
1599
1600 /* inform callbacks */
1601 mParent->onSnapshotTaken(mData->mUuid,
1602 mConsoleTaskData.mSnapshot->getId());
1603 }
1604 else
1605 {
1606 /* delete all differencing hard disks created (this will also attach
1607 * their parents back by rolling back mMediaData) */
1608 rollbackMedia();
1609
1610 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
1611 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
1612
1613 /* delete the saved state file (it might have been already created) */
1614 if (mConsoleTaskData.mSnapshot->stateFilePath().length())
1615 RTFileDelete(mConsoleTaskData.mSnapshot->stateFilePath().c_str());
1616
1617 mConsoleTaskData.mSnapshot->uninit();
1618 }
1619
1620 /* clear out the snapshot data */
1621 mConsoleTaskData.mLastState = MachineState_Null;
1622 mConsoleTaskData.mSnapshot.setNull();
1623
1624 // save VirtualBox.xml (media registry most probably changed with diff image);
1625 // for that we should hold only the VirtualBox lock
1626 machineLock.release();
1627 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
1628 mParent->saveSettings();
1629
1630 return rc;
1631}
1632
1633////////////////////////////////////////////////////////////////////////////////
1634//
1635// RestoreSnapshot methods (SessionMachine and related tasks)
1636//
1637////////////////////////////////////////////////////////////////////////////////
1638
1639/**
1640 * Implementation for IInternalMachineControl::restoreSnapshot().
1641 *
1642 * Gets called from Console::RestoreSnapshot(), and that's basically the
1643 * only thing Console does. Restoring a snapshot happens entirely on the
1644 * server side since the machine cannot be running.
1645 *
1646 * This creates a new thread that does the work and returns a progress
1647 * object to the client which is then returned to the caller of
1648 * Console::RestoreSnapshot().
1649 *
1650 * Actual work then takes place in RestoreSnapshotTask::handler().
1651 *
1652 * @note Locks this + children objects for writing!
1653 *
1654 * @param aInitiator in: rhe console on which Console::RestoreSnapshot was called.
1655 * @param aSnapshot in: the snapshot to restore.
1656 * @param aMachineState in: client-side machine state.
1657 * @param aProgress out: progress object to monitor restore thread.
1658 * @return
1659 */
1660STDMETHODIMP SessionMachine::RestoreSnapshot(IConsole *aInitiator,
1661 ISnapshot *aSnapshot,
1662 MachineState_T *aMachineState,
1663 IProgress **aProgress)
1664{
1665 LogFlowThisFuncEnter();
1666
1667 AssertReturn(aInitiator, E_INVALIDARG);
1668 AssertReturn(aSnapshot && aMachineState && aProgress, E_POINTER);
1669
1670 AutoCaller autoCaller(this);
1671 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
1672
1673 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1674
1675 // machine must not be running
1676 ComAssertRet(!Global::IsOnlineOrTransient(mData->mMachineState),
1677 E_FAIL);
1678
1679 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(aSnapshot));
1680 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
1681
1682 // create a progress object. The number of operations is:
1683 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
1684 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
1685
1686 ULONG ulOpCount = 1; // one for preparations
1687 ULONG ulTotalWeight = 1; // one for preparations
1688 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
1689 it != pSnapMachine->mMediaData->mAttachments.end();
1690 ++it)
1691 {
1692 ComObjPtr<MediumAttachment> &pAttach = *it;
1693 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
1694 if (pAttach->getType() == DeviceType_HardDisk)
1695 {
1696 ++ulOpCount;
1697 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
1698 Assert(pAttach->getMedium());
1699 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pAttach->getMedium()->getName().c_str()));
1700 }
1701 }
1702
1703 ULONG ulStateFileSizeMB = 0;
1704 if (pSnapshot->stateFilePath().length())
1705 {
1706 ++ulOpCount; // one for the saved state
1707
1708 uint64_t ullSize;
1709 int irc = RTFileQuerySize(pSnapshot->stateFilePath().c_str(), &ullSize);
1710 if (!RT_SUCCESS(irc))
1711 // if we can't access the file here, then we'll be doomed later also, so fail right away
1712 setError(E_FAIL, tr("Cannot access state file '%s', runtime error, %Rra"), pSnapshot->stateFilePath().c_str(), irc);
1713 if (ullSize == 0) // avoid division by zero
1714 ullSize = _1M;
1715
1716 ulStateFileSizeMB = (ULONG)(ullSize / _1M);
1717 LogFlowThisFunc(("op %d: saved state file '%s' has %RI64 bytes (%d MB)\n",
1718 ulOpCount, pSnapshot->stateFilePath().c_str(), ullSize, ulStateFileSizeMB));
1719
1720 ulTotalWeight += ulStateFileSizeMB;
1721 }
1722
1723 ComObjPtr<Progress> pProgress;
1724 pProgress.createObject();
1725 pProgress->init(mParent, aInitiator,
1726 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->getName().c_str()).raw(),
1727 FALSE /* aCancelable */,
1728 ulOpCount,
1729 ulTotalWeight,
1730 Bstr(tr("Restoring machine settings")).raw(),
1731 1);
1732
1733 /* create and start the task on a separate thread (note that it will not
1734 * start working until we release alock) */
1735 RestoreSnapshotTask *task = new RestoreSnapshotTask(this,
1736 pProgress,
1737 pSnapshot,
1738 ulStateFileSizeMB);
1739 int vrc = RTThreadCreate(NULL,
1740 taskHandler,
1741 (void*)task,
1742 0,
1743 RTTHREADTYPE_MAIN_WORKER,
1744 0,
1745 "RestoreSnap");
1746 if (RT_FAILURE(vrc))
1747 {
1748 delete task;
1749 ComAssertRCRet(vrc, E_FAIL);
1750 }
1751
1752 /* set the proper machine state (note: after creating a Task instance) */
1753 setMachineState(MachineState_RestoringSnapshot);
1754
1755 /* return the progress to the caller */
1756 pProgress.queryInterfaceTo(aProgress);
1757
1758 /* return the new state to the caller */
1759 *aMachineState = mData->mMachineState;
1760
1761 LogFlowThisFuncLeave();
1762
1763 return S_OK;
1764}
1765
1766/**
1767 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
1768 * This method gets called indirectly through SessionMachine::taskHandler() which then
1769 * calls RestoreSnapshotTask::handler().
1770 *
1771 * The RestoreSnapshotTask contains the progress object returned to the console by
1772 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
1773 *
1774 * @note Locks mParent + this object for writing.
1775 *
1776 * @param aTask Task data.
1777 */
1778void SessionMachine::restoreSnapshotHandler(RestoreSnapshotTask &aTask)
1779{
1780 LogFlowThisFuncEnter();
1781
1782 AutoCaller autoCaller(this);
1783
1784 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
1785 if (!autoCaller.isOk())
1786 {
1787 /* we might have been uninitialized because the session was accidentally
1788 * closed by the client, so don't assert */
1789 aTask.pProgress->notifyComplete(E_FAIL,
1790 COM_IIDOF(IMachine),
1791 getComponentName(),
1792 tr("The session has been accidentally closed"));
1793
1794 LogFlowThisFuncLeave();
1795 return;
1796 }
1797
1798 HRESULT rc = S_OK;
1799
1800 bool stateRestored = false;
1801 GuidList llRegistriesThatNeedSaving;
1802
1803 try
1804 {
1805 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1806
1807 /* Discard all current changes to mUserData (name, OSType etc.).
1808 * Note that the machine is powered off, so there is no need to inform
1809 * the direct session. */
1810 if (mData->flModifications)
1811 rollback(false /* aNotify */);
1812
1813 /* Delete the saved state file if the machine was Saved prior to this
1814 * operation */
1815 if (aTask.machineStateBackup == MachineState_Saved)
1816 {
1817 Assert(!mSSData->mStateFilePath.isEmpty());
1818 RTFileDelete(mSSData->mStateFilePath.c_str());
1819 mSSData->mStateFilePath.setNull();
1820 aTask.modifyBackedUpState(MachineState_PoweredOff);
1821 rc = saveStateSettings(SaveSTS_StateFilePath);
1822 if (FAILED(rc))
1823 throw rc;
1824 }
1825
1826 RTTIMESPEC snapshotTimeStamp;
1827 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
1828
1829 {
1830 AutoReadLock snapshotLock(aTask.pSnapshot COMMA_LOCKVAL_SRC_POS);
1831
1832 /* remember the timestamp of the snapshot we're restoring from */
1833 snapshotTimeStamp = aTask.pSnapshot->getTimeStamp();
1834
1835 ComPtr<SnapshotMachine> pSnapshotMachine(aTask.pSnapshot->getSnapshotMachine());
1836
1837 /* copy all hardware data from the snapshot */
1838 copyFrom(pSnapshotMachine);
1839
1840 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
1841
1842 // restore the attachments from the snapshot
1843 setModified(IsModified_Storage);
1844 mMediaData.backup();
1845 mMediaData->mAttachments = pSnapshotMachine->mMediaData->mAttachments;
1846
1847 /* leave the locks before the potentially lengthy operation */
1848 snapshotLock.release();
1849 alock.leave();
1850
1851 rc = createImplicitDiffs(aTask.pProgress,
1852 1,
1853 false /* aOnline */,
1854 &llRegistriesThatNeedSaving);
1855 if (FAILED(rc))
1856 throw rc;
1857
1858 alock.enter();
1859 snapshotLock.acquire();
1860
1861 /* Note: on success, current (old) hard disks will be
1862 * deassociated/deleted on #commit() called from #saveSettings() at
1863 * the end. On failure, newly created implicit diffs will be
1864 * deleted by #rollback() at the end. */
1865
1866 /* should not have a saved state file associated at this point */
1867 Assert(mSSData->mStateFilePath.isEmpty());
1868
1869 if (!aTask.pSnapshot->stateFilePath().isEmpty())
1870 {
1871 Utf8Str snapStateFilePath = aTask.pSnapshot->stateFilePath();
1872
1873 Utf8Str strFullSnapshotFolder;
1874 calculateFullPath(mUserData->s.strSnapshotFolder, strFullSnapshotFolder);
1875 Utf8Str stateFilePath = Utf8StrFmt("%s%c{%RTuuid}.sav",
1876 strFullSnapshotFolder.c_str(),
1877 RTPATH_DELIMITER,
1878 mData->mUuid.raw());
1879
1880 LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
1881 snapStateFilePath.c_str(), stateFilePath.c_str()));
1882
1883 aTask.pProgress->SetNextOperation(Bstr(tr("Restoring the execution state")).raw(),
1884 aTask.m_ulStateFileSizeMB); // weight
1885
1886 /* leave the lock before the potentially lengthy operation */
1887 snapshotLock.release();
1888 alock.leave();
1889
1890 /* copy the state file */
1891 RTFileDelete(stateFilePath.c_str());
1892 int vrc = RTFileCopyEx(snapStateFilePath.c_str(),
1893 stateFilePath.c_str(),
1894 0,
1895 progressCallback,
1896 static_cast<IProgress*>(aTask.pProgress));
1897
1898 alock.enter();
1899 snapshotLock.acquire();
1900
1901 if (RT_SUCCESS(vrc))
1902 mSSData->mStateFilePath = stateFilePath;
1903 else
1904 throw setError(E_FAIL,
1905 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1906 snapStateFilePath.c_str(),
1907 stateFilePath.c_str(),
1908 vrc);
1909 }
1910
1911 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", aTask.pSnapshot->getId().raw()));
1912 /* make the snapshot we restored from the current snapshot */
1913 mData->mCurrentSnapshot = aTask.pSnapshot;
1914 }
1915
1916 /* grab differencing hard disks from the old attachments that will
1917 * become unused and need to be auto-deleted */
1918 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
1919
1920 for (MediaData::AttachmentList::const_iterator it = mMediaData.backedUpData()->mAttachments.begin();
1921 it != mMediaData.backedUpData()->mAttachments.end();
1922 ++it)
1923 {
1924 ComObjPtr<MediumAttachment> pAttach = *it;
1925 ComObjPtr<Medium> pMedium = pAttach->getMedium();
1926
1927 /* while the hard disk is attached, the number of children or the
1928 * parent cannot change, so no lock */
1929 if ( !pMedium.isNull()
1930 && pAttach->getType() == DeviceType_HardDisk
1931 && !pMedium->getParent().isNull()
1932 && pMedium->getChildren().size() == 0
1933 )
1934 {
1935 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->getName().c_str()));
1936
1937 llDiffAttachmentsToDelete.push_back(pAttach);
1938 }
1939 }
1940
1941 int saveFlags = 0;
1942
1943 /* we have already deleted the current state, so set the execution
1944 * state accordingly no matter of the delete snapshot result */
1945 if (!mSSData->mStateFilePath.isEmpty())
1946 setMachineState(MachineState_Saved);
1947 else
1948 setMachineState(MachineState_PoweredOff);
1949
1950 updateMachineStateOnClient();
1951 stateRestored = true;
1952
1953 /* assign the timestamp from the snapshot */
1954 Assert(RTTimeSpecGetMilli (&snapshotTimeStamp) != 0);
1955 mData->mLastStateChange = snapshotTimeStamp;
1956
1957 // detach the current-state diffs that we detected above and build a list of
1958 // image files to delete _after_ saveSettings()
1959
1960 MediaList llDiffsToDelete;
1961
1962 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
1963 it != llDiffAttachmentsToDelete.end();
1964 ++it)
1965 {
1966 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
1967 ComObjPtr<Medium> pMedium = pAttach->getMedium();
1968
1969 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
1970
1971 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->getName().c_str()));
1972
1973 // Normally we "detach" the medium by removing the attachment object
1974 // from the current machine data; saveSettings() below would then
1975 // compare the current machine data with the one in the backup
1976 // and actually call Medium::removeBackReference(). But that works only half
1977 // the time in our case so instead we force a detachment here:
1978 // remove from machine data
1979 mMediaData->mAttachments.remove(pAttach);
1980 // remove it from the backup or else saveSettings will try to detach
1981 // it again and assert
1982 mMediaData.backedUpData()->mAttachments.remove(pAttach);
1983 // then clean up backrefs
1984 pMedium->removeBackReference(mData->mUuid);
1985
1986 llDiffsToDelete.push_back(pMedium);
1987 }
1988
1989 // save machine settings, reset the modified flag and commit;
1990 bool fNeedsGlobalSaveSettings = false;
1991 rc = saveSettings(&fNeedsGlobalSaveSettings,
1992 SaveS_ResetCurStateModified | saveFlags);
1993 if (FAILED(rc))
1994 throw rc;
1995 if (fNeedsGlobalSaveSettings)
1996 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, mParent->getGlobalRegistryId());
1997
1998 // let go of the locks while we're deleting image files below
1999 alock.leave();
2000 // from here on we cannot roll back on failure any more
2001
2002 for (MediaList::iterator it = llDiffsToDelete.begin();
2003 it != llDiffsToDelete.end();
2004 ++it)
2005 {
2006 ComObjPtr<Medium> &pMedium = *it;
2007 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->getName().c_str()));
2008
2009 HRESULT rc2 = pMedium->deleteStorage(NULL /* aProgress */,
2010 true /* aWait */,
2011 &llRegistriesThatNeedSaving);
2012 // ignore errors here because we cannot roll back after saveSettings() above
2013 if (SUCCEEDED(rc2))
2014 pMedium->uninit();
2015 }
2016 }
2017 catch (HRESULT aRC)
2018 {
2019 rc = aRC;
2020 }
2021
2022 if (FAILED(rc))
2023 {
2024 /* preserve existing error info */
2025 ErrorInfoKeeper eik;
2026
2027 /* undo all changes on failure */
2028 rollback(false /* aNotify */);
2029
2030 if (!stateRestored)
2031 {
2032 /* restore the machine state */
2033 setMachineState(aTask.machineStateBackup);
2034 updateMachineStateOnClient();
2035 }
2036 }
2037
2038 mParent->saveRegistries(llRegistriesThatNeedSaving);
2039
2040 /* set the result (this will try to fetch current error info on failure) */
2041 aTask.pProgress->notifyComplete(rc);
2042
2043 if (SUCCEEDED(rc))
2044 mParent->onSnapshotDeleted(mData->mUuid, Guid());
2045
2046 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
2047
2048 LogFlowThisFuncLeave();
2049}
2050
2051////////////////////////////////////////////////////////////////////////////////
2052//
2053// DeleteSnapshot methods (SessionMachine and related tasks)
2054//
2055////////////////////////////////////////////////////////////////////////////////
2056
2057/**
2058 * Implementation for IInternalMachineControl::deleteSnapshot().
2059 *
2060 * Gets called from Console::DeleteSnapshot(), and that's basically the
2061 * only thing Console does initially. Deleting a snapshot happens entirely on
2062 * the server side if the machine is not running, and if it is running then
2063 * the individual merges are done via internal session callbacks.
2064 *
2065 * This creates a new thread that does the work and returns a progress
2066 * object to the client which is then returned to the caller of
2067 * Console::DeleteSnapshot().
2068 *
2069 * Actual work then takes place in DeleteSnapshotTask::handler().
2070 *
2071 * @note Locks mParent + this + children objects for writing!
2072 */
2073STDMETHODIMP SessionMachine::DeleteSnapshot(IConsole *aInitiator,
2074 IN_BSTR aId,
2075 MachineState_T *aMachineState,
2076 IProgress **aProgress)
2077{
2078 LogFlowThisFuncEnter();
2079
2080 Guid id(aId);
2081 AssertReturn(aInitiator && !id.isEmpty(), E_INVALIDARG);
2082 AssertReturn(aMachineState && aProgress, E_POINTER);
2083
2084 AutoCaller autoCaller(this);
2085 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2086
2087 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2088
2089 // be very picky about machine states
2090 if ( Global::IsOnlineOrTransient(mData->mMachineState)
2091 && mData->mMachineState != MachineState_PoweredOff
2092 && mData->mMachineState != MachineState_Saved
2093 && mData->mMachineState != MachineState_Teleported
2094 && mData->mMachineState != MachineState_Aborted
2095 && mData->mMachineState != MachineState_Running
2096 && mData->mMachineState != MachineState_Paused)
2097 return setError(VBOX_E_INVALID_VM_STATE,
2098 tr("Invalid machine state: %s"),
2099 Global::stringifyMachineState(mData->mMachineState));
2100
2101 ComObjPtr<Snapshot> pSnapshot;
2102 HRESULT rc = findSnapshotById(id, pSnapshot, true /* aSetError */);
2103 if (FAILED(rc)) return rc;
2104
2105 AutoWriteLock snapshotLock(pSnapshot COMMA_LOCKVAL_SRC_POS);
2106
2107 size_t childrenCount = pSnapshot->getChildrenCount();
2108 if (childrenCount > 1)
2109 return setError(VBOX_E_INVALID_OBJECT_STATE,
2110 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"),
2111 pSnapshot->getName().c_str(),
2112 mUserData->s.strName.c_str(),
2113 childrenCount);
2114
2115 /* If the snapshot being deleted is the current one, ensure current
2116 * settings are committed and saved.
2117 */
2118 if (pSnapshot == mData->mCurrentSnapshot)
2119 {
2120 if (mData->flModifications)
2121 {
2122 rc = saveSettings(NULL);
2123 // no need to change for whether VirtualBox.xml needs saving since
2124 // we can't have a machine XML rename pending at this point
2125 if (FAILED(rc)) return rc;
2126 }
2127 }
2128
2129 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
2130
2131 /* create a progress object. The number of operations is:
2132 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
2133 */
2134 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2135
2136 ULONG ulOpCount = 1; // one for preparations
2137 ULONG ulTotalWeight = 1; // one for preparations
2138
2139 if (pSnapshot->stateFilePath().length())
2140 {
2141 ++ulOpCount;
2142 ++ulTotalWeight; // assume 1 MB for deleting the state file
2143 }
2144
2145 // count normal hard disks and add their sizes to the weight
2146 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2147 it != pSnapMachine->mMediaData->mAttachments.end();
2148 ++it)
2149 {
2150 ComObjPtr<MediumAttachment> &pAttach = *it;
2151 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2152 if (pAttach->getType() == DeviceType_HardDisk)
2153 {
2154 ComObjPtr<Medium> pHD = pAttach->getMedium();
2155 Assert(pHD);
2156 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2157
2158 MediumType_T type = pHD->getType();
2159 // writethrough and shareable images are unaffected by snapshots,
2160 // so do nothing for them
2161 if ( type != MediumType_Writethrough
2162 && type != MediumType_Shareable
2163 && type != MediumType_Readonly)
2164 {
2165 // normal or immutable media need attention
2166 ++ulOpCount;
2167 ulTotalWeight += (ULONG)(pHD->getSize() / _1M);
2168 }
2169 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->getName().c_str()));
2170 }
2171 }
2172
2173 ComObjPtr<Progress> pProgress;
2174 pProgress.createObject();
2175 pProgress->init(mParent, aInitiator,
2176 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->getName().c_str()).raw(),
2177 FALSE /* aCancelable */,
2178 ulOpCount,
2179 ulTotalWeight,
2180 Bstr(tr("Setting up")).raw(),
2181 1);
2182
2183 bool fDeleteOnline = ( (mData->mMachineState == MachineState_Running)
2184 || (mData->mMachineState == MachineState_Paused));
2185
2186 /* create and start the task on a separate thread */
2187 DeleteSnapshotTask *task = new DeleteSnapshotTask(this, pProgress,
2188 fDeleteOnline, pSnapshot);
2189 int vrc = RTThreadCreate(NULL,
2190 taskHandler,
2191 (void*)task,
2192 0,
2193 RTTHREADTYPE_MAIN_WORKER,
2194 0,
2195 "DeleteSnapshot");
2196 if (RT_FAILURE(vrc))
2197 {
2198 delete task;
2199 return E_FAIL;
2200 }
2201
2202 // the task might start running but will block on acquiring the machine's write lock
2203 // which we acquired above; once this function leaves, the task will be unblocked;
2204 // set the proper machine state here now (note: after creating a Task instance)
2205 if (mData->mMachineState == MachineState_Running)
2206 setMachineState(MachineState_DeletingSnapshotOnline);
2207 else if (mData->mMachineState == MachineState_Paused)
2208 setMachineState(MachineState_DeletingSnapshotPaused);
2209 else
2210 setMachineState(MachineState_DeletingSnapshot);
2211
2212 /* return the progress to the caller */
2213 pProgress.queryInterfaceTo(aProgress);
2214
2215 /* return the new state to the caller */
2216 *aMachineState = mData->mMachineState;
2217
2218 LogFlowThisFuncLeave();
2219
2220 return S_OK;
2221}
2222
2223/**
2224 * Helper struct for SessionMachine::deleteSnapshotHandler().
2225 */
2226struct MediumDeleteRec
2227{
2228 MediumDeleteRec()
2229 : mfNeedsOnlineMerge(false),
2230 mpMediumLockList(NULL)
2231 {}
2232
2233 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2234 const ComObjPtr<Medium> &aSource,
2235 const ComObjPtr<Medium> &aTarget,
2236 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2237 bool fMergeForward,
2238 const ComObjPtr<Medium> &aParentForTarget,
2239 const MediaList &aChildrenToReparent,
2240 bool fNeedsOnlineMerge,
2241 MediumLockList *aMediumLockList)
2242 : mpHD(aHd),
2243 mpSource(aSource),
2244 mpTarget(aTarget),
2245 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2246 mfMergeForward(fMergeForward),
2247 mpParentForTarget(aParentForTarget),
2248 mChildrenToReparent(aChildrenToReparent),
2249 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2250 mpMediumLockList(aMediumLockList)
2251 {}
2252
2253 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2254 const ComObjPtr<Medium> &aSource,
2255 const ComObjPtr<Medium> &aTarget,
2256 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2257 bool fMergeForward,
2258 const ComObjPtr<Medium> &aParentForTarget,
2259 const MediaList &aChildrenToReparent,
2260 bool fNeedsOnlineMerge,
2261 MediumLockList *aMediumLockList,
2262 const Guid &aMachineId,
2263 const Guid &aSnapshotId)
2264 : mpHD(aHd),
2265 mpSource(aSource),
2266 mpTarget(aTarget),
2267 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2268 mfMergeForward(fMergeForward),
2269 mpParentForTarget(aParentForTarget),
2270 mChildrenToReparent(aChildrenToReparent),
2271 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2272 mpMediumLockList(aMediumLockList),
2273 mMachineId(aMachineId),
2274 mSnapshotId(aSnapshotId)
2275 {}
2276
2277 ComObjPtr<Medium> mpHD;
2278 ComObjPtr<Medium> mpSource;
2279 ComObjPtr<Medium> mpTarget;
2280 ComObjPtr<MediumAttachment> mpOnlineMediumAttachment;
2281 bool mfMergeForward;
2282 ComObjPtr<Medium> mpParentForTarget;
2283 MediaList mChildrenToReparent;
2284 bool mfNeedsOnlineMerge;
2285 MediumLockList *mpMediumLockList;
2286 /* these are for reattaching the hard disk in case of a failure: */
2287 Guid mMachineId;
2288 Guid mSnapshotId;
2289};
2290
2291typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2292
2293/**
2294 * Worker method for the delete snapshot thread created by
2295 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2296 * through SessionMachine::taskHandler() which then calls
2297 * DeleteSnapshotTask::handler().
2298 *
2299 * The DeleteSnapshotTask contains the progress object returned to the console
2300 * by SessionMachine::DeleteSnapshot, through which progress and results are
2301 * reported.
2302 *
2303 * SessionMachine::DeleteSnapshot() has set the machine state to
2304 * MachineState_DeletingSnapshot right after creating this task. Since we block
2305 * on the machine write lock at the beginning, once that has been acquired, we
2306 * can assume that the machine state is indeed that.
2307 *
2308 * @note Locks the machine + the snapshot + the media tree for writing!
2309 *
2310 * @param aTask Task data.
2311 */
2312
2313void SessionMachine::deleteSnapshotHandler(DeleteSnapshotTask &aTask)
2314{
2315 LogFlowThisFuncEnter();
2316
2317 AutoCaller autoCaller(this);
2318
2319 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
2320 if (!autoCaller.isOk())
2321 {
2322 /* we might have been uninitialized because the session was accidentally
2323 * closed by the client, so don't assert */
2324 aTask.pProgress->notifyComplete(E_FAIL,
2325 COM_IIDOF(IMachine),
2326 getComponentName(),
2327 tr("The session has been accidentally closed"));
2328 LogFlowThisFuncLeave();
2329 return;
2330 }
2331
2332 MediumDeleteRecList toDelete;
2333
2334 HRESULT rc = S_OK;
2335
2336 GuidList llRegistriesThatNeedSaving;
2337
2338 Guid snapshotId;
2339
2340 try
2341 {
2342 /* Locking order: */
2343 AutoMultiWriteLock3 multiLock(this->lockHandle(), // machine
2344 aTask.pSnapshot->lockHandle(), // snapshot
2345 &mParent->getMediaTreeLockHandle() // media tree
2346 COMMA_LOCKVAL_SRC_POS);
2347 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2348 // has exited after setting the machine state to MachineState_DeletingSnapshot
2349
2350 ComObjPtr<SnapshotMachine> pSnapMachine = aTask.pSnapshot->getSnapshotMachine();
2351 // no need to lock the snapshot machine since it is const by definition
2352 Guid machineId = pSnapMachine->getId();
2353
2354 // save the snapshot ID (for callbacks)
2355 snapshotId = aTask.pSnapshot->getId();
2356
2357 // first pass:
2358 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2359
2360 // Go thru the attachments of the snapshot machine (the media in here
2361 // point to the disk states _before_ the snapshot was taken, i.e. the
2362 // state we're restoring to; for each such medium, we will need to
2363 // merge it with its one and only child (the diff image holding the
2364 // changes written after the snapshot was taken).
2365 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2366 it != pSnapMachine->mMediaData->mAttachments.end();
2367 ++it)
2368 {
2369 ComObjPtr<MediumAttachment> &pAttach = *it;
2370 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2371 if (pAttach->getType() != DeviceType_HardDisk)
2372 continue;
2373
2374 ComObjPtr<Medium> pHD = pAttach->getMedium();
2375 Assert(!pHD.isNull());
2376
2377 {
2378 // writethrough, shareable and readonly images are
2379 // unaffected by snapshots, skip them
2380 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
2381 MediumType_T type = pHD->getType();
2382 if ( type == MediumType_Writethrough
2383 || type == MediumType_Shareable
2384 || type == MediumType_Readonly)
2385 continue;
2386 }
2387
2388#ifdef DEBUG
2389 pHD->dumpBackRefs();
2390#endif
2391
2392 // needs to be merged with child or deleted, check prerequisites
2393 ComObjPtr<Medium> pTarget;
2394 ComObjPtr<Medium> pSource;
2395 bool fMergeForward = false;
2396 ComObjPtr<Medium> pParentForTarget;
2397 MediaList childrenToReparent;
2398 bool fNeedsOnlineMerge = false;
2399 bool fOnlineMergePossible = aTask.m_fDeleteOnline;
2400 MediumLockList *pMediumLockList = NULL;
2401 MediumLockList *pVMMALockList = NULL;
2402 ComObjPtr<MediumAttachment> pOnlineMediumAttachment;
2403 if (fOnlineMergePossible)
2404 {
2405 // Look up the corresponding medium attachment in the currently
2406 // running VM. Any failure prevents a live merge. Could be made
2407 // a tad smarter by trying a few candidates, so that e.g. disks
2408 // which are simply moved to a different controller slot do not
2409 // prevent online merging in general.
2410 pOnlineMediumAttachment =
2411 findAttachment(mMediaData->mAttachments,
2412 pAttach->getControllerName().raw(),
2413 pAttach->getPort(),
2414 pAttach->getDevice());
2415 if (pOnlineMediumAttachment)
2416 {
2417 rc = mData->mSession.mLockedMedia.Get(pOnlineMediumAttachment,
2418 pVMMALockList);
2419 if (FAILED(rc))
2420 fOnlineMergePossible = false;
2421 }
2422 else
2423 fOnlineMergePossible = false;
2424 }
2425 rc = prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
2426 fOnlineMergePossible,
2427 pVMMALockList, pSource, pTarget,
2428 fMergeForward, pParentForTarget,
2429 childrenToReparent,
2430 fNeedsOnlineMerge,
2431 pMediumLockList);
2432 if (FAILED(rc))
2433 throw rc;
2434
2435 // no need to hold the lock any longer
2436 attachLock.release();
2437
2438 // For simplicity, prepareDeleteSnapshotMedium selects the merge
2439 // direction in the following way: we merge pHD onto its child
2440 // (forward merge), not the other way round, because that saves us
2441 // from unnecessarily shuffling around the attachments for the
2442 // machine that follows the snapshot (next snapshot or current
2443 // state), unless it's a base image. Backwards merges of the first
2444 // snapshot into the base image is essential, as it ensures that
2445 // when all snapshots are deleted the only remaining image is a
2446 // base image. Important e.g. for medium formats which do not have
2447 // a file representation such as iSCSI.
2448
2449 // a couple paranoia checks for backward merges
2450 if (pMediumLockList != NULL && !fMergeForward)
2451 {
2452 // parent is null -> this disk is a base hard disk: we will
2453 // then do a backward merge, i.e. merge its only child onto the
2454 // base disk. Here we need then to update the attachment that
2455 // refers to the child and have it point to the parent instead
2456 Assert(pHD->getParent().isNull());
2457 Assert(pHD->getChildren().size() == 1);
2458
2459 ComObjPtr<Medium> pReplaceHD = pHD->getChildren().front();
2460
2461 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
2462 }
2463
2464 Guid replaceMachineId;
2465 Guid replaceSnapshotId;
2466
2467 const Guid *pReplaceMachineId = pSource->getFirstMachineBackrefId();
2468 // minimal sanity checking
2469 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
2470 if (pReplaceMachineId)
2471 replaceMachineId = *pReplaceMachineId;
2472
2473 const Guid *pSnapshotId = pSource->getFirstMachineBackrefSnapshotId();
2474 if (pSnapshotId)
2475 replaceSnapshotId = *pSnapshotId;
2476
2477 if (!replaceMachineId.isEmpty())
2478 {
2479 // Adjust the backreferences, otherwise merging will assert.
2480 // Note that the medium attachment object stays associated
2481 // with the snapshot until the merge was successful.
2482 HRESULT rc2 = S_OK;
2483 rc2 = pSource->removeBackReference(replaceMachineId, replaceSnapshotId);
2484 AssertComRC(rc2);
2485
2486 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2487 pOnlineMediumAttachment,
2488 fMergeForward,
2489 pParentForTarget,
2490 childrenToReparent,
2491 fNeedsOnlineMerge,
2492 pMediumLockList,
2493 replaceMachineId,
2494 replaceSnapshotId));
2495 }
2496 else
2497 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2498 pOnlineMediumAttachment,
2499 fMergeForward,
2500 pParentForTarget,
2501 childrenToReparent,
2502 fNeedsOnlineMerge,
2503 pMediumLockList));
2504 }
2505
2506 // we can release the lock now since the machine state is MachineState_DeletingSnapshot
2507 multiLock.release();
2508
2509 /* Now we checked that we can successfully merge all normal hard disks
2510 * (unless a runtime error like end-of-disc happens). Now get rid of
2511 * the saved state (if present), as that will free some disk space.
2512 * The snapshot itself will be deleted as late as possible, so that
2513 * the user can repeat the delete operation if he runs out of disk
2514 * space or cancels the delete operation. */
2515
2516 /* second pass: */
2517 LogFlowThisFunc(("2: Deleting saved state...\n"));
2518
2519 {
2520 // saveAllSnapshots() needs a machine lock, and the snapshots
2521 // tree is protected by the machine lock as well
2522 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2523
2524 Utf8Str stateFilePath = aTask.pSnapshot->stateFilePath();
2525 if (!stateFilePath.isEmpty())
2526 {
2527 aTask.pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")).raw(),
2528 1); // weight
2529
2530 aTask.pSnapshot->deleteStateFile();
2531 // machine needs saving now
2532 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, getId());
2533 }
2534 }
2535
2536 /* third pass: */
2537 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
2538
2539 /// @todo NEWMEDIA turn the following errors into warnings because the
2540 /// snapshot itself has been already deleted (and interpret these
2541 /// warnings properly on the GUI side)
2542 for (MediumDeleteRecList::iterator it = toDelete.begin();
2543 it != toDelete.end();)
2544 {
2545 const ComObjPtr<Medium> &pMedium(it->mpHD);
2546 ULONG ulWeight;
2547
2548 {
2549 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
2550 ulWeight = (ULONG)(pMedium->getSize() / _1M);
2551 }
2552
2553 aTask.pProgress->SetNextOperation(BstrFmt(tr("Merging differencing image '%s'"),
2554 pMedium->getName().c_str()).raw(),
2555 ulWeight);
2556
2557 bool fNeedSourceUninit = false;
2558 bool fReparentTarget = false;
2559 if (it->mpMediumLockList == NULL)
2560 {
2561 /* no real merge needed, just updating state and delete
2562 * diff files if necessary */
2563 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
2564
2565 Assert( !it->mfMergeForward
2566 || pMedium->getChildren().size() == 0);
2567
2568 /* Delete the differencing hard disk (has no children). Two
2569 * exceptions: if it's the last medium in the chain or if it's
2570 * a backward merge we don't want to handle due to complexity.
2571 * In both cases leave the image in place. If it's the first
2572 * exception the user can delete it later if he wants. */
2573 if (!pMedium->getParent().isNull())
2574 {
2575 Assert(pMedium->getState() == MediumState_Deleting);
2576 /* No need to hold the lock any longer. */
2577 mLock.release();
2578 rc = pMedium->deleteStorage(&aTask.pProgress,
2579 true /* aWait */,
2580 &llRegistriesThatNeedSaving);
2581 if (FAILED(rc))
2582 throw rc;
2583
2584 // need to uninit the deleted medium
2585 fNeedSourceUninit = true;
2586 }
2587 }
2588 else
2589 {
2590 bool fNeedsSave = false;
2591 if (it->mfNeedsOnlineMerge)
2592 {
2593 // online medium merge, in the direction decided earlier
2594 rc = onlineMergeMedium(it->mpOnlineMediumAttachment,
2595 it->mpSource,
2596 it->mpTarget,
2597 it->mfMergeForward,
2598 it->mpParentForTarget,
2599 it->mChildrenToReparent,
2600 it->mpMediumLockList,
2601 aTask.pProgress,
2602 &fNeedsSave);
2603 }
2604 else
2605 {
2606 // normal medium merge, in the direction decided earlier
2607 rc = it->mpSource->mergeTo(it->mpTarget,
2608 it->mfMergeForward,
2609 it->mpParentForTarget,
2610 it->mChildrenToReparent,
2611 it->mpMediumLockList,
2612 &aTask.pProgress,
2613 true /* aWait */,
2614 &llRegistriesThatNeedSaving);
2615 }
2616
2617 // If the merge failed, we need to do our best to have a usable
2618 // VM configuration afterwards. The return code doesn't tell
2619 // whether the merge completed and so we have to check if the
2620 // source medium (diff images are always file based at the
2621 // moment) is still there or not. Be careful not to lose the
2622 // error code below, before the "Delayed failure exit".
2623 if (FAILED(rc))
2624 {
2625 AutoReadLock mlock(it->mpSource COMMA_LOCKVAL_SRC_POS);
2626 if (!it->mpSource->isMediumFormatFile())
2627 // Diff medium not backed by a file - cannot get status so
2628 // be pessimistic.
2629 throw rc;
2630 const Utf8Str &loc = it->mpSource->getLocationFull();
2631 // Source medium is still there, so merge failed early.
2632 if (RTFileExists(loc.c_str()))
2633 throw rc;
2634
2635 // Source medium is gone. Assume the merge succeeded and
2636 // thus it's safe to remove the attachment. We use the
2637 // "Delayed failure exit" below.
2638 }
2639
2640 // need to change the medium attachment for backward merges
2641 fReparentTarget = !it->mfMergeForward;
2642
2643 if (!it->mfNeedsOnlineMerge)
2644 {
2645 // need to uninit the medium deleted by the merge
2646 fNeedSourceUninit = true;
2647
2648 // delete the no longer needed medium lock list, which
2649 // implicitly handled the unlocking
2650 delete it->mpMediumLockList;
2651 it->mpMediumLockList = NULL;
2652 }
2653 }
2654
2655 // Now that the medium is successfully merged/deleted/whatever,
2656 // remove the medium attachment from the snapshot. For a backwards
2657 // merge the target attachment needs to be removed from the
2658 // snapshot, as the VM will take it over. For forward merges the
2659 // source medium attachment needs to be removed.
2660 ComObjPtr<MediumAttachment> pAtt;
2661 if (fReparentTarget)
2662 {
2663 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2664 it->mpTarget);
2665 it->mpTarget->removeBackReference(machineId, snapshotId);
2666 }
2667 else
2668 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2669 it->mpSource);
2670 pSnapMachine->mMediaData->mAttachments.remove(pAtt);
2671
2672 if (fReparentTarget)
2673 {
2674 // Search for old source attachment and replace with target.
2675 // There can be only one child snapshot in this case.
2676 ComObjPtr<Machine> pMachine = this;
2677 Guid childSnapshotId;
2678 ComObjPtr<Snapshot> pChildSnapshot = aTask.pSnapshot->getFirstChild();
2679 if (pChildSnapshot)
2680 {
2681 pMachine = pChildSnapshot->getSnapshotMachine();
2682 childSnapshotId = pChildSnapshot->getId();
2683 }
2684 pAtt = findAttachment(pMachine->mMediaData->mAttachments, it->mpSource);
2685 if (pAtt)
2686 {
2687 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
2688 pAtt->updateMedium(it->mpTarget);
2689 it->mpTarget->addBackReference(pMachine->mData->mUuid, childSnapshotId);
2690 }
2691 else
2692 {
2693 // If no attachment is found do not change anything. Maybe
2694 // the source medium was not attached to the snapshot.
2695 // If this is an online deletion the attachment was updated
2696 // already to allow the VM continue execution immediately.
2697 // Needs a bit of special treatment due to this difference.
2698 if (it->mfNeedsOnlineMerge)
2699 it->mpTarget->addBackReference(pMachine->mData->mUuid, childSnapshotId);
2700 }
2701 }
2702
2703 if (fNeedSourceUninit)
2704 it->mpSource->uninit();
2705
2706 // One attachment is merged, must save the settings
2707 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, getId());
2708
2709 // prevent calling cancelDeleteSnapshotMedium() for this attachment
2710 it = toDelete.erase(it);
2711
2712 // Delayed failure exit when the merge cleanup failed but the
2713 // merge actually succeeded.
2714 if (FAILED(rc))
2715 throw rc;
2716 }
2717
2718 {
2719 // beginSnapshotDelete() needs the machine lock, and the snapshots
2720 // tree is protected by the machine lock as well
2721 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2722
2723 aTask.pSnapshot->beginSnapshotDelete();
2724 aTask.pSnapshot->uninit();
2725
2726 mParent->addGuidToListUniquely(llRegistriesThatNeedSaving, getId());
2727 }
2728 }
2729 catch (HRESULT aRC) { rc = aRC; }
2730
2731 if (FAILED(rc))
2732 {
2733 // preserve existing error info so that the result can
2734 // be properly reported to the progress object below
2735 ErrorInfoKeeper eik;
2736
2737 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2738 &mParent->getMediaTreeLockHandle() // media tree
2739 COMMA_LOCKVAL_SRC_POS);
2740
2741 // un-prepare the remaining hard disks
2742 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
2743 it != toDelete.end();
2744 ++it)
2745 {
2746 cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
2747 it->mChildrenToReparent,
2748 it->mfNeedsOnlineMerge,
2749 it->mpMediumLockList, it->mMachineId,
2750 it->mSnapshotId);
2751 }
2752 }
2753
2754 // whether we were successful or not, we need to set the machine
2755 // state and save the machine settings;
2756 {
2757 // preserve existing error info so that the result can
2758 // be properly reported to the progress object below
2759 ErrorInfoKeeper eik;
2760
2761 // restore the machine state that was saved when the
2762 // task was started
2763 setMachineState(aTask.machineStateBackup);
2764 updateMachineStateOnClient();
2765
2766 mParent->saveRegistries(llRegistriesThatNeedSaving);
2767 }
2768
2769 // report the result (this will try to fetch current error info on failure)
2770 aTask.pProgress->notifyComplete(rc);
2771
2772 if (SUCCEEDED(rc))
2773 mParent->onSnapshotDeleted(mData->mUuid, snapshotId);
2774
2775 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", rc));
2776 LogFlowThisFuncLeave();
2777}
2778
2779/**
2780 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
2781 * performs necessary state changes. Must not be called for writethrough disks
2782 * because there is nothing to delete/merge then.
2783 *
2784 * This method is to be called prior to calling #deleteSnapshotMedium().
2785 * If #deleteSnapshotMedium() is not called or fails, the state modifications
2786 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
2787 *
2788 * @return COM status code
2789 * @param aHD Hard disk which is connected to the snapshot.
2790 * @param aMachineId UUID of machine this hard disk is attached to.
2791 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
2792 * be a zero UUID if no snapshot is applicable.
2793 * @param fOnlineMergePossible Flag whether an online merge is possible.
2794 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
2795 * Only used if @a fOnlineMergePossible is @c true, and
2796 * must be non-NULL in this case.
2797 * @param aSource Source hard disk for merge (out).
2798 * @param aTarget Target hard disk for merge (out).
2799 * @param aMergeForward Merge direction decision (out).
2800 * @param aParentForTarget New parent if target needs to be reparented (out).
2801 * @param aChildrenToReparent Children which have to be reparented to the
2802 * target (out).
2803 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
2804 * If this is set to @a true then the @a aVMMALockList
2805 * parameter has been modified and is returned as
2806 * @a aMediumLockList.
2807 * @param aMediumLockList Where to store the created medium lock list (may
2808 * return NULL if no real merge is necessary).
2809 *
2810 * @note Caller must hold media tree lock for writing. This locks this object
2811 * and every medium object on the merge chain for writing.
2812 */
2813HRESULT SessionMachine::prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
2814 const Guid &aMachineId,
2815 const Guid &aSnapshotId,
2816 bool fOnlineMergePossible,
2817 MediumLockList *aVMMALockList,
2818 ComObjPtr<Medium> &aSource,
2819 ComObjPtr<Medium> &aTarget,
2820 bool &aMergeForward,
2821 ComObjPtr<Medium> &aParentForTarget,
2822 MediaList &aChildrenToReparent,
2823 bool &fNeedsOnlineMerge,
2824 MediumLockList * &aMediumLockList)
2825{
2826 Assert(mParent->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
2827 Assert(!fOnlineMergePossible || VALID_PTR(aVMMALockList));
2828
2829 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
2830
2831 // Medium must not be writethrough/shareable/readonly at this point
2832 MediumType_T type = aHD->getType();
2833 AssertReturn( type != MediumType_Writethrough
2834 && type != MediumType_Shareable
2835 && type != MediumType_Readonly, E_FAIL);
2836
2837 aMediumLockList = NULL;
2838 fNeedsOnlineMerge = false;
2839
2840 if (aHD->getChildren().size() == 0)
2841 {
2842 /* This technically is no merge, set those values nevertheless.
2843 * Helps with updating the medium attachments. */
2844 aSource = aHD;
2845 aTarget = aHD;
2846
2847 /* special treatment of the last hard disk in the chain: */
2848 if (aHD->getParent().isNull())
2849 {
2850 /* lock only, to prevent any usage until the snapshot deletion
2851 * is completed */
2852 return aHD->LockWrite(NULL);
2853 }
2854
2855 /* the differencing hard disk w/o children will be deleted, protect it
2856 * from attaching to other VMs (this is why Deleting) */
2857 return aHD->markForDeletion();
2858 }
2859
2860 /* not going multi-merge as it's too expensive */
2861 if (aHD->getChildren().size() > 1)
2862 return setError(E_FAIL,
2863 tr("Hard disk '%s' has more than one child hard disk (%d)"),
2864 aHD->getLocationFull().c_str(),
2865 aHD->getChildren().size());
2866
2867 ComObjPtr<Medium> pChild = aHD->getChildren().front();
2868
2869 /* we keep this locked, so lock the affected child to make sure the lock
2870 * order is correct when calling prepareMergeTo() */
2871 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
2872
2873 /* the rest is a normal merge setup */
2874 if (aHD->getParent().isNull())
2875 {
2876 /* base hard disk, backward merge */
2877 const Guid *pMachineId1 = pChild->getFirstMachineBackrefId();
2878 const Guid *pMachineId2 = aHD->getFirstMachineBackrefId();
2879 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
2880 {
2881 /* backward merge is too tricky, we'll just detach on snapshot
2882 * deletion, so lock only, to prevent any usage */
2883 return aHD->LockWrite(NULL);
2884 }
2885
2886 aSource = pChild;
2887 aTarget = aHD;
2888 }
2889 else
2890 {
2891 /* forward merge */
2892 aSource = aHD;
2893 aTarget = pChild;
2894 }
2895
2896 HRESULT rc;
2897 rc = aSource->prepareMergeTo(aTarget, &aMachineId, &aSnapshotId,
2898 !fOnlineMergePossible /* fLockMedia */,
2899 aMergeForward, aParentForTarget,
2900 aChildrenToReparent, aMediumLockList);
2901 if (SUCCEEDED(rc) && fOnlineMergePossible)
2902 {
2903 /* Try to lock the newly constructed medium lock list. If it succeeds
2904 * this can be handled as an offline merge, i.e. without the need of
2905 * asking the VM to do the merging. Only continue with the online
2906 * merging preparation if applicable. */
2907 rc = aMediumLockList->Lock();
2908 if (FAILED(rc) && fOnlineMergePossible)
2909 {
2910 /* Locking failed, this cannot be done as an offline merge. Try to
2911 * combine the locking information into the lock list of the medium
2912 * attachment in the running VM. If that fails or locking the
2913 * resulting lock list fails then the merge cannot be done online.
2914 * It can be repeated by the user when the VM is shut down. */
2915 MediumLockList::Base::iterator lockListVMMABegin =
2916 aVMMALockList->GetBegin();
2917 MediumLockList::Base::iterator lockListVMMAEnd =
2918 aVMMALockList->GetEnd();
2919 MediumLockList::Base::iterator lockListBegin =
2920 aMediumLockList->GetBegin();
2921 MediumLockList::Base::iterator lockListEnd =
2922 aMediumLockList->GetEnd();
2923 for (MediumLockList::Base::iterator it = lockListVMMABegin,
2924 it2 = lockListBegin;
2925 it2 != lockListEnd;
2926 ++it, ++it2)
2927 {
2928 if ( it == lockListVMMAEnd
2929 || it->GetMedium() != it2->GetMedium())
2930 {
2931 fOnlineMergePossible = false;
2932 break;
2933 }
2934 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
2935 rc = it->UpdateLock(fLockReq);
2936 if (FAILED(rc))
2937 {
2938 // could not update the lock, trigger cleanup below
2939 fOnlineMergePossible = false;
2940 break;
2941 }
2942 }
2943
2944 if (fOnlineMergePossible)
2945 {
2946 /* we will lock the children of the source for reparenting */
2947 for (MediaList::const_iterator it = aChildrenToReparent.begin();
2948 it != aChildrenToReparent.end();
2949 ++it)
2950 {
2951 ComObjPtr<Medium> pMedium = *it;
2952 if (pMedium->getState() == MediumState_Created)
2953 {
2954 rc = pMedium->LockWrite(NULL);
2955 if (FAILED(rc))
2956 throw rc;
2957 }
2958 else
2959 {
2960 rc = aVMMALockList->Update(pMedium, true);
2961 if (FAILED(rc))
2962 {
2963 rc = pMedium->LockWrite(NULL);
2964 if (FAILED(rc))
2965 throw rc;
2966 }
2967 }
2968 }
2969 }
2970
2971 if (fOnlineMergePossible)
2972 {
2973 rc = aVMMALockList->Lock();
2974 if (FAILED(rc))
2975 {
2976 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2977 rc = setError(rc,
2978 tr("Cannot lock hard disk '%s' for a live merge"),
2979 aHD->getLocationFull().c_str());
2980 }
2981 else
2982 {
2983 delete aMediumLockList;
2984 aMediumLockList = aVMMALockList;
2985 fNeedsOnlineMerge = true;
2986 }
2987 }
2988 else
2989 {
2990 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2991 rc = setError(rc,
2992 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
2993 aHD->getLocationFull().c_str());
2994 }
2995
2996 // fix the VM's lock list if anything failed
2997 if (FAILED(rc))
2998 {
2999 lockListVMMABegin = aVMMALockList->GetBegin();
3000 lockListVMMAEnd = aVMMALockList->GetEnd();
3001 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
3002 lockListLast--;
3003 for (MediumLockList::Base::iterator it = lockListVMMABegin;
3004 it != lockListVMMAEnd;
3005 ++it)
3006 {
3007 it->UpdateLock(it == lockListLast);
3008 ComObjPtr<Medium> pMedium = it->GetMedium();
3009 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3010 // blindly apply this, only needed for medium objects which
3011 // would be deleted as part of the merge
3012 pMedium->unmarkLockedForDeletion();
3013 }
3014 }
3015
3016 }
3017 else
3018 {
3019 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
3020 rc = setError(rc,
3021 tr("Cannot lock hard disk '%s' for an offline merge"),
3022 aHD->getLocationFull().c_str());
3023 }
3024 }
3025
3026 return rc;
3027}
3028
3029/**
3030 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
3031 * what #prepareDeleteSnapshotMedium() did. Must be called if
3032 * #deleteSnapshotMedium() is not called or fails.
3033 *
3034 * @param aHD Hard disk which is connected to the snapshot.
3035 * @param aSource Source hard disk for merge.
3036 * @param aChildrenToReparent Children to unlock.
3037 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
3038 * @param aMediumLockList Medium locks to cancel.
3039 * @param aMachineId Machine id to attach the medium to.
3040 * @param aSnapshotId Snapshot id to attach the medium to.
3041 *
3042 * @note Locks the medium tree and the hard disks in the chain for writing.
3043 */
3044void SessionMachine::cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3045 const ComObjPtr<Medium> &aSource,
3046 const MediaList &aChildrenToReparent,
3047 bool fNeedsOnlineMerge,
3048 MediumLockList *aMediumLockList,
3049 const Guid &aMachineId,
3050 const Guid &aSnapshotId)
3051{
3052 if (aMediumLockList == NULL)
3053 {
3054 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
3055
3056 Assert(aHD->getChildren().size() == 0);
3057
3058 if (aHD->getParent().isNull())
3059 {
3060 HRESULT rc = aHD->UnlockWrite(NULL);
3061 AssertComRC(rc);
3062 }
3063 else
3064 {
3065 HRESULT rc = aHD->unmarkForDeletion();
3066 AssertComRC(rc);
3067 }
3068 }
3069 else
3070 {
3071 if (fNeedsOnlineMerge)
3072 {
3073 // Online merge uses the medium lock list of the VM, so give
3074 // an empty list to cancelMergeTo so that it works as designed.
3075 aSource->cancelMergeTo(aChildrenToReparent, new MediumLockList());
3076
3077 // clean up the VM medium lock list ourselves
3078 MediumLockList::Base::iterator lockListBegin =
3079 aMediumLockList->GetBegin();
3080 MediumLockList::Base::iterator lockListEnd =
3081 aMediumLockList->GetEnd();
3082 MediumLockList::Base::iterator lockListLast = lockListEnd;
3083 lockListLast--;
3084 for (MediumLockList::Base::iterator it = lockListBegin;
3085 it != lockListEnd;
3086 ++it)
3087 {
3088 ComObjPtr<Medium> pMedium = it->GetMedium();
3089 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3090 if (pMedium->getState() == MediumState_Deleting)
3091 pMedium->unmarkForDeletion();
3092 else
3093 {
3094 // blindly apply this, only needed for medium objects which
3095 // would be deleted as part of the merge
3096 pMedium->unmarkLockedForDeletion();
3097 }
3098 it->UpdateLock(it == lockListLast);
3099 }
3100 }
3101 else
3102 {
3103 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
3104 }
3105 }
3106
3107 if (!aMachineId.isEmpty())
3108 {
3109 // reattach the source media to the snapshot
3110 HRESULT rc = aSource->addBackReference(aMachineId, aSnapshotId);
3111 AssertComRC(rc);
3112 }
3113}
3114
3115/**
3116 * Perform an online merge of a hard disk, i.e. the equivalent of
3117 * Medium::mergeTo(), just for running VMs. If this fails you need to call
3118 * #cancelDeleteSnapshotMedium().
3119 *
3120 * @return COM status code
3121 * @param aMediumAttachment Identify where the disk is attached in the VM.
3122 * @param aSource Source hard disk for merge.
3123 * @param aTarget Target hard disk for merge.
3124 * @param aMergeForward Merge direction.
3125 * @param aParentForTarget New parent if target needs to be reparented.
3126 * @param aChildrenToReparent Children which have to be reparented to the
3127 * target.
3128 * @param aMediumLockList Where to store the created medium lock list (may
3129 * return NULL if no real merge is necessary).
3130 * @param aProgress Progress indicator.
3131 * @param pfNeedsMachineSaveSettings Whether the VM settings need to be saved (out).
3132 */
3133HRESULT SessionMachine::onlineMergeMedium(const ComObjPtr<MediumAttachment> &aMediumAttachment,
3134 const ComObjPtr<Medium> &aSource,
3135 const ComObjPtr<Medium> &aTarget,
3136 bool fMergeForward,
3137 const ComObjPtr<Medium> &aParentForTarget,
3138 const MediaList &aChildrenToReparent,
3139 MediumLockList *aMediumLockList,
3140 ComObjPtr<Progress> &aProgress,
3141 bool *pfNeedsMachineSaveSettings)
3142{
3143 AssertReturn(aSource != NULL, E_FAIL);
3144 AssertReturn(aTarget != NULL, E_FAIL);
3145 AssertReturn(aSource != aTarget, E_FAIL);
3146 AssertReturn(aMediumLockList != NULL, E_FAIL);
3147
3148 HRESULT rc = S_OK;
3149
3150 try
3151 {
3152 // Similar code appears in Medium::taskMergeHandle, so
3153 // if you make any changes below check whether they are applicable
3154 // in that context as well.
3155
3156 unsigned uTargetIdx = (unsigned)-1;
3157 unsigned uSourceIdx = (unsigned)-1;
3158 /* Sanity check all hard disks in the chain. */
3159 MediumLockList::Base::iterator lockListBegin =
3160 aMediumLockList->GetBegin();
3161 MediumLockList::Base::iterator lockListEnd =
3162 aMediumLockList->GetEnd();
3163 unsigned i = 0;
3164 for (MediumLockList::Base::iterator it = lockListBegin;
3165 it != lockListEnd;
3166 ++it)
3167 {
3168 MediumLock &mediumLock = *it;
3169 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
3170
3171 if (pMedium == aSource)
3172 uSourceIdx = i;
3173 else if (pMedium == aTarget)
3174 uTargetIdx = i;
3175
3176 // In Medium::taskMergeHandler there is lots of consistency
3177 // checking which we cannot do here, as the state details are
3178 // impossible to get outside the Medium class. The locking should
3179 // have done the checks already.
3180
3181 i++;
3182 }
3183
3184 ComAssertThrow( uSourceIdx != (unsigned)-1
3185 && uTargetIdx != (unsigned)-1, E_FAIL);
3186
3187 // For forward merges, tell the VM what images need to have their
3188 // parent UUID updated. This cannot be done in VBoxSVC, as opening
3189 // the required parent images is not safe while the VM is running.
3190 // For backward merges this will be simply an array of size 0.
3191 com::SafeIfaceArray<IMedium> childrenToReparent(aChildrenToReparent);
3192
3193 ComPtr<IInternalSessionControl> directControl;
3194 {
3195 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3196
3197 if (mData->mSession.mState != SessionState_Locked)
3198 throw setError(VBOX_E_INVALID_VM_STATE,
3199 tr("Machine is not locked by a session (session state: %s)"),
3200 Global::stringifySessionState(mData->mSession.mState));
3201 directControl = mData->mSession.mDirectControl;
3202 }
3203
3204 // Must not hold any locks here, as this will call back to finish
3205 // updating the medium attachment, chain linking and state.
3206 rc = directControl->OnlineMergeMedium(aMediumAttachment,
3207 uSourceIdx, uTargetIdx,
3208 aSource, aTarget,
3209 fMergeForward, aParentForTarget,
3210 ComSafeArrayAsInParam(childrenToReparent),
3211 aProgress);
3212 if (FAILED(rc))
3213 throw rc;
3214 }
3215 catch (HRESULT aRC) { rc = aRC; }
3216
3217 // The callback mentioned above takes care of update the medium state
3218
3219 if (pfNeedsMachineSaveSettings)
3220 *pfNeedsMachineSaveSettings = true;
3221
3222 return rc;
3223}
3224
3225/**
3226 * Implementation for IInternalMachineControl::finishOnlineMergeMedium().
3227 *
3228 * Gets called after the successful completion of an online merge from
3229 * Console::onlineMergeMedium(), which gets invoked indirectly above in
3230 * the call to IInternalSessionControl::onlineMergeMedium.
3231 *
3232 * This updates the medium information and medium state so that the VM
3233 * can continue with the updated state of the medium chain.
3234 */
3235STDMETHODIMP SessionMachine::FinishOnlineMergeMedium(IMediumAttachment *aMediumAttachment,
3236 IMedium *aSource,
3237 IMedium *aTarget,
3238 BOOL aMergeForward,
3239 IMedium *aParentForTarget,
3240 ComSafeArrayIn(IMedium *, aChildrenToReparent))
3241{
3242 HRESULT rc = S_OK;
3243 ComObjPtr<Medium> pSource(static_cast<Medium *>(aSource));
3244 ComObjPtr<Medium> pTarget(static_cast<Medium *>(aTarget));
3245 ComObjPtr<Medium> pParentForTarget(static_cast<Medium *>(aParentForTarget));
3246 bool fSourceHasChildren = false;
3247
3248 // all hard disks but the target were successfully deleted by
3249 // the merge; reparent target if necessary and uninitialize media
3250
3251 AutoWriteLock treeLock(mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3252
3253 // Declare this here to make sure the object does not get uninitialized
3254 // before this method completes. Would normally happen as halfway through
3255 // we delete the last reference to the no longer existing medium object.
3256 ComObjPtr<Medium> targetChild;
3257
3258 if (aMergeForward)
3259 {
3260 // first, unregister the target since it may become a base
3261 // hard disk which needs re-registration
3262 rc = mParent->unregisterHardDisk(pTarget, NULL /*&fNeedsGlobalSaveSettings*/);
3263 AssertComRC(rc);
3264
3265 // then, reparent it and disconnect the deleted branch at
3266 // both ends (chain->parent() is source's parent)
3267 pTarget->deparent();
3268 pTarget->setParent(pParentForTarget);
3269 if (pParentForTarget)
3270 pSource->deparent();
3271
3272 // then, register again
3273 rc = mParent->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
3274 AssertComRC(rc);
3275 }
3276 else
3277 {
3278 Assert(pTarget->getChildren().size() == 1);
3279 targetChild = pTarget->getChildren().front();
3280
3281 // disconnect the deleted branch at the elder end
3282 targetChild->deparent();
3283
3284 // Update parent UUIDs of the source's children, reparent them and
3285 // disconnect the deleted branch at the younger end
3286 com::SafeIfaceArray<IMedium> childrenToReparent(ComSafeArrayInArg(aChildrenToReparent));
3287 if (childrenToReparent.size() > 0)
3288 {
3289 fSourceHasChildren = true;
3290 // Fix the parent UUID of the images which needs to be moved to
3291 // underneath target. The running machine has the images opened,
3292 // but only for reading since the VM is paused. If anything fails
3293 // we must continue. The worst possible result is that the images
3294 // need manual fixing via VBoxManage to adjust the parent UUID.
3295 MediaList toReparent;
3296 for (size_t i = 0; i < childrenToReparent.size(); i++)
3297 {
3298 Medium *pMedium = static_cast<Medium *>(childrenToReparent[i]);
3299 toReparent.push_back(pMedium);
3300 }
3301 pTarget->fixParentUuidOfChildren(toReparent);
3302
3303 // obey {parent,child} lock order
3304 AutoWriteLock sourceLock(pSource COMMA_LOCKVAL_SRC_POS);
3305
3306 for (size_t i = 0; i < childrenToReparent.size(); i++)
3307 {
3308 Medium *pMedium = static_cast<Medium *>(childrenToReparent[i]);
3309 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
3310
3311 pMedium->deparent(); // removes pMedium from source
3312 pMedium->setParent(pTarget);
3313 }
3314 }
3315 }
3316
3317 /* unregister and uninitialize all hard disks removed by the merge */
3318 MediumLockList *pMediumLockList = NULL;
3319 MediumAttachment *pMediumAttachment = static_cast<MediumAttachment *>(aMediumAttachment);
3320 rc = mData->mSession.mLockedMedia.Get(pMediumAttachment, pMediumLockList);
3321 const ComObjPtr<Medium> &pLast = aMergeForward ? pTarget : pSource;
3322 AssertReturn(SUCCEEDED(rc) && pMediumLockList, E_FAIL);
3323 MediumLockList::Base::iterator lockListBegin =
3324 pMediumLockList->GetBegin();
3325 MediumLockList::Base::iterator lockListEnd =
3326 pMediumLockList->GetEnd();
3327 for (MediumLockList::Base::iterator it = lockListBegin;
3328 it != lockListEnd;
3329 )
3330 {
3331 MediumLock &mediumLock = *it;
3332 /* Create a real copy of the medium pointer, as the medium
3333 * lock deletion below would invalidate the referenced object. */
3334 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
3335
3336 /* The target and all images not merged (readonly) are skipped */
3337 if ( pMedium == pTarget
3338 || pMedium->getState() == MediumState_LockedRead)
3339 {
3340 ++it;
3341 }
3342 else
3343 {
3344 rc = mParent->unregisterHardDisk(pMedium,
3345 NULL /*pfNeedsGlobalSaveSettings*/);
3346 AssertComRC(rc);
3347
3348 /* now, uninitialize the deleted hard disk (note that
3349 * due to the Deleting state, uninit() will not touch
3350 * the parent-child relationship so we need to
3351 * uninitialize each disk individually) */
3352
3353 /* note that the operation initiator hard disk (which is
3354 * normally also the source hard disk) is a special case
3355 * -- there is one more caller added by Task to it which
3356 * we must release. Also, if we are in sync mode, the
3357 * caller may still hold an AutoCaller instance for it
3358 * and therefore we cannot uninit() it (it's therefore
3359 * the caller's responsibility) */
3360 if (pMedium == aSource)
3361 {
3362 Assert(pSource->getChildren().size() == 0);
3363 Assert(pSource->getFirstMachineBackrefId() == NULL);
3364 }
3365
3366 /* Delete the medium lock list entry, which also releases the
3367 * caller added by MergeChain before uninit() and updates the
3368 * iterator to point to the right place. */
3369 rc = pMediumLockList->RemoveByIterator(it);
3370 AssertComRC(rc);
3371
3372 pMedium->uninit();
3373 }
3374
3375 /* Stop as soon as we reached the last medium affected by the merge.
3376 * The remaining images must be kept unchanged. */
3377 if (pMedium == pLast)
3378 break;
3379 }
3380
3381 /* Could be in principle folded into the previous loop, but let's keep
3382 * things simple. Update the medium locking to be the standard state:
3383 * all parent images locked for reading, just the last diff for writing. */
3384 lockListBegin = pMediumLockList->GetBegin();
3385 lockListEnd = pMediumLockList->GetEnd();
3386 MediumLockList::Base::iterator lockListLast = lockListEnd;
3387 lockListLast--;
3388 for (MediumLockList::Base::iterator it = lockListBegin;
3389 it != lockListEnd;
3390 ++it)
3391 {
3392 it->UpdateLock(it == lockListLast);
3393 }
3394
3395 /* If this is a backwards merge of the only remaining snapshot (i.e. the
3396 * source has no children) then update the medium associated with the
3397 * attachment, as the previously associated one (source) is now deleted.
3398 * Without the immediate update the VM could not continue running. */
3399 if (!aMergeForward && !fSourceHasChildren)
3400 {
3401 AutoWriteLock attLock(pMediumAttachment COMMA_LOCKVAL_SRC_POS);
3402 pMediumAttachment->updateMedium(pTarget);
3403 }
3404
3405 return S_OK;
3406}
Note: See TracBrowser for help on using the repository browser.

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