VirtualBox

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

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

Main: rename internal medium attach/detach methods

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