VirtualBox

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

Last change on this file since 31296 was 31242, checked in by vboxsync, 15 years ago

Main: finish Machine::Unregister(), which can now recursively delete all snapshots and differencing media

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 122.9 KB
Line 
1/* $Id: SnapshotImpl.cpp 31242 2010-07-30 13:06:39Z 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 Completetion precentage (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.raw());
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 char *aOldPath, const char *aNewPath)
691{
692 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
693
694 const Utf8Str &path = m->pMachine->mSSData->mStateFilePath;
695 LogFlowThisFunc(("Snap[%s].statePath={%s}\n", m->strName.c_str(), path.c_str()));
696
697 /* state file may be NULL (for offline snapshots) */
698 if ( path.length()
699 && RTPathStartsWith(path.c_str(), aOldPath)
700 )
701 {
702 m->pMachine->mSSData->mStateFilePath = Utf8StrFmt("%s%s", aNewPath, path.raw() + strlen(aOldPath));
703
704 LogFlowThisFunc(("-> updated: {%s}\n", path.raw()));
705 }
706
707 for (SnapshotsList::const_iterator it = m->llChildren.begin();
708 it != m->llChildren.end();
709 ++it)
710 {
711 Snapshot *pChild = *it;
712 pChild->updateSavedStatePathsImpl(aOldPath, aNewPath);
713 }
714}
715
716/**
717 * Checks if the specified path change affects the saved state file path of
718 * this snapshot or any of its (grand-)children and updates it accordingly.
719 *
720 * Intended to be called by Machine::openConfigLoader() only.
721 *
722 * @param aOldPath old path (full)
723 * @param aNewPath new path (full)
724 *
725 * @note Locks the machine (for the snapshots tree) + this object + children for writing.
726 */
727void Snapshot::updateSavedStatePaths(const char *aOldPath, const char *aNewPath)
728{
729 LogFlowThisFunc(("aOldPath={%s} aNewPath={%s}\n", aOldPath, aNewPath));
730
731 AssertReturnVoid(aOldPath);
732 AssertReturnVoid(aNewPath);
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(aOldPath, aNewPath);
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 updatge 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 llFilenames
831 * @return
832 */
833HRESULT Snapshot::uninitRecursively(AutoWriteLock &writeLock,
834 MediaList &llMedia,
835 std::list<Utf8Str> &llFilenames)
836{
837 Assert(m->pMachine->isWriteLockOnCurrentThread());
838
839 HRESULT rc = S_OK;
840
841 // make a copy of the Guid for logging before we uninit ourselfs
842#ifdef LOG_ENABLED
843 Guid uuid = getId();
844 Utf8Str name = getName();
845 LogFlowThisFunc(("Entering for snapshot '%s' {%RTuuid}\n", name.c_str(), uuid.raw()));
846#endif
847
848 // recurse into children first so that the child media appear on
849 // the list first; this way caller can close the media from the
850 // beginning to the end because parent media can't be closed if
851 // they have children
852
853 // make a copy of the children list since uninit() modifies it
854 SnapshotsList llChildrenCopy(m->llChildren);
855 for (SnapshotsList::iterator it = llChildrenCopy.begin();
856 it != llChildrenCopy.end();
857 ++it)
858 {
859 Snapshot *pChild = *it;
860 rc = pChild->uninitRecursively(writeLock, llMedia, llFilenames);
861 if (FAILED(rc))
862 return rc;
863 }
864
865 // now call detachAllMedia on the snapshot machine
866 rc = m->pMachine->detachAllMedia(writeLock,
867 this /* pSnapshot */,
868 llMedia);
869 if (FAILED(rc))
870 return rc;
871
872 // now report the saved state file
873 if (!m->pMachine->mSSData->mStateFilePath.isEmpty())
874 llFilenames.push_back(m->pMachine->mSSData->mStateFilePath);
875
876 this->beginSnapshotDelete();
877 this->uninit();
878
879#ifdef LOG_ENABLED
880 LogFlowThisFunc(("Leaving for snapshot '%s' {%RTuuid}\n", name.c_str(), uuid.raw()));
881#endif
882
883 return S_OK;
884}
885
886////////////////////////////////////////////////////////////////////////////////
887//
888// SnapshotMachine implementation
889//
890////////////////////////////////////////////////////////////////////////////////
891
892DEFINE_EMPTY_CTOR_DTOR(SnapshotMachine)
893
894HRESULT SnapshotMachine::FinalConstruct()
895{
896 LogFlowThisFunc(("\n"));
897
898 return S_OK;
899}
900
901void SnapshotMachine::FinalRelease()
902{
903 LogFlowThisFunc(("\n"));
904
905 uninit();
906}
907
908/**
909 * Initializes the SnapshotMachine object when taking a snapshot.
910 *
911 * @param aSessionMachine machine to take a snapshot from
912 * @param aSnapshotId snapshot ID of this snapshot machine
913 * @param aStateFilePath file where the execution state will be later saved
914 * (or NULL for the offline snapshot)
915 *
916 * @note The aSessionMachine must be locked for writing.
917 */
918HRESULT SnapshotMachine::init(SessionMachine *aSessionMachine,
919 IN_GUID aSnapshotId,
920 const Utf8Str &aStateFilePath)
921{
922 LogFlowThisFuncEnter();
923 LogFlowThisFunc(("mName={%ls}\n", aSessionMachine->mUserData->mName.raw()));
924
925 AssertReturn(aSessionMachine && !Guid(aSnapshotId).isEmpty(), E_INVALIDARG);
926
927 /* Enclose the state transition NotReady->InInit->Ready */
928 AutoInitSpan autoInitSpan(this);
929 AssertReturn(autoInitSpan.isOk(), E_FAIL);
930
931 AssertReturn(aSessionMachine->isWriteLockOnCurrentThread(), E_FAIL);
932
933 mSnapshotId = aSnapshotId;
934
935 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
936 unconst(mPeer) = aSessionMachine->mPeer;
937 /* share the parent pointer */
938 unconst(mParent) = mPeer->mParent;
939
940 /* take the pointer to Data to share */
941 mData.share(mPeer->mData);
942
943 /* take the pointer to UserData to share (our UserData must always be the
944 * same as Machine's data) */
945 mUserData.share(mPeer->mUserData);
946 /* make a private copy of all other data (recent changes from SessionMachine) */
947 mHWData.attachCopy(aSessionMachine->mHWData);
948 mMediaData.attachCopy(aSessionMachine->mMediaData);
949
950 /* SSData is always unique for SnapshotMachine */
951 mSSData.allocate();
952 mSSData->mStateFilePath = aStateFilePath;
953
954 HRESULT rc = S_OK;
955
956 /* create copies of all shared folders (mHWData after attiching a copy
957 * contains just references to original objects) */
958 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
959 it != mHWData->mSharedFolders.end();
960 ++it)
961 {
962 ComObjPtr<SharedFolder> folder;
963 folder.createObject();
964 rc = folder->initCopy(this, *it);
965 if (FAILED(rc)) return rc;
966 *it = folder;
967 }
968
969 /* associate hard disks with the snapshot
970 * (Machine::uninitDataAndChildObjects() will deassociate at destruction) */
971 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
972 it != mMediaData->mAttachments.end();
973 ++it)
974 {
975 MediumAttachment *pAtt = *it;
976 Medium *pMedium = pAtt->getMedium();
977 if (pMedium) // can be NULL for non-harddisk
978 {
979 rc = pMedium->addBackReference(mData->mUuid, mSnapshotId);
980 AssertComRC(rc);
981 }
982 }
983
984 /* create copies of all storage controllers (mStorageControllerData
985 * after attaching a copy contains just references to original objects) */
986 mStorageControllers.allocate();
987 for (StorageControllerList::const_iterator
988 it = aSessionMachine->mStorageControllers->begin();
989 it != aSessionMachine->mStorageControllers->end();
990 ++it)
991 {
992 ComObjPtr<StorageController> ctrl;
993 ctrl.createObject();
994 ctrl->initCopy(this, *it);
995 mStorageControllers->push_back(ctrl);
996 }
997
998 /* create all other child objects that will be immutable private copies */
999
1000 unconst(mBIOSSettings).createObject();
1001 mBIOSSettings->initCopy(this, mPeer->mBIOSSettings);
1002
1003#ifdef VBOX_WITH_VRDP
1004 unconst(mVRDPServer).createObject();
1005 mVRDPServer->initCopy(this, mPeer->mVRDPServer);
1006#endif
1007
1008 unconst(mAudioAdapter).createObject();
1009 mAudioAdapter->initCopy(this, mPeer->mAudioAdapter);
1010
1011 unconst(mUSBController).createObject();
1012 mUSBController->initCopy(this, mPeer->mUSBController);
1013
1014 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
1015 {
1016 unconst(mNetworkAdapters[slot]).createObject();
1017 mNetworkAdapters[slot]->initCopy(this, mPeer->mNetworkAdapters[slot]);
1018 }
1019
1020 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
1021 {
1022 unconst(mSerialPorts[slot]).createObject();
1023 mSerialPorts[slot]->initCopy(this, mPeer->mSerialPorts[slot]);
1024 }
1025
1026 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
1027 {
1028 unconst(mParallelPorts[slot]).createObject();
1029 mParallelPorts[slot]->initCopy(this, mPeer->mParallelPorts[slot]);
1030 }
1031
1032 /* Confirm a successful initialization when it's the case */
1033 autoInitSpan.setSucceeded();
1034
1035 LogFlowThisFuncLeave();
1036 return S_OK;
1037}
1038
1039/**
1040 * Initializes the SnapshotMachine object when loading from the settings file.
1041 *
1042 * @param aMachine machine the snapshot belngs to
1043 * @param aHWNode <Hardware> node
1044 * @param aHDAsNode <HardDiskAttachments> node
1045 * @param aSnapshotId snapshot ID of this snapshot machine
1046 * @param aStateFilePath file where the execution state is saved
1047 * (or NULL for the offline snapshot)
1048 *
1049 * @note Doesn't lock anything.
1050 */
1051HRESULT SnapshotMachine::init(Machine *aMachine,
1052 const settings::Hardware &hardware,
1053 const settings::Storage &storage,
1054 IN_GUID aSnapshotId,
1055 const Utf8Str &aStateFilePath)
1056{
1057 LogFlowThisFuncEnter();
1058 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
1059
1060 AssertReturn(aMachine && !Guid(aSnapshotId).isEmpty(), E_INVALIDARG);
1061
1062 /* Enclose the state transition NotReady->InInit->Ready */
1063 AutoInitSpan autoInitSpan(this);
1064 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1065
1066 /* Don't need to lock aMachine when VirtualBox is starting up */
1067
1068 mSnapshotId = aSnapshotId;
1069
1070 /* memorize the primary Machine instance */
1071 unconst(mPeer) = aMachine;
1072 /* share the parent pointer */
1073 unconst(mParent) = mPeer->mParent;
1074
1075 /* take the pointer to Data to share */
1076 mData.share(mPeer->mData);
1077 /*
1078 * take the pointer to UserData to share
1079 * (our UserData must always be the same as Machine's data)
1080 */
1081 mUserData.share(mPeer->mUserData);
1082 /* allocate private copies of all other data (will be loaded from settings) */
1083 mHWData.allocate();
1084 mMediaData.allocate();
1085 mStorageControllers.allocate();
1086
1087 /* SSData is always unique for SnapshotMachine */
1088 mSSData.allocate();
1089 mSSData->mStateFilePath = aStateFilePath;
1090
1091 /* create all other child objects that will be immutable private copies */
1092
1093 unconst(mBIOSSettings).createObject();
1094 mBIOSSettings->init(this);
1095
1096#ifdef VBOX_WITH_VRDP
1097 unconst(mVRDPServer).createObject();
1098 mVRDPServer->init(this);
1099#endif
1100
1101 unconst(mAudioAdapter).createObject();
1102 mAudioAdapter->init(this);
1103
1104 unconst(mUSBController).createObject();
1105 mUSBController->init(this);
1106
1107 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
1108 {
1109 unconst(mNetworkAdapters[slot]).createObject();
1110 mNetworkAdapters[slot]->init(this, slot);
1111 }
1112
1113 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
1114 {
1115 unconst(mSerialPorts[slot]).createObject();
1116 mSerialPorts[slot]->init(this, slot);
1117 }
1118
1119 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
1120 {
1121 unconst(mParallelPorts[slot]).createObject();
1122 mParallelPorts[slot]->init(this, slot);
1123 }
1124
1125 /* load hardware and harddisk settings */
1126
1127 HRESULT rc = loadHardware(hardware);
1128 if (SUCCEEDED(rc))
1129 rc = loadStorageControllers(storage, &mSnapshotId);
1130
1131 if (SUCCEEDED(rc))
1132 /* commit all changes made during the initialization */
1133 commit(); // @todo r=dj why do we need a commit in init?!? this is very expensive
1134
1135 /* Confirm a successful initialization when it's the case */
1136 if (SUCCEEDED(rc))
1137 autoInitSpan.setSucceeded();
1138
1139 LogFlowThisFuncLeave();
1140 return rc;
1141}
1142
1143/**
1144 * Uninitializes this SnapshotMachine object.
1145 */
1146void SnapshotMachine::uninit()
1147{
1148 LogFlowThisFuncEnter();
1149
1150 /* Enclose the state transition Ready->InUninit->NotReady */
1151 AutoUninitSpan autoUninitSpan(this);
1152 if (autoUninitSpan.uninitDone())
1153 return;
1154
1155 uninitDataAndChildObjects();
1156
1157 /* free the essential data structure last */
1158 mData.free();
1159
1160 unconst(mParent) = NULL;
1161 unconst(mPeer) = NULL;
1162
1163 LogFlowThisFuncLeave();
1164}
1165
1166/**
1167 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
1168 * with the primary Machine instance (mPeer).
1169 */
1170RWLockHandle *SnapshotMachine::lockHandle() const
1171{
1172 AssertReturn(mPeer != NULL, NULL);
1173 return mPeer->lockHandle();
1174}
1175
1176////////////////////////////////////////////////////////////////////////////////
1177//
1178// SnapshotMachine public internal methods
1179//
1180////////////////////////////////////////////////////////////////////////////////
1181
1182/**
1183 * Called by the snapshot object associated with this SnapshotMachine when
1184 * snapshot data such as name or description is changed.
1185 *
1186 * @note Locks this object for writing.
1187 */
1188HRESULT SnapshotMachine::onSnapshotChange(Snapshot *aSnapshot)
1189{
1190 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1191
1192 // mPeer->saveAllSnapshots(); @todo
1193
1194 /* inform callbacks */
1195 mParent->onSnapshotChange(mData->mUuid, aSnapshot->getId());
1196
1197 return S_OK;
1198}
1199
1200////////////////////////////////////////////////////////////////////////////////
1201//
1202// SessionMachine task records
1203//
1204////////////////////////////////////////////////////////////////////////////////
1205
1206/**
1207 * Abstract base class for SessionMachine::RestoreSnapshotTask and
1208 * SessionMachine::DeleteSnapshotTask. This is necessary since
1209 * RTThreadCreate cannot call a method as its thread function, so
1210 * instead we have it call the static SessionMachine::taskHandler,
1211 * which can then call the handler() method in here (implemented
1212 * by the children).
1213 */
1214struct SessionMachine::SnapshotTask
1215{
1216 SnapshotTask(SessionMachine *m,
1217 Progress *p,
1218 Snapshot *s)
1219 : pMachine(m),
1220 pProgress(p),
1221 machineStateBackup(m->mData->mMachineState), // save the current machine state
1222 pSnapshot(s)
1223 {}
1224
1225 void modifyBackedUpState(MachineState_T s)
1226 {
1227 *const_cast<MachineState_T*>(&machineStateBackup) = s;
1228 }
1229
1230 virtual void handler() = 0;
1231
1232 ComObjPtr<SessionMachine> pMachine;
1233 ComObjPtr<Progress> pProgress;
1234 const MachineState_T machineStateBackup;
1235 ComObjPtr<Snapshot> pSnapshot;
1236};
1237
1238/** Restore snapshot state task */
1239struct SessionMachine::RestoreSnapshotTask
1240 : public SessionMachine::SnapshotTask
1241{
1242 RestoreSnapshotTask(SessionMachine *m,
1243 Progress *p,
1244 Snapshot *s,
1245 ULONG ulStateFileSizeMB)
1246 : SnapshotTask(m, p, s),
1247 m_ulStateFileSizeMB(ulStateFileSizeMB)
1248 {}
1249
1250 void handler()
1251 {
1252 pMachine->restoreSnapshotHandler(*this);
1253 }
1254
1255 ULONG m_ulStateFileSizeMB;
1256};
1257
1258/** Delete snapshot task */
1259struct SessionMachine::DeleteSnapshotTask
1260 : public SessionMachine::SnapshotTask
1261{
1262 DeleteSnapshotTask(SessionMachine *m,
1263 Progress *p,
1264 bool fDeleteOnline,
1265 Snapshot *s)
1266 : SnapshotTask(m, p, s),
1267 m_fDeleteOnline(fDeleteOnline)
1268 {}
1269
1270 void handler()
1271 {
1272 pMachine->deleteSnapshotHandler(*this);
1273 }
1274
1275 bool m_fDeleteOnline;
1276};
1277
1278/**
1279 * Static SessionMachine method that can get passed to RTThreadCreate to
1280 * have a thread started for a SnapshotTask. See SnapshotTask above.
1281 *
1282 * This calls either RestoreSnapshotTask::handler() or DeleteSnapshotTask::handler().
1283 */
1284
1285/* static */ DECLCALLBACK(int) SessionMachine::taskHandler(RTTHREAD /* thread */, void *pvUser)
1286{
1287 AssertReturn(pvUser, VERR_INVALID_POINTER);
1288
1289 SnapshotTask *task = static_cast<SnapshotTask*>(pvUser);
1290 task->handler();
1291
1292 // it's our responsibility to delete the task
1293 delete task;
1294
1295 return 0;
1296}
1297
1298////////////////////////////////////////////////////////////////////////////////
1299//
1300// TakeSnapshot methods (SessionMachine and related tasks)
1301//
1302////////////////////////////////////////////////////////////////////////////////
1303
1304/**
1305 * Implementation for IInternalMachineControl::beginTakingSnapshot().
1306 *
1307 * Gets called indirectly from Console::TakeSnapshot, which creates a
1308 * progress object in the client and then starts a thread
1309 * (Console::fntTakeSnapshotWorker) which then calls this.
1310 *
1311 * In other words, the asynchronous work for taking snapshots takes place
1312 * on the _client_ (in the Console). This is different from restoring
1313 * or deleting snapshots, which start threads on the server.
1314 *
1315 * This does the server-side work of taking a snapshot: it creates diffencing
1316 * images for all hard disks attached to the machine and then creates a
1317 * Snapshot object with a corresponding SnapshotMachine to save the VM settings.
1318 *
1319 * The client's fntTakeSnapshotWorker() blocks while this takes place.
1320 * After this returns successfully, fntTakeSnapshotWorker() will begin
1321 * saving the machine state to the snapshot object and reconfigure the
1322 * hard disks.
1323 *
1324 * When the console is done, it calls SessionMachine::EndTakingSnapshot().
1325 *
1326 * @note Locks mParent + this object for writing.
1327 *
1328 * @param aInitiator in: The console on which Console::TakeSnapshot was called.
1329 * @param aName in: The name for the new snapshot.
1330 * @param aDescription in: A description for the new snapshot.
1331 * @param aConsoleProgress in: The console's (client's) progress object.
1332 * @param fTakingSnapshotOnline in: True if an online snapshot is being taken (i.e. machine is running).
1333 * @param aStateFilePath out: name of file in snapshots folder to which the console should write the VM state.
1334 * @return
1335 */
1336STDMETHODIMP SessionMachine::BeginTakingSnapshot(IConsole *aInitiator,
1337 IN_BSTR aName,
1338 IN_BSTR aDescription,
1339 IProgress *aConsoleProgress,
1340 BOOL fTakingSnapshotOnline,
1341 BSTR *aStateFilePath)
1342{
1343 LogFlowThisFuncEnter();
1344
1345 AssertReturn(aInitiator && aName, E_INVALIDARG);
1346 AssertReturn(aStateFilePath, E_POINTER);
1347
1348 LogFlowThisFunc(("aName='%ls' fTakingSnapshotOnline=%RTbool\n", aName, fTakingSnapshotOnline));
1349
1350 AutoCaller autoCaller(this);
1351 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
1352
1353 // if this becomes true, we need to call VirtualBox::saveSettings() in the end
1354 bool fNeedsSaveSettings = false;
1355
1356 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1357
1358 AssertReturn( !Global::IsOnlineOrTransient(mData->mMachineState)
1359 || mData->mMachineState == MachineState_Running
1360 || mData->mMachineState == MachineState_Paused, E_FAIL);
1361 AssertReturn(mSnapshotData.mLastState == MachineState_Null, E_FAIL);
1362 AssertReturn(mSnapshotData.mSnapshot.isNull(), E_FAIL);
1363
1364 if ( !fTakingSnapshotOnline
1365 && mData->mMachineState != MachineState_Saved
1366 )
1367 {
1368 /* save all current settings to ensure current changes are committed and
1369 * hard disks are fixed up */
1370 HRESULT rc = saveSettings(NULL);
1371 // no need to check for whether VirtualBox.xml needs changing since
1372 // we can't have a machine XML rename pending at this point
1373 if (FAILED(rc)) return rc;
1374 }
1375
1376 /* create an ID for the snapshot */
1377 Guid snapshotId;
1378 snapshotId.create();
1379
1380 Utf8Str strStateFilePath;
1381 /* stateFilePath is null when the machine is not online nor saved */
1382 if ( fTakingSnapshotOnline
1383 || mData->mMachineState == MachineState_Saved)
1384 {
1385 strStateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
1386 mUserData->mSnapshotFolderFull.raw(),
1387 RTPATH_DELIMITER,
1388 snapshotId.ptr());
1389 /* ensure the directory for the saved state file exists */
1390 HRESULT rc = VirtualBox::ensureFilePathExists(strStateFilePath);
1391 if (FAILED(rc)) return rc;
1392 }
1393
1394 /* create a snapshot machine object */
1395 ComObjPtr<SnapshotMachine> snapshotMachine;
1396 snapshotMachine.createObject();
1397 HRESULT rc = snapshotMachine->init(this, snapshotId, strStateFilePath);
1398 AssertComRCReturn(rc, rc);
1399
1400 /* create a snapshot object */
1401 RTTIMESPEC time;
1402 ComObjPtr<Snapshot> pSnapshot;
1403 pSnapshot.createObject();
1404 rc = pSnapshot->init(mParent,
1405 snapshotId,
1406 aName,
1407 aDescription,
1408 *RTTimeNow(&time),
1409 snapshotMachine,
1410 mData->mCurrentSnapshot);
1411 AssertComRCReturnRC(rc);
1412
1413 /* fill in the snapshot data */
1414 mSnapshotData.mLastState = mData->mMachineState;
1415 mSnapshotData.mSnapshot = pSnapshot;
1416
1417 try
1418 {
1419 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
1420 fTakingSnapshotOnline));
1421
1422 // backup the media data so we can recover if things goes wrong along the day;
1423 // the matching commit() is in fixupMedia() during endSnapshot()
1424 setModified(IsModified_Storage);
1425 mMediaData.backup();
1426
1427 /* Console::fntTakeSnapshotWorker and friends expects this. */
1428 if (mSnapshotData.mLastState == MachineState_Running)
1429 setMachineState(MachineState_LiveSnapshotting);
1430 else
1431 setMachineState(MachineState_Saving); /** @todo Confusing! Saving is used for both online and offline snapshots. */
1432
1433 /* create new differencing hard disks and attach them to this machine */
1434 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
1435 aConsoleProgress,
1436 1, // operation weight; must be the same as in Console::TakeSnapshot()
1437 !!fTakingSnapshotOnline,
1438 &fNeedsSaveSettings);
1439 if (FAILED(rc))
1440 throw rc;
1441
1442 if (mSnapshotData.mLastState == MachineState_Saved)
1443 {
1444 Utf8Str stateFrom = mSSData->mStateFilePath;
1445 Utf8Str stateTo = mSnapshotData.mSnapshot->stateFilePath();
1446
1447 LogFlowThisFunc(("Copying the execution state from '%s' to '%s'...\n",
1448 stateFrom.raw(), stateTo.raw()));
1449
1450 aConsoleProgress->SetNextOperation(Bstr(tr("Copying the execution state")),
1451 1); // weight
1452
1453 /* Leave the lock before a lengthy operation (machine is protected
1454 * by "Saving" machine state now) */
1455 alock.release();
1456
1457 /* copy the state file */
1458 int vrc = RTFileCopyEx(stateFrom.c_str(),
1459 stateTo.c_str(),
1460 0,
1461 progressCallback,
1462 aConsoleProgress);
1463 alock.acquire();
1464
1465 if (RT_FAILURE(vrc))
1466 /** @todo r=bird: Delete stateTo when appropriate. */
1467 throw setError(E_FAIL,
1468 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1469 stateFrom.raw(),
1470 stateTo.raw(),
1471 vrc);
1472 }
1473 }
1474 catch (HRESULT hrc)
1475 {
1476 LogThisFunc(("Caught %Rhrc [%s]\n", hrc, Global::stringifyMachineState(mData->mMachineState) ));
1477 if ( mSnapshotData.mLastState != mData->mMachineState
1478 && ( mSnapshotData.mLastState == MachineState_Running
1479 ? mData->mMachineState == MachineState_LiveSnapshotting
1480 : mData->mMachineState == MachineState_Saving)
1481 )
1482 setMachineState(mSnapshotData.mLastState);
1483
1484 pSnapshot->uninit();
1485 pSnapshot.setNull();
1486 mSnapshotData.mLastState = MachineState_Null;
1487 mSnapshotData.mSnapshot.setNull();
1488
1489 rc = hrc;
1490
1491 // @todo r=dj what with the implicit diff that we created above? this is never cleaned up
1492 }
1493
1494 if (fTakingSnapshotOnline && SUCCEEDED(rc))
1495 strStateFilePath.cloneTo(aStateFilePath);
1496 else
1497 *aStateFilePath = NULL;
1498
1499 // @todo r=dj normally we would need to save the settings if fNeedsSaveSettings was set to true,
1500 // but since we have no error handling that cleans up the diff image that might have gotten created,
1501 // there's no point in saving the disk registry at this point either... this needs fixing.
1502
1503 LogFlowThisFunc(("LEAVE - %Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
1504 return rc;
1505}
1506
1507/**
1508 * Implementation for IInternalMachineControl::endTakingSnapshot().
1509 *
1510 * Called by the Console when it's done saving the VM state into the snapshot
1511 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
1512 *
1513 * This also gets called if the console part of snapshotting failed after the
1514 * BeginTakingSnapshot() call, to clean up the server side.
1515 *
1516 * @note Locks VirtualBox and this object for writing.
1517 *
1518 * @param aSuccess Whether Console was successful with the client-side snapshot things.
1519 * @return
1520 */
1521STDMETHODIMP SessionMachine::EndTakingSnapshot(BOOL aSuccess)
1522{
1523 LogFlowThisFunc(("\n"));
1524
1525 AutoCaller autoCaller(this);
1526 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1527
1528 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
1529
1530 AssertReturn( !aSuccess
1531 || ( ( mData->mMachineState == MachineState_Saving
1532 || mData->mMachineState == MachineState_LiveSnapshotting)
1533 && mSnapshotData.mLastState != MachineState_Null
1534 && !mSnapshotData.mSnapshot.isNull()
1535 )
1536 , E_FAIL);
1537
1538 /*
1539 * Restore the state we had when BeginTakingSnapshot() was called,
1540 * Console::fntTakeSnapshotWorker restores its local copy when we return.
1541 * If the state was Running, then let Console::fntTakeSnapshotWorker do it
1542 * all to avoid races.
1543 */
1544 if ( mData->mMachineState != mSnapshotData.mLastState
1545 && mSnapshotData.mLastState != MachineState_Running
1546 )
1547 setMachineState(mSnapshotData.mLastState);
1548
1549 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
1550 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
1551
1552 bool fOnline = Global::IsOnline(mSnapshotData.mLastState);
1553
1554 HRESULT rc = S_OK;
1555
1556 if (aSuccess)
1557 {
1558 // new snapshot becomes the current one
1559 mData->mCurrentSnapshot = mSnapshotData.mSnapshot;
1560
1561 /* memorize the first snapshot if necessary */
1562 if (!mData->mFirstSnapshot)
1563 mData->mFirstSnapshot = mData->mCurrentSnapshot;
1564
1565 int flSaveSettings = SaveS_Force; // do not do a deep compare in machine settings,
1566 // snapshots change, so we know we need to save
1567 if (!fOnline)
1568 /* the machine was powered off or saved when taking a snapshot, so
1569 * reset the mCurrentStateModified flag */
1570 flSaveSettings |= SaveS_ResetCurStateModified;
1571
1572 rc = saveSettings(NULL, flSaveSettings);
1573 // no need to change for whether VirtualBox.xml needs saving since
1574 // we'll save the global settings below anyway
1575 }
1576
1577 if (aSuccess && SUCCEEDED(rc))
1578 {
1579 /* associate old hard disks with the snapshot and do locking/unlocking*/
1580 commitMedia(fOnline);
1581
1582 /* inform callbacks */
1583 mParent->onSnapshotTaken(mData->mUuid,
1584 mSnapshotData.mSnapshot->getId());
1585 }
1586 else
1587 {
1588 /* delete all differencing hard disks created (this will also attach
1589 * their parents back by rolling back mMediaData) */
1590 rollbackMedia();
1591
1592 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
1593 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
1594
1595 /* delete the saved state file (it might have been already created) */
1596 if (mSnapshotData.mSnapshot->stateFilePath().length())
1597 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
1598
1599 mSnapshotData.mSnapshot->uninit();
1600 }
1601
1602 /* clear out the snapshot data */
1603 mSnapshotData.mLastState = MachineState_Null;
1604 mSnapshotData.mSnapshot.setNull();
1605
1606 // save VirtualBox.xml (media registry most probably changed with diff image);
1607 // for that we should hold only the VirtualBox lock
1608 machineLock.release();
1609 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
1610 mParent->saveSettings();
1611
1612 return rc;
1613}
1614
1615////////////////////////////////////////////////////////////////////////////////
1616//
1617// RestoreSnapshot methods (SessionMachine and related tasks)
1618//
1619////////////////////////////////////////////////////////////////////////////////
1620
1621/**
1622 * Implementation for IInternalMachineControl::restoreSnapshot().
1623 *
1624 * Gets called from Console::RestoreSnapshot(), and that's basically the
1625 * only thing Console does. Restoring a snapshot happens entirely on the
1626 * server side since the machine cannot be running.
1627 *
1628 * This creates a new thread that does the work and returns a progress
1629 * object to the client which is then returned to the caller of
1630 * Console::RestoreSnapshot().
1631 *
1632 * Actual work then takes place in RestoreSnapshotTask::handler().
1633 *
1634 * @note Locks this + children objects for writing!
1635 *
1636 * @param aInitiator in: rhe console on which Console::RestoreSnapshot was called.
1637 * @param aSnapshot in: the snapshot to restore.
1638 * @param aMachineState in: client-side machine state.
1639 * @param aProgress out: progress object to monitor restore thread.
1640 * @return
1641 */
1642STDMETHODIMP SessionMachine::RestoreSnapshot(IConsole *aInitiator,
1643 ISnapshot *aSnapshot,
1644 MachineState_T *aMachineState,
1645 IProgress **aProgress)
1646{
1647 LogFlowThisFuncEnter();
1648
1649 AssertReturn(aInitiator, E_INVALIDARG);
1650 AssertReturn(aSnapshot && aMachineState && aProgress, E_POINTER);
1651
1652 AutoCaller autoCaller(this);
1653 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
1654
1655 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1656
1657 // machine must not be running
1658 ComAssertRet(!Global::IsOnlineOrTransient(mData->mMachineState),
1659 E_FAIL);
1660
1661 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(aSnapshot));
1662 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
1663
1664 // create a progress object. The number of operations is:
1665 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
1666 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
1667
1668 ULONG ulOpCount = 1; // one for preparations
1669 ULONG ulTotalWeight = 1; // one for preparations
1670 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
1671 it != pSnapMachine->mMediaData->mAttachments.end();
1672 ++it)
1673 {
1674 ComObjPtr<MediumAttachment> &pAttach = *it;
1675 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
1676 if (pAttach->getType() == DeviceType_HardDisk)
1677 {
1678 ++ulOpCount;
1679 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
1680 Assert(pAttach->getMedium());
1681 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pAttach->getMedium()->getName().c_str()));
1682 }
1683 }
1684
1685 ULONG ulStateFileSizeMB = 0;
1686 if (pSnapshot->stateFilePath().length())
1687 {
1688 ++ulOpCount; // one for the saved state
1689
1690 uint64_t ullSize;
1691 int irc = RTFileQuerySize(pSnapshot->stateFilePath().c_str(), &ullSize);
1692 if (!RT_SUCCESS(irc))
1693 // if we can't access the file here, then we'll be doomed later also, so fail right away
1694 setError(E_FAIL, tr("Cannot access state file '%s', runtime error, %Rra"), pSnapshot->stateFilePath().c_str(), irc);
1695 if (ullSize == 0) // avoid division by zero
1696 ullSize = _1M;
1697
1698 ulStateFileSizeMB = (ULONG)(ullSize / _1M);
1699 LogFlowThisFunc(("op %d: saved state file '%s' has %RI64 bytes (%d MB)\n",
1700 ulOpCount, pSnapshot->stateFilePath().raw(), ullSize, ulStateFileSizeMB));
1701
1702 ulTotalWeight += ulStateFileSizeMB;
1703 }
1704
1705 ComObjPtr<Progress> pProgress;
1706 pProgress.createObject();
1707 pProgress->init(mParent, aInitiator,
1708 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->getName().c_str()),
1709 FALSE /* aCancelable */,
1710 ulOpCount,
1711 ulTotalWeight,
1712 Bstr(tr("Restoring machine settings")),
1713 1);
1714
1715 /* create and start the task on a separate thread (note that it will not
1716 * start working until we release alock) */
1717 RestoreSnapshotTask *task = new RestoreSnapshotTask(this,
1718 pProgress,
1719 pSnapshot,
1720 ulStateFileSizeMB);
1721 int vrc = RTThreadCreate(NULL,
1722 taskHandler,
1723 (void*)task,
1724 0,
1725 RTTHREADTYPE_MAIN_WORKER,
1726 0,
1727 "RestoreSnap");
1728 if (RT_FAILURE(vrc))
1729 {
1730 delete task;
1731 ComAssertRCRet(vrc, E_FAIL);
1732 }
1733
1734 /* set the proper machine state (note: after creating a Task instance) */
1735 setMachineState(MachineState_RestoringSnapshot);
1736
1737 /* return the progress to the caller */
1738 pProgress.queryInterfaceTo(aProgress);
1739
1740 /* return the new state to the caller */
1741 *aMachineState = mData->mMachineState;
1742
1743 LogFlowThisFuncLeave();
1744
1745 return S_OK;
1746}
1747
1748/**
1749 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
1750 * This method gets called indirectly through SessionMachine::taskHandler() which then
1751 * calls RestoreSnapshotTask::handler().
1752 *
1753 * The RestoreSnapshotTask contains the progress object returned to the console by
1754 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
1755 *
1756 * @note Locks mParent + this object for writing.
1757 *
1758 * @param aTask Task data.
1759 */
1760void SessionMachine::restoreSnapshotHandler(RestoreSnapshotTask &aTask)
1761{
1762 LogFlowThisFuncEnter();
1763
1764 AutoCaller autoCaller(this);
1765
1766 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
1767 if (!autoCaller.isOk())
1768 {
1769 /* we might have been uninitialized because the session was accidentally
1770 * closed by the client, so don't assert */
1771 aTask.pProgress->notifyComplete(E_FAIL,
1772 COM_IIDOF(IMachine),
1773 getComponentName(),
1774 tr("The session has been accidentally closed"));
1775
1776 LogFlowThisFuncLeave();
1777 return;
1778 }
1779
1780 HRESULT rc = S_OK;
1781
1782 bool stateRestored = false;
1783 bool fNeedsGlobalSaveSettings = false;
1784
1785 try
1786 {
1787 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1788
1789 /* Discard all current changes to mUserData (name, OSType etc.).
1790 * Note that the machine is powered off, so there is no need to inform
1791 * the direct session. */
1792 if (mData->flModifications)
1793 rollback(false /* aNotify */);
1794
1795 /* Delete the saved state file if the machine was Saved prior to this
1796 * operation */
1797 if (aTask.machineStateBackup == MachineState_Saved)
1798 {
1799 Assert(!mSSData->mStateFilePath.isEmpty());
1800 RTFileDelete(mSSData->mStateFilePath.c_str());
1801 mSSData->mStateFilePath.setNull();
1802 aTask.modifyBackedUpState(MachineState_PoweredOff);
1803 rc = saveStateSettings(SaveSTS_StateFilePath);
1804 if (FAILED(rc))
1805 throw rc;
1806 }
1807
1808 RTTIMESPEC snapshotTimeStamp;
1809 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
1810
1811 {
1812 AutoReadLock snapshotLock(aTask.pSnapshot COMMA_LOCKVAL_SRC_POS);
1813
1814 /* remember the timestamp of the snapshot we're restoring from */
1815 snapshotTimeStamp = aTask.pSnapshot->getTimeStamp();
1816
1817 ComPtr<SnapshotMachine> pSnapshotMachine(aTask.pSnapshot->getSnapshotMachine());
1818
1819 /* copy all hardware data from the snapshot */
1820 copyFrom(pSnapshotMachine);
1821
1822 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
1823
1824 // restore the attachments from the snapshot
1825 setModified(IsModified_Storage);
1826 mMediaData.backup();
1827 mMediaData->mAttachments = pSnapshotMachine->mMediaData->mAttachments;
1828
1829 /* leave the locks before the potentially lengthy operation */
1830 snapshotLock.release();
1831 alock.leave();
1832
1833 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
1834 aTask.pProgress,
1835 1,
1836 false /* aOnline */,
1837 &fNeedsGlobalSaveSettings);
1838 if (FAILED(rc))
1839 throw rc;
1840
1841 alock.enter();
1842 snapshotLock.acquire();
1843
1844 /* Note: on success, current (old) hard disks will be
1845 * deassociated/deleted on #commit() called from #saveSettings() at
1846 * the end. On failure, newly created implicit diffs will be
1847 * deleted by #rollback() at the end. */
1848
1849 /* should not have a saved state file associated at this point */
1850 Assert(mSSData->mStateFilePath.isEmpty());
1851
1852 if (!aTask.pSnapshot->stateFilePath().isEmpty())
1853 {
1854 Utf8Str snapStateFilePath = aTask.pSnapshot->stateFilePath();
1855
1856 Utf8Str stateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
1857 mUserData->mSnapshotFolderFull.raw(),
1858 RTPATH_DELIMITER,
1859 mData->mUuid.raw());
1860
1861 LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
1862 snapStateFilePath.raw(), stateFilePath.raw()));
1863
1864 aTask.pProgress->SetNextOperation(Bstr(tr("Restoring the execution state")),
1865 aTask.m_ulStateFileSizeMB); // weight
1866
1867 /* leave the lock before the potentially lengthy operation */
1868 snapshotLock.release();
1869 alock.leave();
1870
1871 /* copy the state file */
1872 RTFileDelete(stateFilePath.c_str());
1873 int vrc = RTFileCopyEx(snapStateFilePath.c_str(),
1874 stateFilePath.c_str(),
1875 0,
1876 progressCallback,
1877 static_cast<IProgress*>(aTask.pProgress));
1878
1879 alock.enter();
1880 snapshotLock.acquire();
1881
1882 if (RT_SUCCESS(vrc))
1883 mSSData->mStateFilePath = stateFilePath;
1884 else
1885 throw setError(E_FAIL,
1886 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1887 snapStateFilePath.raw(),
1888 stateFilePath.raw(),
1889 vrc);
1890 }
1891
1892 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", aTask.pSnapshot->getId().raw()));
1893 /* make the snapshot we restored from the current snapshot */
1894 mData->mCurrentSnapshot = aTask.pSnapshot;
1895 }
1896
1897 /* grab differencing hard disks from the old attachments that will
1898 * become unused and need to be auto-deleted */
1899 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
1900
1901 for (MediaData::AttachmentList::const_iterator it = mMediaData.backedUpData()->mAttachments.begin();
1902 it != mMediaData.backedUpData()->mAttachments.end();
1903 ++it)
1904 {
1905 ComObjPtr<MediumAttachment> pAttach = *it;
1906 ComObjPtr<Medium> pMedium = pAttach->getMedium();
1907
1908 /* while the hard disk is attached, the number of children or the
1909 * parent cannot change, so no lock */
1910 if ( !pMedium.isNull()
1911 && pAttach->getType() == DeviceType_HardDisk
1912 && !pMedium->getParent().isNull()
1913 && pMedium->getChildren().size() == 0
1914 )
1915 {
1916 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->getName().raw()));
1917
1918 llDiffAttachmentsToDelete.push_back(pAttach);
1919 }
1920 }
1921
1922 int saveFlags = 0;
1923
1924 /* we have already deleted the current state, so set the execution
1925 * state accordingly no matter of the delete snapshot result */
1926 if (!mSSData->mStateFilePath.isEmpty())
1927 setMachineState(MachineState_Saved);
1928 else
1929 setMachineState(MachineState_PoweredOff);
1930
1931 updateMachineStateOnClient();
1932 stateRestored = true;
1933
1934 /* assign the timestamp from the snapshot */
1935 Assert(RTTimeSpecGetMilli (&snapshotTimeStamp) != 0);
1936 mData->mLastStateChange = snapshotTimeStamp;
1937
1938 // detach the current-state diffs that we detected above and build a list of
1939 // image files to delete _after_ saveSettings()
1940
1941 MediaList llDiffsToDelete;
1942
1943 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
1944 it != llDiffAttachmentsToDelete.end();
1945 ++it)
1946 {
1947 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
1948 ComObjPtr<Medium> pMedium = pAttach->getMedium();
1949
1950 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
1951
1952 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->getName().raw()));
1953
1954 // Normally we "detach" the medium by removing the attachment object
1955 // from the current machine data; saveSettings() below would then
1956 // compare the current machine data with the one in the backup
1957 // and actually call Medium::removeBackReference(). But that works only half
1958 // the time in our case so instead we force a detachment here:
1959 // remove from machine data
1960 mMediaData->mAttachments.remove(pAttach);
1961 // remove it from the backup or else saveSettings will try to detach
1962 // it again and assert
1963 mMediaData.backedUpData()->mAttachments.remove(pAttach);
1964 // then clean up backrefs
1965 pMedium->removeBackReference(mData->mUuid);
1966
1967 llDiffsToDelete.push_back(pMedium);
1968 }
1969
1970 // save machine settings, reset the modified flag and commit;
1971 rc = saveSettings(&fNeedsGlobalSaveSettings,
1972 SaveS_ResetCurStateModified | saveFlags);
1973 if (FAILED(rc))
1974 throw rc;
1975
1976 // let go of the locks while we're deleting image files below
1977 alock.leave();
1978 // from here on we cannot roll back on failure any more
1979
1980 for (MediaList::iterator it = llDiffsToDelete.begin();
1981 it != llDiffsToDelete.end();
1982 ++it)
1983 {
1984 ComObjPtr<Medium> &pMedium = *it;
1985 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->getName().raw()));
1986
1987 HRESULT rc2 = pMedium->deleteStorage(NULL /* aProgress */,
1988 true /* aWait */,
1989 &fNeedsGlobalSaveSettings);
1990 // ignore errors here because we cannot roll back after saveSettings() above
1991 if (SUCCEEDED(rc2))
1992 pMedium->uninit();
1993 }
1994 }
1995 catch (HRESULT aRC)
1996 {
1997 rc = aRC;
1998 }
1999
2000 if (FAILED(rc))
2001 {
2002 /* preserve existing error info */
2003 ErrorInfoKeeper eik;
2004
2005 /* undo all changes on failure */
2006 rollback(false /* aNotify */);
2007
2008 if (!stateRestored)
2009 {
2010 /* restore the machine state */
2011 setMachineState(aTask.machineStateBackup);
2012 updateMachineStateOnClient();
2013 }
2014 }
2015
2016 if (fNeedsGlobalSaveSettings)
2017 {
2018 // finally, VirtualBox.xml needs saving too
2019 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
2020 mParent->saveSettings();
2021 }
2022
2023 /* set the result (this will try to fetch current error info on failure) */
2024 aTask.pProgress->notifyComplete(rc);
2025
2026 if (SUCCEEDED(rc))
2027 mParent->onSnapshotDeleted(mData->mUuid, Guid());
2028
2029 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
2030
2031 LogFlowThisFuncLeave();
2032}
2033
2034////////////////////////////////////////////////////////////////////////////////
2035//
2036// DeleteSnapshot methods (SessionMachine and related tasks)
2037//
2038////////////////////////////////////////////////////////////////////////////////
2039
2040/**
2041 * Implementation for IInternalMachineControl::deleteSnapshot().
2042 *
2043 * Gets called from Console::DeleteSnapshot(), and that's basically the
2044 * only thing Console does initially. Deleting a snapshot happens entirely on
2045 * the server side if the machine is not running, and if it is running then
2046 * the individual merges are done via internal session callbacks.
2047 *
2048 * This creates a new thread that does the work and returns a progress
2049 * object to the client which is then returned to the caller of
2050 * Console::DeleteSnapshot().
2051 *
2052 * Actual work then takes place in DeleteSnapshotTask::handler().
2053 *
2054 * @note Locks mParent + this + children objects for writing!
2055 */
2056STDMETHODIMP SessionMachine::DeleteSnapshot(IConsole *aInitiator,
2057 IN_BSTR aId,
2058 MachineState_T *aMachineState,
2059 IProgress **aProgress)
2060{
2061 LogFlowThisFuncEnter();
2062
2063 Guid id(aId);
2064 AssertReturn(aInitiator && !id.isEmpty(), E_INVALIDARG);
2065 AssertReturn(aMachineState && aProgress, E_POINTER);
2066
2067 AutoCaller autoCaller(this);
2068 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
2069
2070 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2071
2072 // be very picky about machine states
2073 if ( Global::IsOnlineOrTransient(mData->mMachineState)
2074 && mData->mMachineState != MachineState_PoweredOff
2075 && mData->mMachineState != MachineState_Saved
2076 && mData->mMachineState != MachineState_Teleported
2077 && mData->mMachineState != MachineState_Aborted
2078 && mData->mMachineState != MachineState_Running
2079 && mData->mMachineState != MachineState_Paused)
2080 return setError(VBOX_E_INVALID_VM_STATE,
2081 tr("Invalid machine state: %s"),
2082 Global::stringifyMachineState(mData->mMachineState));
2083
2084 ComObjPtr<Snapshot> pSnapshot;
2085 HRESULT rc = findSnapshot(id, pSnapshot, true /* aSetError */);
2086 if (FAILED(rc)) return rc;
2087
2088 AutoWriteLock snapshotLock(pSnapshot COMMA_LOCKVAL_SRC_POS);
2089
2090 size_t childrenCount = pSnapshot->getChildrenCount();
2091 if (childrenCount > 1)
2092 return setError(VBOX_E_INVALID_OBJECT_STATE,
2093 tr("Snapshot '%s' of the machine '%ls' cannot be deleted. because it has %d child snapshots, which is more than the one snapshot allowed for deletion"),
2094 pSnapshot->getName().c_str(),
2095 mUserData->mName.raw(),
2096 childrenCount);
2097
2098 /* If the snapshot being deleted is the current one, ensure current
2099 * settings are committed and saved.
2100 */
2101 if (pSnapshot == mData->mCurrentSnapshot)
2102 {
2103 if (mData->flModifications)
2104 {
2105 rc = saveSettings(NULL);
2106 // no need to change for whether VirtualBox.xml needs saving since
2107 // we can't have a machine XML rename pending at this point
2108 if (FAILED(rc)) return rc;
2109 }
2110 }
2111
2112 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
2113
2114 /* create a progress object. The number of operations is:
2115 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
2116 */
2117 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2118
2119 ULONG ulOpCount = 1; // one for preparations
2120 ULONG ulTotalWeight = 1; // one for preparations
2121
2122 if (pSnapshot->stateFilePath().length())
2123 {
2124 ++ulOpCount;
2125 ++ulTotalWeight; // assume 1 MB for deleting the state file
2126 }
2127
2128 // count normal hard disks and add their sizes to the weight
2129 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2130 it != pSnapMachine->mMediaData->mAttachments.end();
2131 ++it)
2132 {
2133 ComObjPtr<MediumAttachment> &pAttach = *it;
2134 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2135 if (pAttach->getType() == DeviceType_HardDisk)
2136 {
2137 ComObjPtr<Medium> pHD = pAttach->getMedium();
2138 Assert(pHD);
2139 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2140
2141 MediumType_T type = pHD->getType();
2142 // writethrough and shareable images are unaffected by snapshots,
2143 // so do nothing for them
2144 if ( type != MediumType_Writethrough
2145 && type != MediumType_Shareable)
2146 {
2147 // normal or immutable media need attention
2148 ++ulOpCount;
2149 ulTotalWeight += (ULONG)(pHD->getSize() / _1M);
2150 }
2151 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->getName().c_str()));
2152 }
2153 }
2154
2155 ComObjPtr<Progress> pProgress;
2156 pProgress.createObject();
2157 pProgress->init(mParent, aInitiator,
2158 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->getName().c_str()),
2159 FALSE /* aCancelable */,
2160 ulOpCount,
2161 ulTotalWeight,
2162 Bstr(tr("Setting up")),
2163 1);
2164
2165 bool fDeleteOnline = ( (mData->mMachineState == MachineState_Running)
2166 || (mData->mMachineState == MachineState_Paused));
2167
2168 /* create and start the task on a separate thread */
2169 DeleteSnapshotTask *task = new DeleteSnapshotTask(this, pProgress,
2170 fDeleteOnline, pSnapshot);
2171 int vrc = RTThreadCreate(NULL,
2172 taskHandler,
2173 (void*)task,
2174 0,
2175 RTTHREADTYPE_MAIN_WORKER,
2176 0,
2177 "DeleteSnapshot");
2178 if (RT_FAILURE(vrc))
2179 {
2180 delete task;
2181 return E_FAIL;
2182 }
2183
2184 // the task might start running but will block on acquiring the machine's write lock
2185 // which we acquired above; once this function leaves, the task will be unblocked;
2186 // set the proper machine state here now (note: after creating a Task instance)
2187 if (mData->mMachineState == MachineState_Running)
2188 setMachineState(MachineState_DeletingSnapshotOnline);
2189 else if (mData->mMachineState == MachineState_Paused)
2190 setMachineState(MachineState_DeletingSnapshotPaused);
2191 else
2192 setMachineState(MachineState_DeletingSnapshot);
2193
2194 /* return the progress to the caller */
2195 pProgress.queryInterfaceTo(aProgress);
2196
2197 /* return the new state to the caller */
2198 *aMachineState = mData->mMachineState;
2199
2200 LogFlowThisFuncLeave();
2201
2202 return S_OK;
2203}
2204
2205/**
2206 * Helper struct for SessionMachine::deleteSnapshotHandler().
2207 */
2208struct MediumDeleteRec
2209{
2210 MediumDeleteRec()
2211 : mfNeedsOnlineMerge(false),
2212 mpMediumLockList(NULL)
2213 {}
2214
2215 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2216 const ComObjPtr<Medium> &aSource,
2217 const ComObjPtr<Medium> &aTarget,
2218 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2219 bool fMergeForward,
2220 const ComObjPtr<Medium> &aParentForTarget,
2221 const MediaList &aChildrenToReparent,
2222 bool fNeedsOnlineMerge,
2223 MediumLockList *aMediumLockList)
2224 : mpHD(aHd),
2225 mpSource(aSource),
2226 mpTarget(aTarget),
2227 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2228 mfMergeForward(fMergeForward),
2229 mpParentForTarget(aParentForTarget),
2230 mChildrenToReparent(aChildrenToReparent),
2231 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2232 mpMediumLockList(aMediumLockList)
2233 {}
2234
2235 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2236 const ComObjPtr<Medium> &aSource,
2237 const ComObjPtr<Medium> &aTarget,
2238 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2239 bool fMergeForward,
2240 const ComObjPtr<Medium> &aParentForTarget,
2241 const MediaList &aChildrenToReparent,
2242 bool fNeedsOnlineMerge,
2243 MediumLockList *aMediumLockList,
2244 const Guid &aMachineId,
2245 const Guid &aSnapshotId)
2246 : mpHD(aHd),
2247 mpSource(aSource),
2248 mpTarget(aTarget),
2249 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2250 mfMergeForward(fMergeForward),
2251 mpParentForTarget(aParentForTarget),
2252 mChildrenToReparent(aChildrenToReparent),
2253 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2254 mpMediumLockList(aMediumLockList),
2255 mMachineId(aMachineId),
2256 mSnapshotId(aSnapshotId)
2257 {}
2258
2259 ComObjPtr<Medium> mpHD;
2260 ComObjPtr<Medium> mpSource;
2261 ComObjPtr<Medium> mpTarget;
2262 ComObjPtr<MediumAttachment> mpOnlineMediumAttachment;
2263 bool mfMergeForward;
2264 ComObjPtr<Medium> mpParentForTarget;
2265 MediaList mChildrenToReparent;
2266 bool mfNeedsOnlineMerge;
2267 MediumLockList *mpMediumLockList;
2268 /* these are for reattaching the hard disk in case of a failure: */
2269 Guid mMachineId;
2270 Guid mSnapshotId;
2271};
2272
2273typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2274
2275/**
2276 * Worker method for the delete snapshot thread created by
2277 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2278 * through SessionMachine::taskHandler() which then calls
2279 * DeleteSnapshotTask::handler().
2280 *
2281 * The DeleteSnapshotTask contains the progress object returned to the console
2282 * by SessionMachine::DeleteSnapshot, through which progress and results are
2283 * reported.
2284 *
2285 * SessionMachine::DeleteSnapshot() has set the machine state to
2286 * MachineState_DeletingSnapshot right after creating this task. Since we block
2287 * on the machine write lock at the beginning, once that has been acquired, we
2288 * can assume that the machine state is indeed that.
2289 *
2290 * @note Locks the machine + the snapshot + the media tree for writing!
2291 *
2292 * @param aTask Task data.
2293 */
2294
2295void SessionMachine::deleteSnapshotHandler(DeleteSnapshotTask &aTask)
2296{
2297 LogFlowThisFuncEnter();
2298
2299 AutoCaller autoCaller(this);
2300
2301 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
2302 if (!autoCaller.isOk())
2303 {
2304 /* we might have been uninitialized because the session was accidentally
2305 * closed by the client, so don't assert */
2306 aTask.pProgress->notifyComplete(E_FAIL,
2307 COM_IIDOF(IMachine),
2308 getComponentName(),
2309 tr("The session has been accidentally closed"));
2310 LogFlowThisFuncLeave();
2311 return;
2312 }
2313
2314 MediumDeleteRecList toDelete;
2315
2316 HRESULT rc = S_OK;
2317
2318 bool fMachineSettingsChanged = false; // Machine
2319 bool fNeedsSaveSettings = false; // VirtualBox.xml
2320
2321 Guid snapshotId;
2322
2323 try
2324 {
2325 /* Locking order: */
2326 AutoMultiWriteLock3 multiLock(this->lockHandle(), // machine
2327 aTask.pSnapshot->lockHandle(), // snapshot
2328 &mParent->getMediaTreeLockHandle() // media tree
2329 COMMA_LOCKVAL_SRC_POS);
2330 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2331 // has exited after setting the machine state to MachineState_DeletingSnapshot
2332
2333 ComObjPtr<SnapshotMachine> pSnapMachine = aTask.pSnapshot->getSnapshotMachine();
2334 // no need to lock the snapshot machine since it is const by definiton
2335 Guid machineId = pSnapMachine->getId();
2336
2337 // save the snapshot ID (for callbacks)
2338 snapshotId = aTask.pSnapshot->getId();
2339
2340 // first pass:
2341 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2342
2343 // Go thru the attachments of the snapshot machine (the media in here
2344 // point to the disk states _before_ the snapshot was taken, i.e. the
2345 // state we're restoring to; for each such medium, we will need to
2346 // merge it with its one and only child (the diff image holding the
2347 // changes written after the snapshot was taken).
2348 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2349 it != pSnapMachine->mMediaData->mAttachments.end();
2350 ++it)
2351 {
2352 ComObjPtr<MediumAttachment> &pAttach = *it;
2353 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2354 if (pAttach->getType() != DeviceType_HardDisk)
2355 continue;
2356
2357 ComObjPtr<Medium> pHD = pAttach->getMedium();
2358 Assert(!pHD.isNull());
2359
2360 {
2361 // writethrough and shareable images are unaffected by
2362 // snapshots, skip them
2363 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
2364 MediumType_T type = pHD->getType();
2365 if ( type == MediumType_Writethrough
2366 || type == MediumType_Shareable)
2367 continue;
2368 }
2369
2370#ifdef DEBUG
2371 pHD->dumpBackRefs();
2372#endif
2373
2374 // needs to be merged with child or deleted, check prerequisites
2375 ComObjPtr<Medium> pTarget;
2376 ComObjPtr<Medium> pSource;
2377 bool fMergeForward = false;
2378 ComObjPtr<Medium> pParentForTarget;
2379 MediaList childrenToReparent;
2380 bool fNeedsOnlineMerge = false;
2381 bool fOnlineMergePossible = aTask.m_fDeleteOnline;
2382 MediumLockList *pMediumLockList = NULL;
2383 MediumLockList *pVMMALockList = NULL;
2384 ComObjPtr<MediumAttachment> pOnlineMediumAttachment;
2385 if (fOnlineMergePossible)
2386 {
2387 // Look up the corresponding medium attachment in the currently
2388 // running VM. Any failure prevents a live merge. Could be made
2389 // a tad smarter by trying a few candidates, so that e.g. disks
2390 // which are simply moved to a different controller slot do not
2391 // prevent online merging in general.
2392 pOnlineMediumAttachment =
2393 findAttachment(mMediaData->mAttachments,
2394 pAttach->getControllerName(),
2395 pAttach->getPort(),
2396 pAttach->getDevice());
2397 if (pOnlineMediumAttachment)
2398 {
2399 rc = mData->mSession.mLockedMedia.Get(pOnlineMediumAttachment,
2400 pVMMALockList);
2401 if (FAILED(rc))
2402 fOnlineMergePossible = false;
2403 }
2404 else
2405 fOnlineMergePossible = false;
2406 }
2407 rc = prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
2408 fOnlineMergePossible,
2409 pVMMALockList, pSource, pTarget,
2410 fMergeForward, pParentForTarget,
2411 childrenToReparent,
2412 fNeedsOnlineMerge,
2413 pMediumLockList);
2414 if (FAILED(rc))
2415 throw rc;
2416
2417 // no need to hold the lock any longer
2418 attachLock.release();
2419
2420 // For simplicity, prepareDeleteSnapshotMedium selects the merge
2421 // direction in the following way: we merge pHD onto its child
2422 // (forward merge), not the other way round, because that saves us
2423 // from unnecessarily shuffling around the attachments for the
2424 // machine that follows the snapshot (next snapshot or current
2425 // state), unless it's a base image. Backwards merges of the first
2426 // snapshot into the base image is essential, as it ensures that
2427 // when all snapshots are deleted the only remaining image is a
2428 // base image. Important e.g. for medium formats which do not have
2429 // a file representation such as iSCSI.
2430
2431 // a couple paranoia checks for backward merges
2432 if (pMediumLockList != NULL && !fMergeForward)
2433 {
2434 // parent is null -> this disk is a base hard disk: we will
2435 // then do a backward merge, i.e. merge its only child onto the
2436 // base disk. Here we need then to update the attachment that
2437 // refers to the child and have it point to the parent instead
2438 Assert(pHD->getParent().isNull());
2439 Assert(pHD->getChildren().size() == 1);
2440
2441 ComObjPtr<Medium> pReplaceHD = pHD->getChildren().front();
2442
2443 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
2444 }
2445
2446 Guid replaceMachineId;
2447 Guid replaceSnapshotId;
2448
2449 const Guid *pReplaceMachineId = pSource->getFirstMachineBackrefId();
2450 // minimal sanity checking
2451 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
2452 if (pReplaceMachineId)
2453 replaceMachineId = *pReplaceMachineId;
2454
2455 const Guid *pSnapshotId = pSource->getFirstMachineBackrefSnapshotId();
2456 if (pSnapshotId)
2457 replaceSnapshotId = *pSnapshotId;
2458
2459 if (!replaceMachineId.isEmpty())
2460 {
2461 // Adjust the backreferences, otherwise merging will assert.
2462 // Note that the medium attachment object stays associated
2463 // with the snapshot until the merge was successful.
2464 HRESULT rc2 = S_OK;
2465 rc2 = pSource->removeBackReference(replaceMachineId, replaceSnapshotId);
2466 AssertComRC(rc2);
2467
2468 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2469 pOnlineMediumAttachment,
2470 fMergeForward,
2471 pParentForTarget,
2472 childrenToReparent,
2473 fNeedsOnlineMerge,
2474 pMediumLockList,
2475 replaceMachineId,
2476 replaceSnapshotId));
2477 }
2478 else
2479 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2480 pOnlineMediumAttachment,
2481 fMergeForward,
2482 pParentForTarget,
2483 childrenToReparent,
2484 fNeedsOnlineMerge,
2485 pMediumLockList));
2486 }
2487
2488 // we can release the lock now since the machine state is MachineState_DeletingSnapshot
2489 multiLock.release();
2490
2491 /* Now we checked that we can successfully merge all normal hard disks
2492 * (unless a runtime error like end-of-disc happens). Now get rid of
2493 * the saved state (if present), as that will free some disk space.
2494 * The snapshot itself will be deleted as late as possible, so that
2495 * the user can repeat the delete operation if he runs out of disk
2496 * space or cancels the delete operation. */
2497
2498 /* second pass: */
2499 LogFlowThisFunc(("2: Deleting saved state...\n"));
2500
2501 {
2502 // saveAllSnapshots() needs a machine lock, and the snapshots
2503 // tree is protected by the machine lock as well
2504 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2505
2506 Utf8Str stateFilePath = aTask.pSnapshot->stateFilePath();
2507 if (!stateFilePath.isEmpty())
2508 {
2509 aTask.pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")),
2510 1); // weight
2511
2512 aTask.pSnapshot->deleteStateFile();
2513 fMachineSettingsChanged = true;
2514 }
2515 }
2516
2517 /* third pass: */
2518 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
2519
2520 /// @todo NEWMEDIA turn the following errors into warnings because the
2521 /// snapshot itself has been already deleted (and interpret these
2522 /// warnings properly on the GUI side)
2523 for (MediumDeleteRecList::iterator it = toDelete.begin();
2524 it != toDelete.end();)
2525 {
2526 const ComObjPtr<Medium> &pMedium(it->mpHD);
2527 ULONG ulWeight;
2528
2529 {
2530 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
2531 ulWeight = (ULONG)(pMedium->getSize() / _1M);
2532 }
2533
2534 aTask.pProgress->SetNextOperation(BstrFmt(tr("Merging differencing image '%s'"),
2535 pMedium->getName().raw()),
2536 ulWeight);
2537
2538 bool fNeedSourceUninit = false;
2539 bool fReparentTarget = false;
2540 if (it->mpMediumLockList == NULL)
2541 {
2542 /* no real merge needed, just updating state and delete
2543 * diff files if necessary */
2544 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
2545
2546 Assert( !it->mfMergeForward
2547 || pMedium->getChildren().size() == 0);
2548
2549 /* Delete the differencing hard disk (has no children). Two
2550 * exceptions: if it's the last medium in the chain or if it's
2551 * a backward merge we don't want to handle due to complextity.
2552 * In both cases leave the image in place. If it's the first
2553 * exception the user can delete it later if he wants. */
2554 if (!pMedium->getParent().isNull())
2555 {
2556 Assert(pMedium->getState() == MediumState_Deleting);
2557 /* No need to hold the lock any longer. */
2558 mLock.release();
2559 bool fNeedsSave = false;
2560 rc = pMedium->deleteStorage(&aTask.pProgress,
2561 true /* aWait */,
2562 &fNeedsSave);
2563 fNeedsSaveSettings |= fNeedsSave;
2564 if (FAILED(rc))
2565 throw rc;
2566
2567 // need to uninit the deleted medium
2568 fNeedSourceUninit = true;
2569 }
2570 }
2571 else
2572 {
2573 bool fNeedsSave = false;
2574 if (it->mfNeedsOnlineMerge)
2575 {
2576/// @todo VBoxHDD cannot handle backward merges where source==active disk yet
2577 if (!it->mfMergeForward && it->mChildrenToReparent.size() == 0)
2578 throw setError(E_NOTIMPL,
2579 tr("Snapshot '%s' of the machine '%ls' cannot be deleted while a VM is running, as this case is not implemented yet. You can delete the snapshot when the VM is powered off"),
2580 aTask.pSnapshot->getName().c_str(),
2581 mUserData->mName.raw());
2582
2583 // online medium merge, in the direction decided earlier
2584 rc = onlineMergeMedium(it->mpOnlineMediumAttachment,
2585 it->mpSource,
2586 it->mpTarget,
2587 it->mfMergeForward,
2588 it->mpParentForTarget,
2589 it->mChildrenToReparent,
2590 it->mpMediumLockList,
2591 aTask.pProgress,
2592 &fNeedsSave);
2593 }
2594 else
2595 {
2596 // normal medium merge, in the direction decided earlier
2597 rc = it->mpSource->mergeTo(it->mpTarget,
2598 it->mfMergeForward,
2599 it->mpParentForTarget,
2600 it->mChildrenToReparent,
2601 it->mpMediumLockList,
2602 &aTask.pProgress,
2603 true /* aWait */,
2604 &fNeedsSave);
2605 }
2606 fNeedsSaveSettings |= fNeedsSave;
2607
2608 // If the merge failed, we need to do our best to have a usable
2609 // VM configuration afterwards. The return code doesn't tell
2610 // whether the merge completed and so we have to check if the
2611 // source medium (diff images are always file based at the
2612 // moment) is still there or not. Be careful not to lose the
2613 // error code below, before the "Delayed failure exit".
2614 if (FAILED(rc))
2615 {
2616 AutoReadLock mlock(it->mpSource COMMA_LOCKVAL_SRC_POS);
2617 const ComObjPtr<MediumFormat> &sourceFormat = it->mpSource->getMediumFormat();
2618 // No medium format description? get out of here.
2619 if (sourceFormat.isNull())
2620 throw rc;
2621 // Diff medium not backed by a file - cannot get status so
2622 // be pessimistic.
2623 if (!(sourceFormat->capabilities() & MediumFormatCapabilities_File))
2624 throw rc;
2625 const Utf8Str &loc = it->mpSource->getLocationFull();
2626 // Source medium is still there, so merge failed early.
2627 if (RTFileExists(loc.raw()))
2628 throw rc;
2629
2630 // Source medium is gone. Assume the merge succeeded and
2631 // thus it's safe to remove the attachment. We use the
2632 // "Delayed failure exit" below.
2633 }
2634
2635 // need to change the medium attachment for backward merges
2636 fReparentTarget = !it->mfMergeForward;
2637
2638 if (!it->mfNeedsOnlineMerge)
2639 {
2640 // need to uninit the medium deleted by the merge
2641 fNeedSourceUninit = true;
2642
2643 // delete the no longer needed medium lock list, which
2644 // implicitly handled the unlocking
2645 delete it->mpMediumLockList;
2646 it->mpMediumLockList = NULL;
2647 }
2648 }
2649
2650 // Now that the medium is successfully merged/deleted/whatever,
2651 // remove the medium attachment from the snapshot. For a backwards
2652 // merge the target attachment needs to be removed from the
2653 // snapshot, as the VM will take it over. For forward merges the
2654 // source medium attachment needs to be removed.
2655 ComObjPtr<MediumAttachment> pAtt;
2656 if (fReparentTarget)
2657 {
2658 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2659 it->mpTarget);
2660 it->mpTarget->removeBackReference(machineId, snapshotId);
2661 }
2662 else
2663 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2664 it->mpSource);
2665 pSnapMachine->mMediaData->mAttachments.remove(pAtt);
2666
2667 if (fReparentTarget)
2668 {
2669 // Search for old source attachment and replace with target.
2670 // There can be only one child snapshot in this case.
2671 ComObjPtr<Machine> pMachine = this;
2672 Guid childSnapshotId;
2673 ComObjPtr<Snapshot> pChildSnapshot = aTask.pSnapshot->getFirstChild();
2674 if (pChildSnapshot)
2675 {
2676 pMachine = pChildSnapshot->getSnapshotMachine();
2677 childSnapshotId = pChildSnapshot->getId();
2678 }
2679 pAtt = findAttachment(pMachine->mMediaData->mAttachments, it->mpSource);
2680 // If no attachment is found do not change anything. The source
2681 // medium might not have been attached to the snapshot.
2682 if (pAtt)
2683 {
2684 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
2685 pAtt->updateMedium(it->mpTarget, false /* aImplicit */);
2686 it->mpTarget->addBackReference(pMachine->mData->mUuid, childSnapshotId);
2687 }
2688 }
2689
2690 if (fNeedSourceUninit)
2691 it->mpSource->uninit();
2692
2693 // One attachment is merged, must save the settings
2694 fMachineSettingsChanged = true;
2695
2696 // prevent calling cancelDeleteSnapshotMedium() for this attachment
2697 it = toDelete.erase(it);
2698
2699 // Delayed failure exit when the merge cleanup failed but the
2700 // merge actually succeeded.
2701 if (FAILED(rc))
2702 throw rc;
2703 }
2704
2705 {
2706 // beginSnapshotDelete() needs the machine lock, and the snapshots
2707 // tree is protected by the machine lock as well
2708 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2709
2710 aTask.pSnapshot->beginSnapshotDelete();
2711 aTask.pSnapshot->uninit();
2712
2713 fMachineSettingsChanged = true;
2714 }
2715 }
2716 catch (HRESULT aRC) { rc = aRC; }
2717
2718 if (FAILED(rc))
2719 {
2720 // preserve existing error info so that the result can
2721 // be properly reported to the progress object below
2722 ErrorInfoKeeper eik;
2723
2724 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2725 &mParent->getMediaTreeLockHandle() // media tree
2726 COMMA_LOCKVAL_SRC_POS);
2727
2728 // un-prepare the remaining hard disks
2729 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
2730 it != toDelete.end();
2731 ++it)
2732 {
2733 cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
2734 it->mChildrenToReparent,
2735 it->mfNeedsOnlineMerge,
2736 it->mpMediumLockList, it->mMachineId,
2737 it->mSnapshotId);
2738 }
2739 }
2740
2741 // whether we were successful or not, we need to set the machine
2742 // state and save the machine settings;
2743 {
2744 // preserve existing error info so that the result can
2745 // be properly reported to the progress object below
2746 ErrorInfoKeeper eik;
2747
2748 // restore the machine state that was saved when the
2749 // task was started
2750 setMachineState(aTask.machineStateBackup);
2751 updateMachineStateOnClient();
2752
2753 if (fMachineSettingsChanged || fNeedsSaveSettings)
2754 {
2755 if (fMachineSettingsChanged)
2756 {
2757 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2758 /// @todo r=klaus the SaveS_Force is right now a workaround,
2759 // as something in saveSettings fails to detect deleted
2760 // snapshots in some cases (2 child snapshots -> 1 child
2761 // snapshot). Should be fixed, but don't drop SaveS_Force
2762 // then, as it avoids a rather costly config equality check
2763 // when we know that it is changed.
2764 saveSettings(&fNeedsSaveSettings, SaveS_Force | SaveS_InformCallbacksAnyway);
2765 }
2766
2767 if (fNeedsSaveSettings)
2768 {
2769 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
2770 mParent->saveSettings();
2771 }
2772 }
2773 }
2774
2775 // report the result (this will try to fetch current error info on failure)
2776 aTask.pProgress->notifyComplete(rc);
2777
2778 if (SUCCEEDED(rc))
2779 mParent->onSnapshotDeleted(mData->mUuid, snapshotId);
2780
2781 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", rc));
2782 LogFlowThisFuncLeave();
2783}
2784
2785/**
2786 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
2787 * performs necessary state changes. Must not be called for writethrough disks
2788 * because there is nothing to delete/merge then.
2789 *
2790 * This method is to be called prior to calling #deleteSnapshotMedium().
2791 * If #deleteSnapshotMedium() is not called or fails, the state modifications
2792 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
2793 *
2794 * @return COM status code
2795 * @param aHD Hard disk which is connected to the snapshot.
2796 * @param aMachineId UUID of machine this hard disk is attached to.
2797 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
2798 * be a zero UUID if no snapshot is applicable.
2799 * @param fOnlineMergePossible Flag whether an online merge is possible.
2800 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
2801 * Only used if @a fOnlineMergePossible is @c true, and
2802 * must be non-NULL in this case.
2803 * @param aSource Source hard disk for merge (out).
2804 * @param aTarget Target hard disk for merge (out).
2805 * @param aMergeForward Merge direction decision (out).
2806 * @param aParentForTarget New parent if target needs to be reparented (out).
2807 * @param aChildrenToReparent Children which have to be reparented to the
2808 * target (out).
2809 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
2810 * If this is set to @a true then the @a aVMMALockList
2811 * parameter has been modified and is returned as
2812 * @a aMediumLockList.
2813 * @param aMediumLockList Where to store the created medium lock list (may
2814 * return NULL if no real merge is necessary).
2815 *
2816 * @note Caller must hold media tree lock for writing. This locks this object
2817 * and every medium object on the merge chain for writing.
2818 */
2819HRESULT SessionMachine::prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
2820 const Guid &aMachineId,
2821 const Guid &aSnapshotId,
2822 bool fOnlineMergePossible,
2823 MediumLockList *aVMMALockList,
2824 ComObjPtr<Medium> &aSource,
2825 ComObjPtr<Medium> &aTarget,
2826 bool &aMergeForward,
2827 ComObjPtr<Medium> &aParentForTarget,
2828 MediaList &aChildrenToReparent,
2829 bool &fNeedsOnlineMerge,
2830 MediumLockList * &aMediumLockList)
2831{
2832 Assert(mParent->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
2833 Assert(!fOnlineMergePossible || VALID_PTR(aVMMALockList));
2834
2835 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
2836
2837 // Medium must not be writethrough/shareable at this point
2838 MediumType_T type = aHD->getType();
2839 AssertReturn( type != MediumType_Writethrough
2840 && type != MediumType_Shareable, E_FAIL);
2841
2842 aMediumLockList = NULL;
2843 fNeedsOnlineMerge = false;
2844
2845 if (aHD->getChildren().size() == 0)
2846 {
2847 /* This technically is no merge, set those values nevertheless.
2848 * Helps with updating the medium attachments. */
2849 aSource = aHD;
2850 aTarget = aHD;
2851
2852 /* special treatment of the last hard disk in the chain: */
2853 if (aHD->getParent().isNull())
2854 {
2855 /* lock only, to prevent any usage until the snapshot deletion
2856 * is completed */
2857 return aHD->LockWrite(NULL);
2858 }
2859
2860 /* the differencing hard disk w/o children will be deleted, protect it
2861 * from attaching to other VMs (this is why Deleting) */
2862 return aHD->markForDeletion();
2863 }
2864
2865 /* not going multi-merge as it's too expensive */
2866 if (aHD->getChildren().size() > 1)
2867 return setError(E_FAIL,
2868 tr("Hard disk '%s' has more than one child hard disk (%d)"),
2869 aHD->getLocationFull().raw(),
2870 aHD->getChildren().size());
2871
2872 ComObjPtr<Medium> pChild = aHD->getChildren().front();
2873
2874 /* we keep this locked, so lock the affected child to make sure the lock
2875 * order is correct when calling prepareMergeTo() */
2876 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
2877
2878 /* the rest is a normal merge setup */
2879 if (aHD->getParent().isNull())
2880 {
2881 /* base hard disk, backward merge */
2882 const Guid *pMachineId1 = pChild->getFirstMachineBackrefId();
2883 const Guid *pMachineId2 = aHD->getFirstMachineBackrefId();
2884 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
2885 {
2886 /* backward merge is too tricky, we'll just detach on snapshot
2887 * deletion, so lock only, to prevent any usage */
2888 return aHD->LockWrite(NULL);
2889 }
2890
2891 aSource = pChild;
2892 aTarget = aHD;
2893 }
2894 else
2895 {
2896 /* forward merge */
2897 aSource = aHD;
2898 aTarget = pChild;
2899 }
2900
2901 HRESULT rc;
2902 rc = aSource->prepareMergeTo(aTarget, &aMachineId, &aSnapshotId,
2903 !fOnlineMergePossible /* fLockMedia */,
2904 aMergeForward, aParentForTarget,
2905 aChildrenToReparent, aMediumLockList);
2906 if (SUCCEEDED(rc) && fOnlineMergePossible)
2907 {
2908 /* Try to lock the newly constructed medium lock list. If it succeeds
2909 * this can be handled as an offline merge, i.e. without the need of
2910 * asking the VM to do the merging. Only continue with the online
2911 * merging preparation if applicable. */
2912 rc = aMediumLockList->Lock();
2913 if (FAILED(rc) && fOnlineMergePossible)
2914 {
2915 /* Locking failed, this cannot be done as an offline merge. Try to
2916 * combine the locking information into the lock list of the medium
2917 * attachment in the running VM. If that fails or locking the
2918 * resulting lock list fails then the merge cannot be done online.
2919 * It can be repeated by the user when the VM is shut down. */
2920 MediumLockList::Base::iterator lockListVMMABegin =
2921 aVMMALockList->GetBegin();
2922 MediumLockList::Base::iterator lockListVMMAEnd =
2923 aVMMALockList->GetEnd();
2924 MediumLockList::Base::iterator lockListBegin =
2925 aMediumLockList->GetBegin();
2926 MediumLockList::Base::iterator lockListEnd =
2927 aMediumLockList->GetEnd();
2928 for (MediumLockList::Base::iterator it = lockListVMMABegin,
2929 it2 = lockListBegin;
2930 it2 != lockListEnd;
2931 ++it, ++it2)
2932 {
2933 if ( it == lockListVMMAEnd
2934 || it->GetMedium() != it2->GetMedium())
2935 {
2936 fOnlineMergePossible = false;
2937 break;
2938 }
2939 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
2940 rc = it->UpdateLock(fLockReq);
2941 if (FAILED(rc))
2942 {
2943 // could not update the lock, trigger cleanup below
2944 fOnlineMergePossible = false;
2945 break;
2946 }
2947 }
2948
2949 if (fOnlineMergePossible)
2950 {
2951 /* we will lock the children of the source for reparenting */
2952 for (MediaList::const_iterator it = aChildrenToReparent.begin();
2953 it != aChildrenToReparent.end();
2954 ++it)
2955 {
2956 ComObjPtr<Medium> pMedium = *it;
2957 if (pMedium->getState() == MediumState_Created)
2958 {
2959 rc = pMedium->LockWrite(NULL);
2960 if (FAILED(rc))
2961 throw rc;
2962 }
2963 else
2964 {
2965 rc = aVMMALockList->Update(pMedium, true);
2966 if (FAILED(rc))
2967 {
2968 rc = pMedium->LockWrite(NULL);
2969 if (FAILED(rc))
2970 throw rc;
2971 }
2972 }
2973 }
2974 }
2975
2976 if (fOnlineMergePossible)
2977 {
2978 rc = aVMMALockList->Lock();
2979 if (FAILED(rc))
2980 {
2981 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2982 rc = setError(rc,
2983 tr("Cannot lock hard disk '%s' for a live merge"),
2984 aHD->getLocationFull().raw());
2985 }
2986 else
2987 {
2988 delete aMediumLockList;
2989 aMediumLockList = aVMMALockList;
2990 fNeedsOnlineMerge = true;
2991 }
2992 }
2993 else
2994 {
2995 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2996 rc = setError(rc,
2997 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
2998 aHD->getLocationFull().raw());
2999 }
3000
3001 // fix the VM's lock list if anything failed
3002 if (FAILED(rc))
3003 {
3004 lockListVMMABegin = aVMMALockList->GetBegin();
3005 lockListVMMAEnd = aVMMALockList->GetEnd();
3006 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
3007 lockListLast--;
3008 for (MediumLockList::Base::iterator it = lockListVMMABegin;
3009 it != lockListVMMAEnd;
3010 ++it)
3011 {
3012 it->UpdateLock(it == lockListLast);
3013 ComObjPtr<Medium> pMedium = it->GetMedium();
3014 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3015 // blindly apply this, only needed for medium objects which
3016 // would be deleted as part of the merge
3017 pMedium->unmarkLockedForDeletion();
3018 }
3019 }
3020
3021 }
3022 else
3023 {
3024 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
3025 rc = setError(rc,
3026 tr("Cannot lock hard disk '%s' for an offline merge"),
3027 aHD->getLocationFull().raw());
3028 }
3029 }
3030
3031 return rc;
3032}
3033
3034/**
3035 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
3036 * what #prepareDeleteSnapshotMedium() did. Must be called if
3037 * #deleteSnapshotMedium() is not called or fails.
3038 *
3039 * @param aHD Hard disk which is connected to the snapshot.
3040 * @param aSource Source hard disk for merge.
3041 * @param aChildrenToReparent Children to unlock.
3042 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
3043 * @param aMediumLockList Medium locks to cancel.
3044 * @param aMachineId Machine id to attach the medium to.
3045 * @param aSnapshotId Snapshot id to attach the medium to.
3046 *
3047 * @note Locks the medium tree and the hard disks in the chain for writing.
3048 */
3049void SessionMachine::cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3050 const ComObjPtr<Medium> &aSource,
3051 const MediaList &aChildrenToReparent,
3052 bool fNeedsOnlineMerge,
3053 MediumLockList *aMediumLockList,
3054 const Guid &aMachineId,
3055 const Guid &aSnapshotId)
3056{
3057 if (aMediumLockList == NULL)
3058 {
3059 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
3060
3061 Assert(aHD->getChildren().size() == 0);
3062
3063 if (aHD->getParent().isNull())
3064 {
3065 HRESULT rc = aHD->UnlockWrite(NULL);;
3066 AssertComRC(rc);
3067 }
3068 else
3069 {
3070 HRESULT rc = aHD->unmarkForDeletion();
3071 AssertComRC(rc);
3072 }
3073 }
3074 else
3075 {
3076 if (fNeedsOnlineMerge)
3077 {
3078 // Online merge uses the medium lock list of the VM, so give
3079 // an empty list to cancelMergeTo so that it works as designed.
3080 aSource->cancelMergeTo(aChildrenToReparent, new MediumLockList());
3081
3082 // clean up the VM medium lock list ourselves
3083 MediumLockList::Base::iterator lockListBegin =
3084 aMediumLockList->GetBegin();
3085 MediumLockList::Base::iterator lockListEnd =
3086 aMediumLockList->GetEnd();
3087 MediumLockList::Base::iterator lockListLast = lockListEnd;
3088 lockListLast--;
3089 for (MediumLockList::Base::iterator it = lockListBegin;
3090 it != lockListEnd;
3091 ++it)
3092 {
3093 ComObjPtr<Medium> pMedium = it->GetMedium();
3094 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3095 if (pMedium->getState() == MediumState_Deleting)
3096 pMedium->unmarkForDeletion();
3097 else
3098 {
3099 // blindly apply this, only needed for medium objects which
3100 // would be deleted as part of the merge
3101 pMedium->unmarkLockedForDeletion();
3102 }
3103 it->UpdateLock(it == lockListLast);
3104 }
3105 }
3106 else
3107 {
3108 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
3109 }
3110 }
3111
3112 if (!aMachineId.isEmpty())
3113 {
3114 // reattach the source media to the snapshot
3115 HRESULT rc = aSource->addBackReference(aMachineId, aSnapshotId);
3116 AssertComRC(rc);
3117 }
3118}
3119
3120/**
3121 * Perform an online merge of a hard disk, i.e. the equivalent of
3122 * Medium::mergeTo(), just for running VMs. If this fails you need to call
3123 * #cancelDeleteSnapshotMedium().
3124 *
3125 * @return COM status code
3126 * @param aMediumAttachment Identify where the disk is attached in the VM.
3127 * @param aSource Source hard disk for merge.
3128 * @param aTarget Target hard disk for merge.
3129 * @param aMergeForward Merge direction.
3130 * @param aParentForTarget New parent if target needs to be reparented.
3131 * @param aChildrenToReparent Children which have to be reparented to the
3132 * target.
3133 * @param aMediumLockList Where to store the created medium lock list (may
3134 * return NULL if no real merge is necessary).
3135 * @param aProgress Progress indicator.
3136 * @param pfNeedsSaveSettings Whether the VM settings need to be saved (out).
3137 */
3138HRESULT SessionMachine::onlineMergeMedium(const ComObjPtr<MediumAttachment> &aMediumAttachment,
3139 const ComObjPtr<Medium> &aSource,
3140 const ComObjPtr<Medium> &aTarget,
3141 bool fMergeForward,
3142 const ComObjPtr<Medium> &aParentForTarget,
3143 const MediaList &aChildrenToReparent,
3144 MediumLockList *aMediumLockList,
3145 ComObjPtr<Progress> &aProgress,
3146 bool *pfNeedsSaveSettings)
3147{
3148 AssertReturn(aSource != NULL, E_FAIL);
3149 AssertReturn(aTarget != NULL, E_FAIL);
3150 AssertReturn(aSource != aTarget, E_FAIL);
3151 AssertReturn(aMediumLockList != NULL, E_FAIL);
3152
3153 HRESULT rc = S_OK;
3154
3155 try
3156 {
3157 // Similar code appears in Medium::taskMergeHandle, so
3158 // if you make any changes below check whether they are applicable
3159 // in that context as well.
3160
3161 unsigned uTargetIdx = (unsigned)-1;
3162 unsigned uSourceIdx = (unsigned)-1;
3163 /* Sanity check all hard disks in the chain. */
3164 MediumLockList::Base::iterator lockListBegin =
3165 aMediumLockList->GetBegin();
3166 MediumLockList::Base::iterator lockListEnd =
3167 aMediumLockList->GetEnd();
3168 unsigned i = 0;
3169 for (MediumLockList::Base::iterator it = lockListBegin;
3170 it != lockListEnd;
3171 ++it)
3172 {
3173 MediumLock &mediumLock = *it;
3174 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
3175
3176 if (pMedium == aSource)
3177 uSourceIdx = i;
3178 else if (pMedium == aTarget)
3179 uTargetIdx = i;
3180
3181 // In Medium::taskMergeHandler there is lots of consistency
3182 // checking which we cannot do here, as the state details are
3183 // impossible to get outside the Medium class. The locking should
3184 // have done the checks already.
3185
3186 i++;
3187 }
3188
3189 ComAssertThrow( uSourceIdx != (unsigned)-1
3190 && uTargetIdx != (unsigned)-1, E_FAIL);
3191
3192 // For forward merges, tell the VM what images need to have their
3193 // parent UUID updated. This cannot be done in VBoxSVC, as opening
3194 // the required parent images is not safe while the VM is running.
3195 // For backward merges this will be simply an array of size 0.
3196 com::SafeIfaceArray<IMedium> childrenToReparent(aChildrenToReparent);
3197
3198 ComPtr<IInternalSessionControl> directControl;
3199 {
3200 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3201
3202 if (mData->mSession.mState != SessionState_Locked)
3203 throw setError(VBOX_E_INVALID_VM_STATE,
3204 tr("Machine is not locked by a session (session state: %s)"),
3205 Global::stringifySessionState(mData->mSession.mState));
3206 directControl = mData->mSession.mDirectControl;
3207 }
3208
3209 // Must not hold any locks here, as this will call back to finish
3210 // updating the medium attachment, chain linking and state.
3211 rc = directControl->OnlineMergeMedium(aMediumAttachment,
3212 uSourceIdx, uTargetIdx,
3213 aSource, aTarget,
3214 fMergeForward, aParentForTarget,
3215 ComSafeArrayAsInParam(childrenToReparent),
3216 aProgress);
3217 if (FAILED(rc))
3218 throw rc;
3219 }
3220 catch (HRESULT aRC) { rc = aRC; }
3221
3222 // The callback mentioned above takes care of update the medium state
3223
3224 if (pfNeedsSaveSettings)
3225 *pfNeedsSaveSettings = true;
3226
3227 return rc;
3228}
3229
3230/**
3231 * Implementation for IInternalMachineControl::finishOnlineMergeMedium().
3232 *
3233 * Gets called after the successful completion of an online merge from
3234 * Console::onlineMergeMedium(), which gets invoked indirectly above in
3235 * the call to IInternalSessionControl::onlineMergeMedium.
3236 *
3237 * This updates the medium information and medium state so that the VM
3238 * can continue with the updated state of the medium chain.
3239 */
3240STDMETHODIMP SessionMachine::FinishOnlineMergeMedium(IMediumAttachment *aMediumAttachment,
3241 IMedium *aSource,
3242 IMedium *aTarget,
3243 BOOL aMergeForward,
3244 IMedium *aParentForTarget,
3245 ComSafeArrayIn(IMedium *, aChildrenToReparent))
3246{
3247 HRESULT rc = S_OK;
3248 ComObjPtr<Medium> pSource(static_cast<Medium *>(aSource));
3249 ComObjPtr<Medium> pTarget(static_cast<Medium *>(aTarget));
3250 ComObjPtr<Medium> pParentForTarget(static_cast<Medium *>(aParentForTarget));
3251
3252 // all hard disks but the target were successfully deleted by
3253 // the merge; reparent target if necessary and uninitialize media
3254
3255 AutoWriteLock treeLock(mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3256
3257 if (aMergeForward)
3258 {
3259 // first, unregister the target since it may become a base
3260 // hard disk which needs re-registration
3261 rc = mParent->unregisterHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
3262 AssertComRC(rc);
3263
3264 // then, reparent it and disconnect the deleted branch at
3265 // both ends (chain->parent() is source's parent)
3266 pTarget->deparent();
3267 pTarget->setParent(pParentForTarget);
3268 if (pParentForTarget)
3269 pSource->deparent();
3270
3271 // then, register again
3272 rc = mParent->registerHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
3273 AssertComRC(rc);
3274 }
3275 else
3276 {
3277 Assert(pTarget->getChildren().size() == 1);
3278 Medium *targetChild = pTarget->getChildren().front();
3279
3280 // disconnect the deleted branch at the elder end
3281 targetChild->deparent();
3282
3283 // Update parent UUIDs of the source's children, reparent them and
3284 // disconnect the deleted branch at the younger end
3285 com::SafeIfaceArray<IMedium> childrenToReparent(ComSafeArrayInArg(aChildrenToReparent));
3286 if (childrenToReparent.size() > 0)
3287 {
3288 // Fix the parent UUID of the images which needs to be moved to
3289 // underneath target. The running machine has the images opened,
3290 // but only for reading since the VM is paused. If anything fails
3291 // we must continue. The worst possible result is that the images
3292 // need manual fixing via VBoxManage to adjust the parent UUID.
3293 MediaList toReparent;
3294 for (size_t i = 0; i < childrenToReparent.size(); i++)
3295 {
3296 Medium *pMedium = static_cast<Medium *>(childrenToReparent[i]);
3297 toReparent.push_back(pMedium);
3298 }
3299 pTarget->fixParentUuidOfChildren(toReparent);
3300
3301 // obey {parent,child} lock order
3302 AutoWriteLock sourceLock(pSource COMMA_LOCKVAL_SRC_POS);
3303
3304 for (size_t i = 0; i < childrenToReparent.size(); i++)
3305 {
3306 Medium *pMedium = static_cast<Medium *>(childrenToReparent[i]);
3307 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
3308
3309 pMedium->deparent(); // removes pMedium from source
3310 pMedium->setParent(pTarget);
3311 }
3312 }
3313 }
3314
3315 /* unregister and uninitialize all hard disks removed by the merge */
3316 MediumLockList *pMediumLockList = NULL;
3317 rc = mData->mSession.mLockedMedia.Get(static_cast<MediumAttachment *>(aMediumAttachment),
3318 pMediumLockList);
3319 const ComObjPtr<Medium> &pLast = aMergeForward ? pTarget : pSource;
3320 AssertReturn(SUCCEEDED(rc) && pMediumLockList, E_FAIL);
3321 MediumLockList::Base::iterator lockListBegin =
3322 pMediumLockList->GetBegin();
3323 MediumLockList::Base::iterator lockListEnd =
3324 pMediumLockList->GetEnd();
3325 for (MediumLockList::Base::iterator it = lockListBegin;
3326 it != lockListEnd;
3327 )
3328 {
3329 MediumLock &mediumLock = *it;
3330 /* Create a real copy of the medium pointer, as the medium
3331 * lock deletion below would invalidate the referenced object. */
3332 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
3333
3334 /* The target and all images not merged (readonly) are skipped */
3335 if ( pMedium == pTarget
3336 || pMedium->getState() == MediumState_LockedRead)
3337 {
3338 ++it;
3339 }
3340 else
3341 {
3342 rc = mParent->unregisterHardDisk(pMedium,
3343 NULL /*pfNeedsSaveSettings*/);
3344 AssertComRC(rc);
3345
3346 /* now, uninitialize the deleted hard disk (note that
3347 * due to the Deleting state, uninit() will not touch
3348 * the parent-child relationship so we need to
3349 * uninitialize each disk individually) */
3350
3351 /* note that the operation initiator hard disk (which is
3352 * normally also the source hard disk) is a special case
3353 * -- there is one more caller added by Task to it which
3354 * we must release. Also, if we are in sync mode, the
3355 * caller may still hold an AutoCaller instance for it
3356 * and therefore we cannot uninit() it (it's therefore
3357 * the caller's responsibility) */
3358 if (pMedium == aSource)
3359 {
3360 Assert(pSource->getChildren().size() == 0);
3361 Assert(pSource->getFirstMachineBackrefId() == NULL);
3362 }
3363
3364 /* Delete the medium lock list entry, which also releases the
3365 * caller added by MergeChain before uninit() and updates the
3366 * iterator to point to the right place. */
3367 rc = pMediumLockList->RemoveByIterator(it);
3368 AssertComRC(rc);
3369
3370 pMedium->uninit();
3371 }
3372
3373 /* Stop as soon as we reached the last medium affected by the merge.
3374 * The remaining images must be kept unchanged. */
3375 if (pMedium == pLast)
3376 break;
3377 }
3378
3379 /* Could be in principle folded into the previous loop, but let's keep
3380 * things simple. Update the medium locking to be the standard state:
3381 * all parent images locked for reading, just the last diff for writing. */
3382 lockListBegin = pMediumLockList->GetBegin();
3383 lockListEnd = pMediumLockList->GetEnd();
3384 MediumLockList::Base::iterator lockListLast = lockListEnd;
3385 lockListLast--;
3386 for (MediumLockList::Base::iterator it = lockListBegin;
3387 it != lockListEnd;
3388 ++it)
3389 {
3390 it->UpdateLock(it == lockListLast);
3391 }
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