VirtualBox

source: vbox/trunk/src/VBox/Main/SnapshotImpl.cpp@ 34079

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

Main: rework 'save registries' logic to ensure that all media registries get saved, not just the global VirtualBox.xml file

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

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