VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/SnapshotImpl.cpp@ 47348

Last change on this file since 47348 was 46720, checked in by vboxsync, 12 years ago

Main/xml/Settings.cpp: limit snapshot depth to 250, avoiding crashes
Main/Snapshot: limit snapshot depth to 250
Main/Medium: eliminate some spurious error messages when saving a VM config

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