VirtualBox

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

Last change on this file since 49953 was 49871, checked in by vboxsync, 11 years ago

6813 - User server side API wrapper code in all interfaces.. stage 4 rev 1

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