VirtualBox

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

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

Main: typo

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

© 2023 Oracle
ContactPrivacy policyTerms of Use