VirtualBox

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

Last change on this file since 44037 was 43915, checked in by vboxsync, 12 years ago

Main/Machine+Snapshot+Medium: fix cancelling snapshots, used to trigger both backref inconsistency and incorrect lock list/map updates which could cause runtime misbehavior, the config file was already made consistent with the previous changes

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

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