VirtualBox

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

Last change on this file since 66046 was 66046, checked in by vboxsync, 8 years ago

Main/Snapshot: When creating a snapshot it's necessary to copy the medium attachment objects (and not use the same ones) to separate the new snapshot from current state. Otherwise changing a removable medium (DVD/floppy) will show up in 'fresh' snapshots, i.e. the ones taken since VBoxSVC was started. Same issue for PCI device attachments (which isn't used as much). Apart from that a lot of error checking cleanup, for consistency reasons.

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