VirtualBox

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

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

Main: make calculateRelativePath methods a bit smarter and rename them to VirtualBox::copyPathRelativeToConfig() and Machine::copyPathRelativeToMachine()

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

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