VirtualBox

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

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

Main/Machine+Snapshot+Appliance+StorageController: eliminate the one-member struct MediaData, as a preparation for later eliminating the Backupable<> template use in combination with anything containing a ComObjPtr (since these are not handled in a sensible way when creating a session or a snapshot anyway, needing more effort to fix than do right from the beginning). Additionally a lot of iterator loop cleanups, making proper use of scoping and const_iterator whenever possible. Also take the opportunity to improve the readability of some quite long lines. No behavior change intended.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 145.6 KB
Line 
1/* $Id: SnapshotImpl.cpp 66126 2017-03-16 14:06:27Z vboxsync $ */
2/** @file
3 * COM class implementation for Snapshot and SnapshotMachine in VBoxSVC.
4 */
5
6/*
7 * Copyright (C) 2006-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. 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 mMediumAttachments.allocate();
1016 for (MediumAttachmentList::const_iterator
1017 it = aSessionMachine->mMediumAttachments->begin();
1018 it != aSessionMachine->mMediumAttachments->end();
1019 ++it)
1020 {
1021 ComObjPtr<MediumAttachment> pAtt;
1022 pAtt.createObject();
1023 rc = pAtt->initCopy(this, *it);
1024 if (FAILED(rc)) return rc;
1025 mMediumAttachments->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 mMediumAttachments.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 (MediumAttachmentList::iterator
1513 it = mMediumAttachments->begin();
1514 it != mMediumAttachments->end();
1515 ++it)
1516 {
1517 const ComObjPtr<MediumAttachment> pAtt(*it);
1518 AutoReadLock attlock(pAtt COMMA_LOCKVAL_SRC_POS);
1519 AutoCaller attCaller(pAtt);
1520 if (pAtt->i_getType() == DeviceType_HardDisk)
1521 {
1522 ++cOperations;
1523
1524 // assume that creating a diff image takes as long as saving a 1MB state
1525 ulTotalOperationsWeight += 1;
1526 }
1527 }
1528
1529 // b) one extra sub-operations for online snapshots OR offline snapshots that have a saved state (needs to be copied)
1530 const bool fTakingSnapshotOnline = Global::IsOnline(mData->mMachineState);
1531 LogFlowThisFunc(("fTakingSnapshotOnline = %d\n", fTakingSnapshotOnline));
1532 if (fTakingSnapshotOnline)
1533 {
1534 ++cOperations;
1535 ulTotalOperationsWeight += mHWData->mMemorySize;
1536 }
1537
1538 // finally, create the progress object
1539 ComObjPtr<Progress> pProgress;
1540 pProgress.createObject();
1541 rc = pProgress->init(mParent,
1542 static_cast<IMachine *>(this),
1543 Bstr(tr("Taking a snapshot of the virtual machine")).raw(),
1544 fTakingSnapshotOnline /* aCancelable */,
1545 cOperations,
1546 ulTotalOperationsWeight,
1547 Bstr(tr("Setting up snapshot operation")).raw(), // first sub-op description
1548 1); // ulFirstOperationWeight
1549 if (FAILED(rc))
1550 return rc;
1551
1552 /* create an ID for the snapshot */
1553 Guid snapshotId;
1554 snapshotId.create();
1555
1556 /* create and start the task on a separate thread (note that it will not
1557 * start working until we release alock) */
1558 TakeSnapshotTask *pTask = new TakeSnapshotTask(this,
1559 pProgress,
1560 "TakeSnap",
1561 NULL /* pSnapshot */,
1562 aName,
1563 aDescription,
1564 snapshotId,
1565 !!fPause,
1566 mHWData->mMemorySize,
1567 fTakingSnapshotOnline);
1568 rc = pTask->createThread();
1569 if (FAILED(rc))
1570 return rc;
1571
1572 /* set the proper machine state (note: after creating a Task instance) */
1573 if (fTakingSnapshotOnline)
1574 {
1575 if (pTask->m_machineStateBackup != MachineState_Paused && !fPause)
1576 i_setMachineState(MachineState_LiveSnapshotting);
1577 else
1578 i_setMachineState(MachineState_OnlineSnapshotting);
1579 i_updateMachineStateOnClient();
1580 }
1581 else
1582 i_setMachineState(MachineState_Snapshotting);
1583
1584 aId = snapshotId;
1585 pTask->m_pProgress.queryInterfaceTo(aProgress.asOutParam());
1586
1587 return rc;
1588}
1589
1590/**
1591 * Task thread implementation for SessionMachine::TakeSnapshot(), called from
1592 * SessionMachine::taskHandler().
1593 *
1594 * @note Locks this object for writing.
1595 *
1596 * @param task
1597 * @return
1598 */
1599void SessionMachine::i_takeSnapshotHandler(TakeSnapshotTask &task)
1600{
1601 LogFlowThisFuncEnter();
1602
1603 // Taking a snapshot consists of the following:
1604 // 1) creating a Snapshot object with the current state of the machine
1605 // (hardware + storage)
1606 // 2) creating a diff image for each virtual hard disk, into which write
1607 // operations go after the snapshot has been created
1608 // 3) if the machine is online: saving the state of the virtual machine
1609 // (in the VM process)
1610 // 4) reattach the hard disks
1611 // 5) update the various snapshot/machine objects, save settings
1612
1613 HRESULT rc = S_OK;
1614 AutoCaller autoCaller(this);
1615 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
1616 if (FAILED(autoCaller.rc()))
1617 {
1618 /* we might have been uninitialized because the session was accidentally
1619 * closed by the client, so don't assert */
1620 rc = setError(E_FAIL,
1621 tr("The session has been accidentally closed"));
1622 task.m_pProgress->i_notifyComplete(rc);
1623 LogFlowThisFuncLeave();
1624 return;
1625 }
1626
1627 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1628
1629 bool fBeganTakingSnapshot = false;
1630 BOOL fSuspendedBySave = FALSE;
1631
1632 try
1633 {
1634 /// @todo at this point we have to be in the right state!!!!
1635 AssertStmt( mData->mMachineState == MachineState_Snapshotting
1636 || mData->mMachineState == MachineState_OnlineSnapshotting
1637 || mData->mMachineState == MachineState_LiveSnapshotting, throw E_FAIL);
1638 AssertStmt(task.m_machineStateBackup != mData->mMachineState, throw E_FAIL);
1639 AssertStmt(task.m_pSnapshot.isNull(), throw E_FAIL);
1640
1641 if ( mData->mCurrentSnapshot
1642 && mData->mCurrentSnapshot->i_getDepth() >= SETTINGS_SNAPSHOT_DEPTH_MAX)
1643 {
1644 throw setError(VBOX_E_INVALID_OBJECT_STATE,
1645 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"),
1646 mUserData->s.strName.c_str());
1647 }
1648
1649 /* save settings to ensure current changes are committed and
1650 * hard disks are fixed up */
1651 rc = i_saveSettings(NULL);
1652 // no need to check for whether VirtualBox.xml needs changing since
1653 // we can't have a machine XML rename pending at this point
1654 if (FAILED(rc))
1655 throw rc;
1656
1657 /* task.m_strStateFilePath is "" when the machine is offline or saved */
1658 if (task.m_fTakingSnapshotOnline)
1659 {
1660 Bstr value;
1661 rc = GetExtraData(Bstr("VBoxInternal2/ForceTakeSnapshotWithoutState").raw(),
1662 value.asOutParam());
1663 if (FAILED(rc) || value != "1")
1664 // creating a new online snapshot: we need a fresh saved state file
1665 i_composeSavedStateFilename(task.m_strStateFilePath);
1666 }
1667 else if (task.m_machineStateBackup == MachineState_Saved)
1668 // taking an offline snapshot from machine in "saved" state: use existing state file
1669 task.m_strStateFilePath = mSSData->strStateFilePath;
1670
1671 if (task.m_strStateFilePath.isNotEmpty())
1672 {
1673 // ensure the directory for the saved state file exists
1674 rc = VirtualBox::i_ensureFilePathExists(task.m_strStateFilePath, true /* fCreate */);
1675 if (FAILED(rc))
1676 throw rc;
1677 }
1678
1679 /* STEP 1: create the snapshot object */
1680
1681 /* create a snapshot machine object */
1682 ComObjPtr<SnapshotMachine> pSnapshotMachine;
1683 pSnapshotMachine.createObject();
1684 rc = pSnapshotMachine->init(this, task.m_uuidSnapshot.ref(), task.m_strStateFilePath);
1685 AssertComRCThrowRC(rc);
1686
1687 /* create a snapshot object */
1688 RTTIMESPEC time;
1689 RTTimeNow(&time);
1690 task.m_pSnapshot.createObject();
1691 rc = task.m_pSnapshot->init(mParent,
1692 task.m_uuidSnapshot,
1693 task.m_strName,
1694 task.m_strDescription,
1695 time,
1696 pSnapshotMachine,
1697 mData->mCurrentSnapshot);
1698 AssertComRCThrowRC(rc);
1699
1700 /* STEP 2: create the diff images */
1701 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
1702 task.m_fTakingSnapshotOnline));
1703
1704 // Backup the media data so we can recover if something goes wrong.
1705 // The matching commit() is in fixupMedia() during SessionMachine::i_finishTakingSnapshot()
1706 i_setModified(IsModified_Storage);
1707 mMediumAttachments.backup();
1708
1709 alock.release();
1710 /* create new differencing hard disks and attach them to this machine */
1711 rc = i_createImplicitDiffs(task.m_pProgress,
1712 1, // operation weight; must be the same as in Machine::TakeSnapshot()
1713 task.m_fTakingSnapshotOnline);
1714 if (FAILED(rc))
1715 throw rc;
1716 alock.acquire();
1717
1718 // MUST NOT save the settings or the media registry here, because
1719 // this causes trouble with rolling back settings if the user cancels
1720 // taking the snapshot after the diff images have been created.
1721
1722 fBeganTakingSnapshot = true;
1723
1724 // STEP 3: save the VM state (if online)
1725 if (task.m_fTakingSnapshotOnline)
1726 {
1727 task.m_pProgress->SetNextOperation(Bstr(tr("Saving the machine state")).raw(),
1728 mHWData->mMemorySize); // operation weight, same as computed
1729 // when setting up progress object
1730
1731 if (task.m_strStateFilePath.isNotEmpty())
1732 {
1733 alock.release();
1734 task.m_pProgress->i_setCancelCallback(i_takeSnapshotProgressCancelCallback, &task);
1735 rc = task.m_pDirectControl->SaveStateWithReason(Reason_Snapshot,
1736 task.m_pProgress,
1737 Bstr(task.m_strStateFilePath).raw(),
1738 task.m_fPause,
1739 &fSuspendedBySave);
1740 task.m_pProgress->i_setCancelCallback(NULL, NULL);
1741 alock.acquire();
1742 if (FAILED(rc))
1743 throw rc;
1744 }
1745 else
1746 LogRel(("Machine: skipped saving state as part of online snapshot\n"));
1747
1748 if (!task.m_pProgress->i_notifyPointOfNoReturn())
1749 throw setError(E_FAIL, tr("Canceled"));
1750
1751 // STEP 4: reattach hard disks
1752 LogFlowThisFunc(("Reattaching new differencing hard disks...\n"));
1753
1754 task.m_pProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")).raw(),
1755 1); // operation weight, same as computed when setting up progress object
1756
1757 com::SafeIfaceArray<IMediumAttachment> atts;
1758 rc = COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
1759 if (FAILED(rc))
1760 throw rc;
1761
1762 alock.release();
1763 rc = task.m_pDirectControl->ReconfigureMediumAttachments(ComSafeArrayAsInParam(atts));
1764 alock.acquire();
1765 if (FAILED(rc))
1766 throw rc;
1767 }
1768
1769 /*
1770 * Finalize the requested snapshot object. This will reset the
1771 * machine state to the state it had at the beginning.
1772 */
1773 rc = i_finishTakingSnapshot(task, alock, true /*aSuccess*/);
1774 // do not throw rc here because we can't call i_finishTakingSnapshot() twice
1775 LogFlowThisFunc(("i_finishTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(mData->mMachineState)));
1776 }
1777 catch (HRESULT rcThrown)
1778 {
1779 rc = rcThrown;
1780 LogThisFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(mData->mMachineState)));
1781
1782 /// @todo r=klaus check that the implicit diffs created above are cleaned up im the relevant error cases
1783
1784 /* preserve existing error info */
1785 ErrorInfoKeeper eik;
1786
1787 if (fBeganTakingSnapshot)
1788 i_finishTakingSnapshot(task, alock, false /*aSuccess*/);
1789
1790 // have to postpone this to the end as i_finishTakingSnapshot() needs
1791 // it for various cleanup steps
1792 if (task.m_pSnapshot)
1793 {
1794 task.m_pSnapshot->uninit();
1795 task.m_pSnapshot.setNull();
1796 }
1797 }
1798 Assert(alock.isWriteLockOnCurrentThread());
1799
1800 {
1801 // Keep all error information over the cleanup steps
1802 ErrorInfoKeeper eik;
1803
1804 /*
1805 * Fix up the machine state.
1806 *
1807 * For offline snapshots we just update the local copy, for the other
1808 * variants do the entire work. This ensures that the state is in sync
1809 * with the VM process (in particular the VM execution state).
1810 */
1811 bool fNeedClientMachineStateUpdate = false;
1812 if ( mData->mMachineState == MachineState_LiveSnapshotting
1813 || mData->mMachineState == MachineState_OnlineSnapshotting
1814 || mData->mMachineState == MachineState_Snapshotting)
1815 {
1816 if (!task.m_fTakingSnapshotOnline)
1817 i_setMachineState(task.m_machineStateBackup);
1818 else
1819 {
1820 MachineState_T enmMachineState = MachineState_Null;
1821 HRESULT rc2 = task.m_pDirectControl->COMGETTER(NominalState)(&enmMachineState);
1822 if (FAILED(rc2) || enmMachineState == MachineState_Null)
1823 {
1824 AssertMsgFailed(("state=%s\n", Global::stringifyMachineState(enmMachineState)));
1825 // pure nonsense, try to continue somehow
1826 enmMachineState = MachineState_Aborted;
1827 }
1828 if (enmMachineState == MachineState_Paused)
1829 {
1830 if (fSuspendedBySave)
1831 {
1832 alock.release();
1833 rc2 = task.m_pDirectControl->ResumeWithReason(Reason_Snapshot);
1834 alock.acquire();
1835 if (SUCCEEDED(rc2))
1836 enmMachineState = task.m_machineStateBackup;
1837 }
1838 else
1839 enmMachineState = task.m_machineStateBackup;
1840 }
1841 if (enmMachineState != mData->mMachineState)
1842 {
1843 fNeedClientMachineStateUpdate = true;
1844 i_setMachineState(enmMachineState);
1845 }
1846 }
1847 }
1848
1849 /* check the remote state to see that we got it right. */
1850 MachineState_T enmMachineState = MachineState_Null;
1851 if (!task.m_pDirectControl.isNull())
1852 {
1853 ComPtr<IConsole> pConsole;
1854 task.m_pDirectControl->COMGETTER(RemoteConsole)(pConsole.asOutParam());
1855 if (!pConsole.isNull())
1856 pConsole->COMGETTER(State)(&enmMachineState);
1857 }
1858 LogFlowThisFunc(("local mMachineState=%s remote mMachineState=%s\n",
1859 Global::stringifyMachineState(mData->mMachineState),
1860 Global::stringifyMachineState(enmMachineState)));
1861
1862 if (fNeedClientMachineStateUpdate)
1863 i_updateMachineStateOnClient();
1864 }
1865
1866 task.m_pProgress->i_notifyComplete(rc);
1867
1868 if (SUCCEEDED(rc))
1869 mParent->i_onSnapshotTaken(mData->mUuid, task.m_uuidSnapshot);
1870 LogFlowThisFuncLeave();
1871}
1872
1873
1874/**
1875 * Progress cancelation callback employed by SessionMachine::i_takeSnapshotHandler.
1876 */
1877/*static*/
1878void SessionMachine::i_takeSnapshotProgressCancelCallback(void *pvUser)
1879{
1880 TakeSnapshotTask *pTask = (TakeSnapshotTask *)pvUser;
1881 AssertPtrReturnVoid(pTask);
1882 AssertReturnVoid(!pTask->m_pDirectControl.isNull());
1883 pTask->m_pDirectControl->CancelSaveStateWithReason();
1884}
1885
1886
1887/**
1888 * Called by the Console when it's done saving the VM state into the snapshot
1889 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
1890 *
1891 * This also gets called if the console part of snapshotting failed after the
1892 * BeginTakingSnapshot() call, to clean up the server side.
1893 *
1894 * @note Locks VirtualBox and this object for writing.
1895 *
1896 * @param task
1897 * @param alock
1898 * @param aSuccess Whether Console was successful with the client-side
1899 * snapshot things.
1900 * @return
1901 */
1902HRESULT SessionMachine::i_finishTakingSnapshot(TakeSnapshotTask &task, AutoWriteLock &alock, bool aSuccess)
1903{
1904 LogFlowThisFunc(("\n"));
1905
1906 Assert(alock.isWriteLockOnCurrentThread());
1907
1908 AssertReturn( !aSuccess
1909 || mData->mMachineState == MachineState_Snapshotting
1910 || mData->mMachineState == MachineState_OnlineSnapshotting
1911 || mData->mMachineState == MachineState_LiveSnapshotting, E_FAIL);
1912
1913 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
1914 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
1915
1916 HRESULT rc = S_OK;
1917
1918 if (aSuccess)
1919 {
1920 // new snapshot becomes the current one
1921 mData->mCurrentSnapshot = task.m_pSnapshot;
1922
1923 /* memorize the first snapshot if necessary */
1924 if (!mData->mFirstSnapshot)
1925 mData->mFirstSnapshot = mData->mCurrentSnapshot;
1926
1927 int flSaveSettings = SaveS_Force; // do not do a deep compare in machine settings,
1928 // snapshots change, so we know we need to save
1929 if (!task.m_fTakingSnapshotOnline)
1930 /* the machine was powered off or saved when taking a snapshot, so
1931 * reset the mCurrentStateModified flag */
1932 flSaveSettings |= SaveS_ResetCurStateModified;
1933
1934 rc = i_saveSettings(NULL, flSaveSettings);
1935 }
1936
1937 if (aSuccess && SUCCEEDED(rc))
1938 {
1939 /* associate old hard disks with the snapshot and do locking/unlocking*/
1940 i_commitMedia(task.m_fTakingSnapshotOnline);
1941 alock.release();
1942 }
1943 else
1944 {
1945 /* delete all differencing hard disks created (this will also attach
1946 * their parents back by rolling back mMediaData) */
1947 alock.release();
1948
1949 i_rollbackMedia();
1950
1951 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
1952 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
1953
1954 // delete the saved state file (it might have been already created)
1955 if (task.m_fTakingSnapshotOnline)
1956 // no need to test for whether the saved state file is shared: an online
1957 // snapshot means that a new saved state file was created, which we must
1958 // clean up now
1959 RTFileDelete(task.m_pSnapshot->i_getStateFilePath().c_str());
1960
1961 alock.acquire();
1962
1963 task.m_pSnapshot->uninit();
1964 alock.release();
1965
1966 }
1967
1968 /* clear out the snapshot data */
1969 task.m_pSnapshot.setNull();
1970
1971 /* alock has been released already */
1972 mParent->i_saveModifiedRegistries();
1973
1974 alock.acquire();
1975
1976 return rc;
1977}
1978
1979////////////////////////////////////////////////////////////////////////////////
1980//
1981// RestoreSnapshot methods (Machine and related tasks)
1982//
1983////////////////////////////////////////////////////////////////////////////////
1984
1985HRESULT Machine::restoreSnapshot(const ComPtr<ISnapshot> &aSnapshot,
1986 ComPtr<IProgress> &aProgress)
1987{
1988 NOREF(aSnapshot);
1989 NOREF(aProgress);
1990 ReturnComNotImplemented();
1991}
1992
1993/**
1994 * Restoring a snapshot happens entirely on the server side, the machine cannot be running.
1995 *
1996 * This creates a new thread that does the work and returns a progress object to the client.
1997 * Actual work then takes place in RestoreSnapshotTask::handler().
1998 *
1999 * @note Locks this + children objects for writing!
2000 *
2001 * @param aSnapshot in: the snapshot to restore.
2002 * @param aProgress out: progress object to monitor restore thread.
2003 * @return
2004 */
2005HRESULT SessionMachine::restoreSnapshot(const ComPtr<ISnapshot> &aSnapshot,
2006 ComPtr<IProgress> &aProgress)
2007{
2008 LogFlowThisFuncEnter();
2009
2010 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2011
2012 // machine must not be running
2013 if (Global::IsOnlineOrTransient(mData->mMachineState))
2014 return setError(VBOX_E_INVALID_VM_STATE,
2015 tr("Cannot delete the current state of the running machine (machine state: %s)"),
2016 Global::stringifyMachineState(mData->mMachineState));
2017
2018 HRESULT rc = i_checkStateDependency(MutableOrSavedStateDep);
2019 if (FAILED(rc))
2020 return rc;
2021
2022 ISnapshot* iSnapshot = aSnapshot;
2023 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(iSnapshot));
2024 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->i_getSnapshotMachine();
2025
2026 // create a progress object. The number of operations is:
2027 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
2028 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2029
2030 ULONG ulOpCount = 1; // one for preparations
2031 ULONG ulTotalWeight = 1; // one for preparations
2032 for (MediumAttachmentList::iterator
2033 it = pSnapMachine->mMediumAttachments->begin();
2034 it != pSnapMachine->mMediumAttachments->end();
2035 ++it)
2036 {
2037 ComObjPtr<MediumAttachment> &pAttach = *it;
2038 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2039 if (pAttach->i_getType() == DeviceType_HardDisk)
2040 {
2041 ++ulOpCount;
2042 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
2043 Assert(pAttach->i_getMedium());
2044 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount,
2045 pAttach->i_getMedium()->i_getName().c_str()));
2046 }
2047 }
2048
2049 ComObjPtr<Progress> pProgress;
2050 pProgress.createObject();
2051 pProgress->init(mParent, static_cast<IMachine*>(this),
2052 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->i_getName().c_str()).raw(),
2053 FALSE /* aCancelable */,
2054 ulOpCount,
2055 ulTotalWeight,
2056 Bstr(tr("Restoring machine settings")).raw(),
2057 1);
2058
2059 /* create and start the task on a separate thread (note that it will not
2060 * start working until we release alock) */
2061 RestoreSnapshotTask *pTask = new RestoreSnapshotTask(this,
2062 pProgress,
2063 "RestoreSnap",
2064 pSnapshot);
2065 rc = pTask->createThread();
2066 if (FAILED(rc))
2067 return rc;
2068
2069 /* set the proper machine state (note: after creating a Task instance) */
2070 i_setMachineState(MachineState_RestoringSnapshot);
2071
2072 /* return the progress to the caller */
2073 pProgress.queryInterfaceTo(aProgress.asOutParam());
2074
2075 LogFlowThisFuncLeave();
2076
2077 return S_OK;
2078}
2079
2080/**
2081 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
2082 * This method gets called indirectly through SessionMachine::taskHandler() which then
2083 * calls RestoreSnapshotTask::handler().
2084 *
2085 * The RestoreSnapshotTask contains the progress object returned to the console by
2086 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
2087 *
2088 * @note Locks mParent + this object for writing.
2089 *
2090 * @param task Task data.
2091 */
2092void SessionMachine::i_restoreSnapshotHandler(RestoreSnapshotTask &task)
2093{
2094 LogFlowThisFuncEnter();
2095
2096 AutoCaller autoCaller(this);
2097
2098 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
2099 if (!autoCaller.isOk())
2100 {
2101 /* we might have been uninitialized because the session was accidentally
2102 * closed by the client, so don't assert */
2103 task.m_pProgress->i_notifyComplete(E_FAIL,
2104 COM_IIDOF(IMachine),
2105 getComponentName(),
2106 tr("The session has been accidentally closed"));
2107
2108 LogFlowThisFuncLeave();
2109 return;
2110 }
2111
2112 HRESULT rc = S_OK;
2113
2114 try
2115 {
2116 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2117
2118 /* Discard all current changes to mUserData (name, OSType etc.).
2119 * Note that the machine is powered off, so there is no need to inform
2120 * the direct session. */
2121 if (mData->flModifications)
2122 i_rollback(false /* aNotify */);
2123
2124 /* Delete the saved state file if the machine was Saved prior to this
2125 * operation */
2126 if (task.m_machineStateBackup == MachineState_Saved)
2127 {
2128 Assert(!mSSData->strStateFilePath.isEmpty());
2129
2130 // release the saved state file AFTER unsetting the member variable
2131 // so that releaseSavedStateFile() won't think it's still in use
2132 Utf8Str strStateFile(mSSData->strStateFilePath);
2133 mSSData->strStateFilePath.setNull();
2134 i_releaseSavedStateFile(strStateFile, NULL /* pSnapshotToIgnore */ );
2135
2136 task.modifyBackedUpState(MachineState_PoweredOff);
2137
2138 rc = i_saveStateSettings(SaveSTS_StateFilePath);
2139 if (FAILED(rc))
2140 throw rc;
2141 }
2142
2143 RTTIMESPEC snapshotTimeStamp;
2144 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
2145
2146 {
2147 AutoReadLock snapshotLock(task.m_pSnapshot COMMA_LOCKVAL_SRC_POS);
2148
2149 /* remember the timestamp of the snapshot we're restoring from */
2150 snapshotTimeStamp = task.m_pSnapshot->i_getTimeStamp();
2151
2152 ComPtr<SnapshotMachine> pSnapshotMachine(task.m_pSnapshot->i_getSnapshotMachine());
2153
2154 /* copy all hardware data from the snapshot */
2155 i_copyFrom(pSnapshotMachine);
2156
2157 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
2158
2159 // restore the attachments from the snapshot
2160 i_setModified(IsModified_Storage);
2161 mMediumAttachments.backup();
2162 mMediumAttachments->clear();
2163 for (MediumAttachmentList::const_iterator
2164 it = pSnapshotMachine->mMediumAttachments->begin();
2165 it != pSnapshotMachine->mMediumAttachments->end();
2166 ++it)
2167 {
2168 ComObjPtr<MediumAttachment> pAttach;
2169 pAttach.createObject();
2170 pAttach->initCopy(this, *it);
2171 mMediumAttachments->push_back(pAttach);
2172 }
2173
2174 /* release the locks before the potentially lengthy operation */
2175 snapshotLock.release();
2176 alock.release();
2177
2178 rc = i_createImplicitDiffs(task.m_pProgress,
2179 1,
2180 false /* aOnline */);
2181 if (FAILED(rc))
2182 throw rc;
2183
2184 alock.acquire();
2185 snapshotLock.acquire();
2186
2187 /* Note: on success, current (old) hard disks will be
2188 * deassociated/deleted on #commit() called from #i_saveSettings() at
2189 * the end. On failure, newly created implicit diffs will be
2190 * deleted by #rollback() at the end. */
2191
2192 /* should not have a saved state file associated at this point */
2193 Assert(mSSData->strStateFilePath.isEmpty());
2194
2195 const Utf8Str &strSnapshotStateFile = task.m_pSnapshot->i_getStateFilePath();
2196
2197 if (strSnapshotStateFile.isNotEmpty())
2198 // online snapshot: then share the state file
2199 mSSData->strStateFilePath = strSnapshotStateFile;
2200
2201 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", task.m_pSnapshot->i_getId().raw()));
2202 /* make the snapshot we restored from the current snapshot */
2203 mData->mCurrentSnapshot = task.m_pSnapshot;
2204 }
2205
2206 /* grab differencing hard disks from the old attachments that will
2207 * become unused and need to be auto-deleted */
2208 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
2209
2210 for (MediumAttachmentList::const_iterator
2211 it = mMediumAttachments.backedUpData()->begin();
2212 it != mMediumAttachments.backedUpData()->end();
2213 ++it)
2214 {
2215 ComObjPtr<MediumAttachment> pAttach = *it;
2216 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
2217
2218 /* while the hard disk is attached, the number of children or the
2219 * parent cannot change, so no lock */
2220 if ( !pMedium.isNull()
2221 && pAttach->i_getType() == DeviceType_HardDisk
2222 && !pMedium->i_getParent().isNull()
2223 && pMedium->i_getChildren().size() == 0
2224 )
2225 {
2226 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->i_getName().c_str()));
2227
2228 llDiffAttachmentsToDelete.push_back(pAttach);
2229 }
2230 }
2231
2232 /* we have already deleted the current state, so set the execution
2233 * state accordingly no matter of the delete snapshot result */
2234 if (mSSData->strStateFilePath.isNotEmpty())
2235 task.modifyBackedUpState(MachineState_Saved);
2236 else
2237 task.modifyBackedUpState(MachineState_PoweredOff);
2238
2239 /* Paranoia: no one must have saved the settings in the mean time. If
2240 * it happens nevertheless we'll close our eyes and continue below. */
2241 Assert(mMediumAttachments.isBackedUp());
2242
2243 /* assign the timestamp from the snapshot */
2244 Assert(RTTimeSpecGetMilli(&snapshotTimeStamp) != 0);
2245 mData->mLastStateChange = snapshotTimeStamp;
2246
2247 // detach the current-state diffs that we detected above and build a list of
2248 // image files to delete _after_ i_saveSettings()
2249
2250 MediaList llDiffsToDelete;
2251
2252 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
2253 it != llDiffAttachmentsToDelete.end();
2254 ++it)
2255 {
2256 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
2257 ComObjPtr<Medium> pMedium = pAttach->i_getMedium();
2258
2259 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
2260
2261 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->i_getName().c_str()));
2262
2263 // Normally we "detach" the medium by removing the attachment object
2264 // from the current machine data; i_saveSettings() below would then
2265 // compare the current machine data with the one in the backup
2266 // and actually call Medium::removeBackReference(). But that works only half
2267 // the time in our case so instead we force a detachment here:
2268 // remove from machine data
2269 mMediumAttachments->remove(pAttach);
2270 // Remove it from the backup or else i_saveSettings will try to detach
2271 // it again and assert. The paranoia check avoids crashes (see
2272 // assert above) if this code is buggy and saves settings in the
2273 // wrong place.
2274 if (mMediumAttachments.isBackedUp())
2275 mMediumAttachments.backedUpData()->remove(pAttach);
2276 // then clean up backrefs
2277 pMedium->i_removeBackReference(mData->mUuid);
2278
2279 llDiffsToDelete.push_back(pMedium);
2280 }
2281
2282 // save machine settings, reset the modified flag and commit;
2283 bool fNeedsGlobalSaveSettings = false;
2284 rc = i_saveSettings(&fNeedsGlobalSaveSettings,
2285 SaveS_ResetCurStateModified);
2286 if (FAILED(rc))
2287 throw rc;
2288
2289 // release the locks before updating registry and deleting image files
2290 alock.release();
2291
2292 // unconditionally add the parent registry.
2293 mParent->i_markRegistryModified(mParent->i_getGlobalRegistryId());
2294
2295 // from here on we cannot roll back on failure any more
2296
2297 for (MediaList::iterator it = llDiffsToDelete.begin();
2298 it != llDiffsToDelete.end();
2299 ++it)
2300 {
2301 ComObjPtr<Medium> &pMedium = *it;
2302 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->i_getName().c_str()));
2303
2304 HRESULT rc2 = pMedium->i_deleteStorage(NULL /* aProgress */,
2305 true /* aWait */);
2306 // ignore errors here because we cannot roll back after i_saveSettings() above
2307 if (SUCCEEDED(rc2))
2308 pMedium->uninit();
2309 }
2310 }
2311 catch (HRESULT aRC)
2312 {
2313 rc = aRC;
2314 }
2315
2316 if (FAILED(rc))
2317 {
2318 /* preserve existing error info */
2319 ErrorInfoKeeper eik;
2320
2321 /* undo all changes on failure */
2322 i_rollback(false /* aNotify */);
2323
2324 }
2325
2326 mParent->i_saveModifiedRegistries();
2327
2328 /* restore the machine state */
2329 i_setMachineState(task.m_machineStateBackup);
2330
2331 /* set the result (this will try to fetch current error info on failure) */
2332 task.m_pProgress->i_notifyComplete(rc);
2333
2334 if (SUCCEEDED(rc))
2335 mParent->i_onSnapshotRestored(mData->mUuid, Guid());
2336
2337 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
2338
2339 LogFlowThisFuncLeave();
2340}
2341
2342////////////////////////////////////////////////////////////////////////////////
2343//
2344// DeleteSnapshot methods (SessionMachine and related tasks)
2345//
2346////////////////////////////////////////////////////////////////////////////////
2347
2348HRESULT Machine::deleteSnapshot(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2349{
2350 NOREF(aId);
2351 NOREF(aProgress);
2352 ReturnComNotImplemented();
2353}
2354
2355HRESULT SessionMachine::deleteSnapshot(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2356{
2357 return i_deleteSnapshot(aId, aId,
2358 FALSE /* fDeleteAllChildren */,
2359 aProgress);
2360}
2361
2362HRESULT Machine::deleteSnapshotAndAllChildren(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2363{
2364 NOREF(aId);
2365 NOREF(aProgress);
2366 ReturnComNotImplemented();
2367}
2368
2369HRESULT SessionMachine::deleteSnapshotAndAllChildren(const com::Guid &aId, ComPtr<IProgress> &aProgress)
2370{
2371 return i_deleteSnapshot(aId, aId,
2372 TRUE /* fDeleteAllChildren */,
2373 aProgress);
2374}
2375
2376HRESULT Machine::deleteSnapshotRange(const com::Guid &aStartId, const com::Guid &aEndId, ComPtr<IProgress> &aProgress)
2377{
2378 NOREF(aStartId);
2379 NOREF(aEndId);
2380 NOREF(aProgress);
2381 ReturnComNotImplemented();
2382}
2383
2384HRESULT SessionMachine::deleteSnapshotRange(const com::Guid &aStartId, const com::Guid &aEndId, ComPtr<IProgress> &aProgress)
2385{
2386 return i_deleteSnapshot(aStartId, aEndId,
2387 FALSE /* fDeleteAllChildren */,
2388 aProgress);
2389}
2390
2391
2392/**
2393 * Implementation for SessionMachine::i_deleteSnapshot().
2394 *
2395 * Gets called from SessionMachine::DeleteSnapshot(). Deleting a snapshot
2396 * happens entirely on the server side if the machine is not running, and
2397 * if it is running then the merges are done via internal session callbacks.
2398 *
2399 * This creates a new thread that does the work and returns a progress
2400 * object to the client.
2401 *
2402 * Actual work then takes place in SessionMachine::i_deleteSnapshotHandler().
2403 *
2404 * @note Locks mParent + this + children objects for writing!
2405 */
2406HRESULT SessionMachine::i_deleteSnapshot(const com::Guid &aStartId,
2407 const com::Guid &aEndId,
2408 BOOL aDeleteAllChildren,
2409 ComPtr<IProgress> &aProgress)
2410{
2411 LogFlowThisFuncEnter();
2412
2413 AssertReturn(!aStartId.isZero() && !aEndId.isZero() && aStartId.isValid() && aEndId.isValid(), E_INVALIDARG);
2414
2415 /** @todo implement the "and all children" and "range" variants */
2416 if (aDeleteAllChildren || aStartId != aEndId)
2417 ReturnComNotImplemented();
2418
2419 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2420
2421 if (Global::IsTransient(mData->mMachineState))
2422 return setError(VBOX_E_INVALID_VM_STATE,
2423 tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
2424 Global::stringifyMachineState(mData->mMachineState));
2425
2426 // be very picky about machine states
2427 if ( Global::IsOnlineOrTransient(mData->mMachineState)
2428 && mData->mMachineState != MachineState_PoweredOff
2429 && mData->mMachineState != MachineState_Saved
2430 && mData->mMachineState != MachineState_Teleported
2431 && mData->mMachineState != MachineState_Aborted
2432 && mData->mMachineState != MachineState_Running
2433 && mData->mMachineState != MachineState_Paused)
2434 return setError(VBOX_E_INVALID_VM_STATE,
2435 tr("Invalid machine state: %s"),
2436 Global::stringifyMachineState(mData->mMachineState));
2437
2438 HRESULT rc = i_checkStateDependency(MutableOrSavedOrRunningStateDep);
2439 if (FAILED(rc))
2440 return rc;
2441
2442 ComObjPtr<Snapshot> pSnapshot;
2443 rc = i_findSnapshotById(aStartId, pSnapshot, true /* aSetError */);
2444 if (FAILED(rc))
2445 return rc;
2446
2447 AutoWriteLock snapshotLock(pSnapshot COMMA_LOCKVAL_SRC_POS);
2448 Utf8Str str;
2449
2450 size_t childrenCount = pSnapshot->i_getChildrenCount();
2451 if (childrenCount > 1)
2452 return setError(VBOX_E_INVALID_OBJECT_STATE,
2453 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"),
2454 pSnapshot->i_getName().c_str(),
2455 mUserData->s.strName.c_str(),
2456 childrenCount);
2457
2458 if (pSnapshot == mData->mCurrentSnapshot && childrenCount >= 1)
2459 return setError(VBOX_E_INVALID_OBJECT_STATE,
2460 tr("Snapshot '%s' of the machine '%s' cannot be deleted, because it is the current snapshot and has one child snapshot"),
2461 pSnapshot->i_getName().c_str(),
2462 mUserData->s.strName.c_str());
2463
2464 /* If the snapshot being deleted is the current one, ensure current
2465 * settings are committed and saved.
2466 */
2467 if (pSnapshot == mData->mCurrentSnapshot)
2468 {
2469 if (mData->flModifications)
2470 {
2471 rc = i_saveSettings(NULL);
2472 // no need to change for whether VirtualBox.xml needs saving since
2473 // we can't have a machine XML rename pending at this point
2474 if (FAILED(rc)) return rc;
2475 }
2476 }
2477
2478 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->i_getSnapshotMachine();
2479
2480 /* create a progress object. The number of operations is:
2481 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
2482 */
2483 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2484
2485 ULONG ulOpCount = 1; // one for preparations
2486 ULONG ulTotalWeight = 1; // one for preparations
2487
2488 if (pSnapshot->i_getStateFilePath().length())
2489 {
2490 ++ulOpCount;
2491 ++ulTotalWeight; // assume 1 MB for deleting the state file
2492 }
2493
2494 // count normal hard disks and add their sizes to the weight
2495 for (MediumAttachmentList::iterator
2496 it = pSnapMachine->mMediumAttachments->begin();
2497 it != pSnapMachine->mMediumAttachments->end();
2498 ++it)
2499 {
2500 ComObjPtr<MediumAttachment> &pAttach = *it;
2501 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2502 if (pAttach->i_getType() == DeviceType_HardDisk)
2503 {
2504 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
2505 Assert(pHD);
2506 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2507
2508 MediumType_T type = pHD->i_getType();
2509 // writethrough and shareable images are unaffected by snapshots,
2510 // so do nothing for them
2511 if ( type != MediumType_Writethrough
2512 && type != MediumType_Shareable
2513 && type != MediumType_Readonly)
2514 {
2515 // normal or immutable media need attention
2516 ++ulOpCount;
2517 ulTotalWeight += (ULONG)(pHD->i_getSize() / _1M);
2518 }
2519 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->i_getName().c_str()));
2520 }
2521 }
2522
2523 ComObjPtr<Progress> pProgress;
2524 pProgress.createObject();
2525 pProgress->init(mParent, static_cast<IMachine*>(this),
2526 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->i_getName().c_str()).raw(),
2527 FALSE /* aCancelable */,
2528 ulOpCount,
2529 ulTotalWeight,
2530 Bstr(tr("Setting up")).raw(),
2531 1);
2532
2533 bool fDeleteOnline = ( (mData->mMachineState == MachineState_Running)
2534 || (mData->mMachineState == MachineState_Paused));
2535
2536 /* create and start the task on a separate thread */
2537 DeleteSnapshotTask *pTask = new DeleteSnapshotTask(this, pProgress,
2538 "DeleteSnap",
2539 fDeleteOnline,
2540 pSnapshot);
2541 rc = pTask->createThread();
2542 if (FAILED(rc))
2543 return rc;
2544
2545 // the task might start running but will block on acquiring the machine's write lock
2546 // which we acquired above; once this function leaves, the task will be unblocked;
2547 // set the proper machine state here now (note: after creating a Task instance)
2548 if (mData->mMachineState == MachineState_Running)
2549 {
2550 i_setMachineState(MachineState_DeletingSnapshotOnline);
2551 i_updateMachineStateOnClient();
2552 }
2553 else if (mData->mMachineState == MachineState_Paused)
2554 {
2555 i_setMachineState(MachineState_DeletingSnapshotPaused);
2556 i_updateMachineStateOnClient();
2557 }
2558 else
2559 i_setMachineState(MachineState_DeletingSnapshot);
2560
2561 /* return the progress to the caller */
2562 pProgress.queryInterfaceTo(aProgress.asOutParam());
2563
2564 LogFlowThisFuncLeave();
2565
2566 return S_OK;
2567}
2568
2569/**
2570 * Helper struct for SessionMachine::deleteSnapshotHandler().
2571 */
2572struct MediumDeleteRec
2573{
2574 MediumDeleteRec()
2575 : mfNeedsOnlineMerge(false),
2576 mpMediumLockList(NULL)
2577 {}
2578
2579 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2580 const ComObjPtr<Medium> &aSource,
2581 const ComObjPtr<Medium> &aTarget,
2582 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2583 bool fMergeForward,
2584 const ComObjPtr<Medium> &aParentForTarget,
2585 MediumLockList *aChildrenToReparent,
2586 bool fNeedsOnlineMerge,
2587 MediumLockList *aMediumLockList,
2588 const ComPtr<IToken> &aHDLockToken)
2589 : mpHD(aHd),
2590 mpSource(aSource),
2591 mpTarget(aTarget),
2592 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2593 mfMergeForward(fMergeForward),
2594 mpParentForTarget(aParentForTarget),
2595 mpChildrenToReparent(aChildrenToReparent),
2596 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2597 mpMediumLockList(aMediumLockList),
2598 mpHDLockToken(aHDLockToken)
2599 {}
2600
2601 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2602 const ComObjPtr<Medium> &aSource,
2603 const ComObjPtr<Medium> &aTarget,
2604 const ComObjPtr<MediumAttachment> &aOnlineMediumAttachment,
2605 bool fMergeForward,
2606 const ComObjPtr<Medium> &aParentForTarget,
2607 MediumLockList *aChildrenToReparent,
2608 bool fNeedsOnlineMerge,
2609 MediumLockList *aMediumLockList,
2610 const ComPtr<IToken> &aHDLockToken,
2611 const Guid &aMachineId,
2612 const Guid &aSnapshotId)
2613 : mpHD(aHd),
2614 mpSource(aSource),
2615 mpTarget(aTarget),
2616 mpOnlineMediumAttachment(aOnlineMediumAttachment),
2617 mfMergeForward(fMergeForward),
2618 mpParentForTarget(aParentForTarget),
2619 mpChildrenToReparent(aChildrenToReparent),
2620 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2621 mpMediumLockList(aMediumLockList),
2622 mpHDLockToken(aHDLockToken),
2623 mMachineId(aMachineId),
2624 mSnapshotId(aSnapshotId)
2625 {}
2626
2627 ComObjPtr<Medium> mpHD;
2628 ComObjPtr<Medium> mpSource;
2629 ComObjPtr<Medium> mpTarget;
2630 ComObjPtr<MediumAttachment> mpOnlineMediumAttachment;
2631 bool mfMergeForward;
2632 ComObjPtr<Medium> mpParentForTarget;
2633 MediumLockList *mpChildrenToReparent;
2634 bool mfNeedsOnlineMerge;
2635 MediumLockList *mpMediumLockList;
2636 /** optional lock token, used only in case mpHD is not merged/deleted */
2637 ComPtr<IToken> mpHDLockToken;
2638 /* these are for reattaching the hard disk in case of a failure: */
2639 Guid mMachineId;
2640 Guid mSnapshotId;
2641};
2642
2643typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2644
2645/**
2646 * Worker method for the delete snapshot thread created by
2647 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2648 * through SessionMachine::taskHandler() which then calls
2649 * DeleteSnapshotTask::handler().
2650 *
2651 * The DeleteSnapshotTask contains the progress object returned to the console
2652 * by SessionMachine::DeleteSnapshot, through which progress and results are
2653 * reported.
2654 *
2655 * SessionMachine::DeleteSnapshot() has set the machine state to
2656 * MachineState_DeletingSnapshot right after creating this task. Since we block
2657 * on the machine write lock at the beginning, once that has been acquired, we
2658 * can assume that the machine state is indeed that.
2659 *
2660 * @note Locks the machine + the snapshot + the media tree for writing!
2661 *
2662 * @param task Task data.
2663 */
2664void SessionMachine::i_deleteSnapshotHandler(DeleteSnapshotTask &task)
2665{
2666 LogFlowThisFuncEnter();
2667
2668 MultiResult mrc(S_OK);
2669 AutoCaller autoCaller(this);
2670 LogFlowThisFunc(("state=%d\n", getObjectState().getState()));
2671 if (FAILED(autoCaller.rc()))
2672 {
2673 /* we might have been uninitialized because the session was accidentally
2674 * closed by the client, so don't assert */
2675 mrc = setError(E_FAIL,
2676 tr("The session has been accidentally closed"));
2677 task.m_pProgress->i_notifyComplete(mrc);
2678 LogFlowThisFuncLeave();
2679 return;
2680 }
2681
2682 MediumDeleteRecList toDelete;
2683 Guid snapshotId;
2684
2685 try
2686 {
2687 HRESULT rc = S_OK;
2688
2689 /* Locking order: */
2690 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2691 task.m_pSnapshot->lockHandle() // snapshot
2692 COMMA_LOCKVAL_SRC_POS);
2693 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2694 // has exited after setting the machine state to MachineState_DeletingSnapshot
2695
2696 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle()
2697 COMMA_LOCKVAL_SRC_POS);
2698
2699 ComObjPtr<SnapshotMachine> pSnapMachine = task.m_pSnapshot->i_getSnapshotMachine();
2700 // no need to lock the snapshot machine since it is const by definition
2701 Guid machineId = pSnapMachine->i_getId();
2702
2703 // save the snapshot ID (for callbacks)
2704 snapshotId = task.m_pSnapshot->i_getId();
2705
2706 // first pass:
2707 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2708
2709 // Go thru the attachments of the snapshot machine (the media in here
2710 // point to the disk states _before_ the snapshot was taken, i.e. the
2711 // state we're restoring to; for each such medium, we will need to
2712 // merge it with its one and only child (the diff image holding the
2713 // changes written after the snapshot was taken).
2714 for (MediumAttachmentList::iterator
2715 it = pSnapMachine->mMediumAttachments->begin();
2716 it != pSnapMachine->mMediumAttachments->end();
2717 ++it)
2718 {
2719 ComObjPtr<MediumAttachment> &pAttach = *it;
2720 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2721 if (pAttach->i_getType() != DeviceType_HardDisk)
2722 continue;
2723
2724 ComObjPtr<Medium> pHD = pAttach->i_getMedium();
2725 Assert(!pHD.isNull());
2726
2727 {
2728 // writethrough, shareable and readonly images are
2729 // unaffected by snapshots, skip them
2730 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
2731 MediumType_T type = pHD->i_getType();
2732 if ( type == MediumType_Writethrough
2733 || type == MediumType_Shareable
2734 || type == MediumType_Readonly)
2735 continue;
2736 }
2737
2738#ifdef DEBUG
2739 pHD->i_dumpBackRefs();
2740#endif
2741
2742 // needs to be merged with child or deleted, check prerequisites
2743 ComObjPtr<Medium> pTarget;
2744 ComObjPtr<Medium> pSource;
2745 bool fMergeForward = false;
2746 ComObjPtr<Medium> pParentForTarget;
2747 MediumLockList *pChildrenToReparent = NULL;
2748 bool fNeedsOnlineMerge = false;
2749 bool fOnlineMergePossible = task.m_fDeleteOnline;
2750 MediumLockList *pMediumLockList = NULL;
2751 MediumLockList *pVMMALockList = NULL;
2752 ComPtr<IToken> pHDLockToken;
2753 ComObjPtr<MediumAttachment> pOnlineMediumAttachment;
2754 if (fOnlineMergePossible)
2755 {
2756 // Look up the corresponding medium attachment in the currently
2757 // running VM. Any failure prevents a live merge. Could be made
2758 // a tad smarter by trying a few candidates, so that e.g. disks
2759 // which are simply moved to a different controller slot do not
2760 // prevent online merging in general.
2761 pOnlineMediumAttachment =
2762 i_findAttachment(*mMediumAttachments.data(),
2763 pAttach->i_getControllerName(),
2764 pAttach->i_getPort(),
2765 pAttach->i_getDevice());
2766 if (pOnlineMediumAttachment)
2767 {
2768 rc = mData->mSession.mLockedMedia.Get(pOnlineMediumAttachment,
2769 pVMMALockList);
2770 if (FAILED(rc))
2771 fOnlineMergePossible = false;
2772 }
2773 else
2774 fOnlineMergePossible = false;
2775 }
2776
2777 // no need to hold the lock any longer
2778 attachLock.release();
2779
2780 treeLock.release();
2781 rc = i_prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
2782 fOnlineMergePossible,
2783 pVMMALockList, pSource, pTarget,
2784 fMergeForward, pParentForTarget,
2785 pChildrenToReparent,
2786 fNeedsOnlineMerge,
2787 pMediumLockList,
2788 pHDLockToken);
2789 treeLock.acquire();
2790 if (FAILED(rc))
2791 throw rc;
2792
2793 // For simplicity, prepareDeleteSnapshotMedium selects the merge
2794 // direction in the following way: we merge pHD onto its child
2795 // (forward merge), not the other way round, because that saves us
2796 // from unnecessarily shuffling around the attachments for the
2797 // machine that follows the snapshot (next snapshot or current
2798 // state), unless it's a base image. Backwards merges of the first
2799 // snapshot into the base image is essential, as it ensures that
2800 // when all snapshots are deleted the only remaining image is a
2801 // base image. Important e.g. for medium formats which do not have
2802 // a file representation such as iSCSI.
2803
2804 // a couple paranoia checks for backward merges
2805 if (pMediumLockList != NULL && !fMergeForward)
2806 {
2807 // parent is null -> this disk is a base hard disk: we will
2808 // then do a backward merge, i.e. merge its only child onto the
2809 // base disk. Here we need then to update the attachment that
2810 // refers to the child and have it point to the parent instead
2811 Assert(pHD->i_getChildren().size() == 1);
2812
2813 ComObjPtr<Medium> pReplaceHD = pHD->i_getChildren().front();
2814
2815 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
2816 }
2817
2818 Guid replaceMachineId;
2819 Guid replaceSnapshotId;
2820
2821 const Guid *pReplaceMachineId = pSource->i_getFirstMachineBackrefId();
2822 // minimal sanity checking
2823 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
2824 if (pReplaceMachineId)
2825 replaceMachineId = *pReplaceMachineId;
2826
2827 const Guid *pSnapshotId = pSource->i_getFirstMachineBackrefSnapshotId();
2828 if (pSnapshotId)
2829 replaceSnapshotId = *pSnapshotId;
2830
2831 if (replaceMachineId.isValid() && !replaceMachineId.isZero())
2832 {
2833 // Adjust the backreferences, otherwise merging will assert.
2834 // Note that the medium attachment object stays associated
2835 // with the snapshot until the merge was successful.
2836 HRESULT rc2 = S_OK;
2837 rc2 = pSource->i_removeBackReference(replaceMachineId, replaceSnapshotId);
2838 AssertComRC(rc2);
2839
2840 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2841 pOnlineMediumAttachment,
2842 fMergeForward,
2843 pParentForTarget,
2844 pChildrenToReparent,
2845 fNeedsOnlineMerge,
2846 pMediumLockList,
2847 pHDLockToken,
2848 replaceMachineId,
2849 replaceSnapshotId));
2850 }
2851 else
2852 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2853 pOnlineMediumAttachment,
2854 fMergeForward,
2855 pParentForTarget,
2856 pChildrenToReparent,
2857 fNeedsOnlineMerge,
2858 pMediumLockList,
2859 pHDLockToken));
2860 }
2861
2862 {
2863 /*check available place on the storage*/
2864 RTFOFF pcbTotal = 0;
2865 RTFOFF pcbFree = 0;
2866 uint32_t pcbBlock = 0;
2867 uint32_t pcbSector = 0;
2868 std::multimap<uint32_t,uint64_t> neededStorageFreeSpace;
2869 std::map<uint32_t,const char*> serialMapToStoragePath;
2870
2871 for (MediumDeleteRecList::const_iterator
2872 it = toDelete.begin();
2873 it != toDelete.end();
2874 ++it)
2875 {
2876 uint64_t diskSize = 0;
2877 uint32_t pu32Serial = 0;
2878 ComObjPtr<Medium> pSource_local = it->mpSource;
2879 ComObjPtr<Medium> pTarget_local = it->mpTarget;
2880 ComPtr<IMediumFormat> pTargetFormat;
2881
2882 {
2883 if ( pSource_local.isNull()
2884 || pSource_local == pTarget_local)
2885 continue;
2886 }
2887
2888 rc = pTarget_local->COMGETTER(MediumFormat)(pTargetFormat.asOutParam());
2889 if (FAILED(rc))
2890 throw rc;
2891
2892 if (pTarget_local->i_isMediumFormatFile())
2893 {
2894 int vrc = RTFsQuerySerial(pTarget_local->i_getLocationFull().c_str(), &pu32Serial);
2895 if (RT_FAILURE(vrc))
2896 {
2897 rc = setError(E_FAIL,
2898 tr(" Unable to merge storage '%s'. Can't get storage UID "),
2899 pTarget_local->i_getLocationFull().c_str());
2900 throw rc;
2901 }
2902
2903 pSource_local->COMGETTER(Size)((LONG64*)&diskSize);
2904
2905 /* store needed free space in multimap */
2906 neededStorageFreeSpace.insert(std::make_pair(pu32Serial,diskSize));
2907 /* linking storage UID with snapshot path, it is a helper container (just for easy finding needed path) */
2908 serialMapToStoragePath.insert(std::make_pair(pu32Serial,pTarget_local->i_getLocationFull().c_str()));
2909 }
2910 }
2911
2912 while (!neededStorageFreeSpace.empty())
2913 {
2914 std::pair<std::multimap<uint32_t,uint64_t>::iterator,std::multimap<uint32_t,uint64_t>::iterator> ret;
2915 uint64_t commonSourceStoragesSize = 0;
2916
2917 /* find all records in multimap with identical storage UID*/
2918 ret = neededStorageFreeSpace.equal_range(neededStorageFreeSpace.begin()->first);
2919 std::multimap<uint32_t,uint64_t>::const_iterator it_ns = ret.first;
2920
2921 for (; it_ns != ret.second ; ++it_ns)
2922 {
2923 commonSourceStoragesSize += it_ns->second;
2924 }
2925
2926 /* find appropriate path by storage UID*/
2927 std::map<uint32_t,const char*>::const_iterator it_sm = serialMapToStoragePath.find(ret.first->first);
2928 /* get info about a storage */
2929 if (it_sm == serialMapToStoragePath.end())
2930 {
2931 LogFlowThisFunc((" Path to the storage wasn't found...\n "));
2932
2933 rc = setError(E_INVALIDARG,
2934 tr(" Unable to merge storage '%s'. Path to the storage wasn't found. "),
2935 it_sm->second);
2936 throw rc;
2937 }
2938
2939 int vrc = RTFsQuerySizes(it_sm->second, &pcbTotal, &pcbFree,&pcbBlock, &pcbSector);
2940 if (RT_FAILURE(vrc))
2941 {
2942 rc = setError(E_FAIL,
2943 tr(" Unable to merge storage '%s'. Can't get the storage size. "),
2944 it_sm->second);
2945 throw rc;
2946 }
2947
2948 if (commonSourceStoragesSize > (uint64_t)pcbFree)
2949 {
2950 LogFlowThisFunc((" Not enough free space to merge...\n "));
2951
2952 rc = setError(E_OUTOFMEMORY,
2953 tr(" Unable to merge storage '%s' - not enough free storage space. "),
2954 it_sm->second);
2955 throw rc;
2956 }
2957
2958 neededStorageFreeSpace.erase(ret.first, ret.second);
2959 }
2960
2961 serialMapToStoragePath.clear();
2962 }
2963
2964 // we can release the locks now since the machine state is MachineState_DeletingSnapshot
2965 treeLock.release();
2966 multiLock.release();
2967
2968 /* Now we checked that we can successfully merge all normal hard disks
2969 * (unless a runtime error like end-of-disc happens). Now get rid of
2970 * the saved state (if present), as that will free some disk space.
2971 * The snapshot itself will be deleted as late as possible, so that
2972 * the user can repeat the delete operation if he runs out of disk
2973 * space or cancels the delete operation. */
2974
2975 /* second pass: */
2976 LogFlowThisFunc(("2: Deleting saved state...\n"));
2977
2978 {
2979 // saveAllSnapshots() needs a machine lock, and the snapshots
2980 // tree is protected by the machine lock as well
2981 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2982
2983 Utf8Str stateFilePath = task.m_pSnapshot->i_getStateFilePath();
2984 if (!stateFilePath.isEmpty())
2985 {
2986 task.m_pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")).raw(),
2987 1); // weight
2988
2989 i_releaseSavedStateFile(stateFilePath, task.m_pSnapshot /* pSnapshotToIgnore */);
2990
2991 // machine will need saving now
2992 machineLock.release();
2993 mParent->i_markRegistryModified(i_getId());
2994 }
2995 }
2996
2997 /* third pass: */
2998 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
2999
3000 /// @todo NEWMEDIA turn the following errors into warnings because the
3001 /// snapshot itself has been already deleted (and interpret these
3002 /// warnings properly on the GUI side)
3003 for (MediumDeleteRecList::iterator it = toDelete.begin();
3004 it != toDelete.end();)
3005 {
3006 const ComObjPtr<Medium> &pMedium(it->mpHD);
3007 ULONG ulWeight;
3008
3009 {
3010 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3011 ulWeight = (ULONG)(pMedium->i_getSize() / _1M);
3012 }
3013
3014 task.m_pProgress->SetNextOperation(BstrFmt(tr("Merging differencing image '%s'"),
3015 pMedium->i_getName().c_str()).raw(),
3016 ulWeight);
3017
3018 bool fNeedSourceUninit = false;
3019 bool fReparentTarget = false;
3020 if (it->mpMediumLockList == NULL)
3021 {
3022 /* no real merge needed, just updating state and delete
3023 * diff files if necessary */
3024 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
3025
3026 Assert( !it->mfMergeForward
3027 || pMedium->i_getChildren().size() == 0);
3028
3029 /* Delete the differencing hard disk (has no children). Two
3030 * exceptions: if it's the last medium in the chain or if it's
3031 * a backward merge we don't want to handle due to complexity.
3032 * In both cases leave the image in place. If it's the first
3033 * exception the user can delete it later if he wants. */
3034 if (!pMedium->i_getParent().isNull())
3035 {
3036 Assert(pMedium->i_getState() == MediumState_Deleting);
3037 /* No need to hold the lock any longer. */
3038 mLock.release();
3039 rc = pMedium->i_deleteStorage(&task.m_pProgress,
3040 true /* aWait */);
3041 if (FAILED(rc))
3042 throw rc;
3043
3044 // need to uninit the deleted medium
3045 fNeedSourceUninit = true;
3046 }
3047 }
3048 else
3049 {
3050 bool fNeedsSave = false;
3051 if (it->mfNeedsOnlineMerge)
3052 {
3053 // Put the medium merge information (MediumDeleteRec) where
3054 // SessionMachine::FinishOnlineMergeMedium can get at it.
3055 // This callback will arrive while onlineMergeMedium is
3056 // still executing, and there can't be two tasks.
3057 /// @todo r=klaus this hack needs to go, and the logic needs to be "unconvoluted", putting SessionMachine in charge of coordinating the reconfig/resume.
3058 mConsoleTaskData.mDeleteSnapshotInfo = (void *)&(*it);
3059 // online medium merge, in the direction decided earlier
3060 rc = i_onlineMergeMedium(it->mpOnlineMediumAttachment,
3061 it->mpSource,
3062 it->mpTarget,
3063 it->mfMergeForward,
3064 it->mpParentForTarget,
3065 it->mpChildrenToReparent,
3066 it->mpMediumLockList,
3067 task.m_pProgress,
3068 &fNeedsSave);
3069 mConsoleTaskData.mDeleteSnapshotInfo = NULL;
3070 }
3071 else
3072 {
3073 // normal medium merge, in the direction decided earlier
3074 rc = it->mpSource->i_mergeTo(it->mpTarget,
3075 it->mfMergeForward,
3076 it->mpParentForTarget,
3077 it->mpChildrenToReparent,
3078 it->mpMediumLockList,
3079 &task.m_pProgress,
3080 true /* aWait */);
3081 }
3082
3083 // If the merge failed, we need to do our best to have a usable
3084 // VM configuration afterwards. The return code doesn't tell
3085 // whether the merge completed and so we have to check if the
3086 // source medium (diff images are always file based at the
3087 // moment) is still there or not. Be careful not to lose the
3088 // error code below, before the "Delayed failure exit".
3089 if (FAILED(rc))
3090 {
3091 AutoReadLock mlock(it->mpSource COMMA_LOCKVAL_SRC_POS);
3092 if (!it->mpSource->i_isMediumFormatFile())
3093 // Diff medium not backed by a file - cannot get status so
3094 // be pessimistic.
3095 throw rc;
3096 const Utf8Str &loc = it->mpSource->i_getLocationFull();
3097 // Source medium is still there, so merge failed early.
3098 if (RTFileExists(loc.c_str()))
3099 throw rc;
3100
3101 // Source medium is gone. Assume the merge succeeded and
3102 // thus it's safe to remove the attachment. We use the
3103 // "Delayed failure exit" below.
3104 }
3105
3106 // need to change the medium attachment for backward merges
3107 fReparentTarget = !it->mfMergeForward;
3108
3109 if (!it->mfNeedsOnlineMerge)
3110 {
3111 // need to uninit the medium deleted by the merge
3112 fNeedSourceUninit = true;
3113
3114 // delete the no longer needed medium lock list, which
3115 // implicitly handled the unlocking
3116 delete it->mpMediumLockList;
3117 it->mpMediumLockList = NULL;
3118 }
3119 }
3120
3121 // Now that the medium is successfully merged/deleted/whatever,
3122 // remove the medium attachment from the snapshot. For a backwards
3123 // merge the target attachment needs to be removed from the
3124 // snapshot, as the VM will take it over. For forward merges the
3125 // source medium attachment needs to be removed.
3126 ComObjPtr<MediumAttachment> pAtt;
3127 if (fReparentTarget)
3128 {
3129 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3130 it->mpTarget);
3131 it->mpTarget->i_removeBackReference(machineId, snapshotId);
3132 }
3133 else
3134 pAtt = i_findAttachment(*(pSnapMachine->mMediumAttachments.data()),
3135 it->mpSource);
3136 pSnapMachine->mMediumAttachments->remove(pAtt);
3137
3138 if (fReparentTarget)
3139 {
3140 // Search for old source attachment and replace with target.
3141 // There can be only one child snapshot in this case.
3142 ComObjPtr<Machine> pMachine = this;
3143 Guid childSnapshotId;
3144 ComObjPtr<Snapshot> pChildSnapshot = task.m_pSnapshot->i_getFirstChild();
3145 if (pChildSnapshot)
3146 {
3147 pMachine = pChildSnapshot->i_getSnapshotMachine();
3148 childSnapshotId = pChildSnapshot->i_getId();
3149 }
3150 pAtt = i_findAttachment(*(pMachine->mMediumAttachments).data(), it->mpSource);
3151 if (pAtt)
3152 {
3153 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
3154 pAtt->i_updateMedium(it->mpTarget);
3155 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3156 }
3157 else
3158 {
3159 // If no attachment is found do not change anything. Maybe
3160 // the source medium was not attached to the snapshot.
3161 // If this is an online deletion the attachment was updated
3162 // already to allow the VM continue execution immediately.
3163 // Needs a bit of special treatment due to this difference.
3164 if (it->mfNeedsOnlineMerge)
3165 it->mpTarget->i_addBackReference(pMachine->mData->mUuid, childSnapshotId);
3166 }
3167 }
3168
3169 if (fNeedSourceUninit)
3170 {
3171 // make sure that the diff image to be deleted has no parent,
3172 // even in error cases (where the deparenting may be missing)
3173 if (it->mpSource->i_getParent())
3174 it->mpSource->i_deparent();
3175 it->mpSource->uninit();
3176 }
3177
3178 // One attachment is merged, must save the settings
3179 mParent->i_markRegistryModified(i_getId());
3180
3181 // prevent calling cancelDeleteSnapshotMedium() for this attachment
3182 it = toDelete.erase(it);
3183
3184 // Delayed failure exit when the merge cleanup failed but the
3185 // merge actually succeeded.
3186 if (FAILED(rc))
3187 throw rc;
3188 }
3189
3190 {
3191 // beginSnapshotDelete() needs the machine lock, and the snapshots
3192 // tree is protected by the machine lock as well
3193 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
3194
3195 task.m_pSnapshot->i_beginSnapshotDelete();
3196 task.m_pSnapshot->uninit();
3197
3198 machineLock.release();
3199 mParent->i_markRegistryModified(i_getId());
3200 }
3201 }
3202 catch (HRESULT aRC) {
3203 mrc = aRC;
3204 }
3205
3206 if (FAILED(mrc))
3207 {
3208 // preserve existing error info so that the result can
3209 // be properly reported to the progress object below
3210 ErrorInfoKeeper eik;
3211
3212 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
3213 &mParent->i_getMediaTreeLockHandle() // media tree
3214 COMMA_LOCKVAL_SRC_POS);
3215
3216 // un-prepare the remaining hard disks
3217 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
3218 it != toDelete.end();
3219 ++it)
3220 i_cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
3221 it->mpChildrenToReparent,
3222 it->mfNeedsOnlineMerge,
3223 it->mpMediumLockList, it->mpHDLockToken,
3224 it->mMachineId, it->mSnapshotId);
3225 }
3226
3227 // whether we were successful or not, we need to set the machine
3228 // state and save the machine settings;
3229 {
3230 // preserve existing error info so that the result can
3231 // be properly reported to the progress object below
3232 ErrorInfoKeeper eik;
3233
3234 // restore the machine state that was saved when the
3235 // task was started
3236 i_setMachineState(task.m_machineStateBackup);
3237 if (Global::IsOnline(mData->mMachineState))
3238 i_updateMachineStateOnClient();
3239
3240 mParent->i_saveModifiedRegistries();
3241 }
3242
3243 // report the result (this will try to fetch current error info on failure)
3244 task.m_pProgress->i_notifyComplete(mrc);
3245
3246 if (SUCCEEDED(mrc))
3247 mParent->i_onSnapshotDeleted(mData->mUuid, snapshotId);
3248
3249 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", (HRESULT)mrc));
3250 LogFlowThisFuncLeave();
3251}
3252
3253/**
3254 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
3255 * performs necessary state changes. Must not be called for writethrough disks
3256 * because there is nothing to delete/merge then.
3257 *
3258 * This method is to be called prior to calling #deleteSnapshotMedium().
3259 * If #deleteSnapshotMedium() is not called or fails, the state modifications
3260 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
3261 *
3262 * @return COM status code
3263 * @param aHD Hard disk which is connected to the snapshot.
3264 * @param aMachineId UUID of machine this hard disk is attached to.
3265 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
3266 * be a zero UUID if no snapshot is applicable.
3267 * @param fOnlineMergePossible Flag whether an online merge is possible.
3268 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
3269 * Only used if @a fOnlineMergePossible is @c true, and
3270 * must be non-NULL in this case.
3271 * @param aSource Source hard disk for merge (out).
3272 * @param aTarget Target hard disk for merge (out).
3273 * @param aMergeForward Merge direction decision (out).
3274 * @param aParentForTarget New parent if target needs to be reparented (out).
3275 * @param aChildrenToReparent MediumLockList with children which have to be
3276 * reparented to the target (out).
3277 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
3278 * If this is set to @a true then the @a aVMMALockList
3279 * parameter has been modified and is returned as
3280 * @a aMediumLockList.
3281 * @param aMediumLockList Where to store the created medium lock list (may
3282 * return NULL if no real merge is necessary).
3283 * @param aHDLockToken Where to store the write lock token for aHD, in case
3284 * it is not merged or deleted (out).
3285 *
3286 * @note Caller must hold media tree lock for writing. This locks this object
3287 * and every medium object on the merge chain for writing.
3288 */
3289HRESULT SessionMachine::i_prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3290 const Guid &aMachineId,
3291 const Guid &aSnapshotId,
3292 bool fOnlineMergePossible,
3293 MediumLockList *aVMMALockList,
3294 ComObjPtr<Medium> &aSource,
3295 ComObjPtr<Medium> &aTarget,
3296 bool &aMergeForward,
3297 ComObjPtr<Medium> &aParentForTarget,
3298 MediumLockList * &aChildrenToReparent,
3299 bool &fNeedsOnlineMerge,
3300 MediumLockList * &aMediumLockList,
3301 ComPtr<IToken> &aHDLockToken)
3302{
3303 Assert(!mParent->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3304 Assert(!fOnlineMergePossible || VALID_PTR(aVMMALockList));
3305
3306 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
3307
3308 // Medium must not be writethrough/shareable/readonly at this point
3309 MediumType_T type = aHD->i_getType();
3310 AssertReturn( type != MediumType_Writethrough
3311 && type != MediumType_Shareable
3312 && type != MediumType_Readonly, E_FAIL);
3313
3314 aChildrenToReparent = NULL;
3315 aMediumLockList = NULL;
3316 fNeedsOnlineMerge = false;
3317
3318 if (aHD->i_getChildren().size() == 0)
3319 {
3320 /* This technically is no merge, set those values nevertheless.
3321 * Helps with updating the medium attachments. */
3322 aSource = aHD;
3323 aTarget = aHD;
3324
3325 /* special treatment of the last hard disk in the chain: */
3326 if (aHD->i_getParent().isNull())
3327 {
3328 /* lock only, to prevent any usage until the snapshot deletion
3329 * is completed */
3330 alock.release();
3331 return aHD->LockWrite(aHDLockToken.asOutParam());
3332 }
3333
3334 /* the differencing hard disk w/o children will be deleted, protect it
3335 * from attaching to other VMs (this is why Deleting) */
3336 return aHD->i_markForDeletion();
3337 }
3338
3339 /* not going multi-merge as it's too expensive */
3340 if (aHD->i_getChildren().size() > 1)
3341 return setError(E_FAIL,
3342 tr("Hard disk '%s' has more than one child hard disk (%d)"),
3343 aHD->i_getLocationFull().c_str(),
3344 aHD->i_getChildren().size());
3345
3346 ComObjPtr<Medium> pChild = aHD->i_getChildren().front();
3347
3348 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
3349
3350 /* the rest is a normal merge setup */
3351 if (aHD->i_getParent().isNull())
3352 {
3353 /* base hard disk, backward merge */
3354 const Guid *pMachineId1 = pChild->i_getFirstMachineBackrefId();
3355 const Guid *pMachineId2 = aHD->i_getFirstMachineBackrefId();
3356 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
3357 {
3358 /* backward merge is too tricky, we'll just detach on snapshot
3359 * deletion, so lock only, to prevent any usage */
3360 childLock.release();
3361 alock.release();
3362 return aHD->LockWrite(aHDLockToken.asOutParam());
3363 }
3364
3365 aSource = pChild;
3366 aTarget = aHD;
3367 }
3368 else
3369 {
3370 /* Determine best merge direction. */
3371 bool fMergeForward = true;
3372
3373 childLock.release();
3374 alock.release();
3375 HRESULT rc = aHD->i_queryPreferredMergeDirection(pChild, fMergeForward);
3376 alock.acquire();
3377 childLock.acquire();
3378
3379 if (FAILED(rc) && rc != E_FAIL)
3380 return rc;
3381
3382 if (fMergeForward)
3383 {
3384 aSource = aHD;
3385 aTarget = pChild;
3386 LogFlowThisFunc(("Forward merging selected\n"));
3387 }
3388 else
3389 {
3390 aSource = pChild;
3391 aTarget = aHD;
3392 LogFlowThisFunc(("Backward merging selected\n"));
3393 }
3394 }
3395
3396 HRESULT rc;
3397 childLock.release();
3398 alock.release();
3399 rc = aSource->i_prepareMergeTo(aTarget, &aMachineId, &aSnapshotId,
3400 !fOnlineMergePossible /* fLockMedia */,
3401 aMergeForward, aParentForTarget,
3402 aChildrenToReparent, aMediumLockList);
3403 alock.acquire();
3404 childLock.acquire();
3405 if (SUCCEEDED(rc) && fOnlineMergePossible)
3406 {
3407 /* Try to lock the newly constructed medium lock list. If it succeeds
3408 * this can be handled as an offline merge, i.e. without the need of
3409 * asking the VM to do the merging. Only continue with the online
3410 * merging preparation if applicable. */
3411 childLock.release();
3412 alock.release();
3413 rc = aMediumLockList->Lock();
3414 alock.acquire();
3415 childLock.acquire();
3416 if (FAILED(rc))
3417 {
3418 /* Locking failed, this cannot be done as an offline merge. Try to
3419 * combine the locking information into the lock list of the medium
3420 * attachment in the running VM. If that fails or locking the
3421 * resulting lock list fails then the merge cannot be done online.
3422 * It can be repeated by the user when the VM is shut down. */
3423 MediumLockList::Base::iterator lockListVMMABegin =
3424 aVMMALockList->GetBegin();
3425 MediumLockList::Base::iterator lockListVMMAEnd =
3426 aVMMALockList->GetEnd();
3427 MediumLockList::Base::iterator lockListBegin =
3428 aMediumLockList->GetBegin();
3429 MediumLockList::Base::iterator lockListEnd =
3430 aMediumLockList->GetEnd();
3431 for (MediumLockList::Base::iterator it = lockListVMMABegin,
3432 it2 = lockListBegin;
3433 it2 != lockListEnd;
3434 ++it, ++it2)
3435 {
3436 if ( it == lockListVMMAEnd
3437 || it->GetMedium() != it2->GetMedium())
3438 {
3439 fOnlineMergePossible = false;
3440 break;
3441 }
3442 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
3443 childLock.release();
3444 alock.release();
3445 rc = it->UpdateLock(fLockReq);
3446 alock.acquire();
3447 childLock.acquire();
3448 if (FAILED(rc))
3449 {
3450 // could not update the lock, trigger cleanup below
3451 fOnlineMergePossible = false;
3452 break;
3453 }
3454 }
3455
3456 if (fOnlineMergePossible)
3457 {
3458 /* we will lock the children of the source for reparenting */
3459 if (aChildrenToReparent && !aChildrenToReparent->IsEmpty())
3460 {
3461 /* Cannot just call aChildrenToReparent->Lock(), as one of
3462 * the children is the one under which the current state of
3463 * the VM is located, and this means it is already locked
3464 * (for reading). Note that no special unlocking is needed,
3465 * because cancelMergeTo will unlock everything locked in
3466 * its context (using the unlock on destruction), and both
3467 * cancelDeleteSnapshotMedium (in case something fails) and
3468 * FinishOnlineMergeMedium re-define the read/write lock
3469 * state of everything which the VM need, search for the
3470 * UpdateLock method calls. */
3471 childLock.release();
3472 alock.release();
3473 rc = aChildrenToReparent->Lock(true /* fSkipOverLockedMedia */);
3474 alock.acquire();
3475 childLock.acquire();
3476 MediumLockList::Base::iterator childrenToReparentBegin = aChildrenToReparent->GetBegin();
3477 MediumLockList::Base::iterator childrenToReparentEnd = aChildrenToReparent->GetEnd();
3478 for (MediumLockList::Base::iterator it = childrenToReparentBegin;
3479 it != childrenToReparentEnd;
3480 ++it)
3481 {
3482 ComObjPtr<Medium> pMedium = it->GetMedium();
3483 AutoReadLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3484 if (!it->IsLocked())
3485 {
3486 mediumLock.release();
3487 childLock.release();
3488 alock.release();
3489 rc = aVMMALockList->Update(pMedium, true);
3490 alock.acquire();
3491 childLock.acquire();
3492 mediumLock.acquire();
3493 if (FAILED(rc))
3494 throw rc;
3495 }
3496 }
3497 }
3498 }
3499
3500 if (fOnlineMergePossible)
3501 {
3502 childLock.release();
3503 alock.release();
3504 rc = aVMMALockList->Lock();
3505 alock.acquire();
3506 childLock.acquire();
3507 if (FAILED(rc))
3508 {
3509 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3510 rc = setError(rc,
3511 tr("Cannot lock hard disk '%s' for a live merge"),
3512 aHD->i_getLocationFull().c_str());
3513 }
3514 else
3515 {
3516 delete aMediumLockList;
3517 aMediumLockList = aVMMALockList;
3518 fNeedsOnlineMerge = true;
3519 }
3520 }
3521 else
3522 {
3523 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3524 rc = setError(rc,
3525 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
3526 aHD->i_getLocationFull().c_str());
3527 }
3528
3529 // fix the VM's lock list if anything failed
3530 if (FAILED(rc))
3531 {
3532 lockListVMMABegin = aVMMALockList->GetBegin();
3533 lockListVMMAEnd = aVMMALockList->GetEnd();
3534 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
3535 --lockListLast;
3536 for (MediumLockList::Base::iterator it = lockListVMMABegin;
3537 it != lockListVMMAEnd;
3538 ++it)
3539 {
3540 childLock.release();
3541 alock.release();
3542 it->UpdateLock(it == lockListLast);
3543 alock.acquire();
3544 childLock.acquire();
3545 ComObjPtr<Medium> pMedium = it->GetMedium();
3546 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3547 // blindly apply this, only needed for medium objects which
3548 // would be deleted as part of the merge
3549 pMedium->i_unmarkLockedForDeletion();
3550 }
3551 }
3552 }
3553 }
3554 else if (FAILED(rc))
3555 {
3556 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3557 rc = setError(rc,
3558 tr("Cannot lock hard disk '%s' when deleting a snapshot"),
3559 aHD->i_getLocationFull().c_str());
3560 }
3561
3562 return rc;
3563}
3564
3565/**
3566 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
3567 * what #prepareDeleteSnapshotMedium() did. Must be called if
3568 * #deleteSnapshotMedium() is not called or fails.
3569 *
3570 * @param aHD Hard disk which is connected to the snapshot.
3571 * @param aSource Source hard disk for merge.
3572 * @param aChildrenToReparent Children to unlock.
3573 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
3574 * @param aMediumLockList Medium locks to cancel.
3575 * @param aHDLockToken Optional write lock token for aHD.
3576 * @param aMachineId Machine id to attach the medium to.
3577 * @param aSnapshotId Snapshot id to attach the medium to.
3578 *
3579 * @note Locks the medium tree and the hard disks in the chain for writing.
3580 */
3581void SessionMachine::i_cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
3582 const ComObjPtr<Medium> &aSource,
3583 MediumLockList *aChildrenToReparent,
3584 bool fNeedsOnlineMerge,
3585 MediumLockList *aMediumLockList,
3586 const ComPtr<IToken> &aHDLockToken,
3587 const Guid &aMachineId,
3588 const Guid &aSnapshotId)
3589{
3590 if (aMediumLockList == NULL)
3591 {
3592 AutoMultiWriteLock2 mLock(&mParent->i_getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
3593
3594 Assert(aHD->i_getChildren().size() == 0);
3595
3596 if (aHD->i_getParent().isNull())
3597 {
3598 Assert(!aHDLockToken.isNull());
3599 if (!aHDLockToken.isNull())
3600 {
3601 HRESULT rc = aHDLockToken->Abandon();
3602 AssertComRC(rc);
3603 }
3604 }
3605 else
3606 {
3607 HRESULT rc = aHD->i_unmarkForDeletion();
3608 AssertComRC(rc);
3609 }
3610 }
3611 else
3612 {
3613 if (fNeedsOnlineMerge)
3614 {
3615 // Online merge uses the medium lock list of the VM, so give
3616 // an empty list to cancelMergeTo so that it works as designed.
3617 aSource->i_cancelMergeTo(aChildrenToReparent, new MediumLockList());
3618
3619 // clean up the VM medium lock list ourselves
3620 MediumLockList::Base::iterator lockListBegin =
3621 aMediumLockList->GetBegin();
3622 MediumLockList::Base::iterator lockListEnd =
3623 aMediumLockList->GetEnd();
3624 MediumLockList::Base::iterator lockListLast = lockListEnd;
3625 --lockListLast;
3626 for (MediumLockList::Base::iterator it = lockListBegin;
3627 it != lockListEnd;
3628 ++it)
3629 {
3630 ComObjPtr<Medium> pMedium = it->GetMedium();
3631 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
3632 if (pMedium->i_getState() == MediumState_Deleting)
3633 pMedium->i_unmarkForDeletion();
3634 else
3635 {
3636 // blindly apply this, only needed for medium objects which
3637 // would be deleted as part of the merge
3638 pMedium->i_unmarkLockedForDeletion();
3639 }
3640 mediumLock.release();
3641 it->UpdateLock(it == lockListLast);
3642 mediumLock.acquire();
3643 }
3644 }
3645 else
3646 {
3647 aSource->i_cancelMergeTo(aChildrenToReparent, aMediumLockList);
3648 }
3649 }
3650
3651 if (aMachineId.isValid() && !aMachineId.isZero())
3652 {
3653 // reattach the source media to the snapshot
3654 HRESULT rc = aSource->i_addBackReference(aMachineId, aSnapshotId);
3655 AssertComRC(rc);
3656 }
3657}
3658
3659/**
3660 * Perform an online merge of a hard disk, i.e. the equivalent of
3661 * Medium::mergeTo(), just for running VMs. If this fails you need to call
3662 * #cancelDeleteSnapshotMedium().
3663 *
3664 * @return COM status code
3665 * @param aMediumAttachment Identify where the disk is attached in the VM.
3666 * @param aSource Source hard disk for merge.
3667 * @param aTarget Target hard disk for merge.
3668 * @param fMergeForward Merge direction.
3669 * @param aParentForTarget New parent if target needs to be reparented.
3670 * @param aChildrenToReparent Medium lock list with children which have to be
3671 * reparented to the target.
3672 * @param aMediumLockList Where to store the created medium lock list (may
3673 * return NULL if no real merge is necessary).
3674 * @param aProgress Progress indicator.
3675 * @param pfNeedsMachineSaveSettings Whether the VM settings need to be saved (out).
3676 */
3677HRESULT SessionMachine::i_onlineMergeMedium(const ComObjPtr<MediumAttachment> &aMediumAttachment,
3678 const ComObjPtr<Medium> &aSource,
3679 const ComObjPtr<Medium> &aTarget,
3680 bool fMergeForward,
3681 const ComObjPtr<Medium> &aParentForTarget,
3682 MediumLockList *aChildrenToReparent,
3683 MediumLockList *aMediumLockList,
3684 ComObjPtr<Progress> &aProgress,
3685 bool *pfNeedsMachineSaveSettings)
3686{
3687 AssertReturn(aSource != NULL, E_FAIL);
3688 AssertReturn(aTarget != NULL, E_FAIL);
3689 AssertReturn(aSource != aTarget, E_FAIL);
3690 AssertReturn(aMediumLockList != NULL, E_FAIL);
3691 NOREF(fMergeForward);
3692 NOREF(aParentForTarget);
3693 NOREF(aChildrenToReparent);
3694
3695 HRESULT rc = S_OK;
3696
3697 try
3698 {
3699 // Similar code appears in Medium::taskMergeHandle, so
3700 // if you make any changes below check whether they are applicable
3701 // in that context as well.
3702
3703 unsigned uTargetIdx = (unsigned)-1;
3704 unsigned uSourceIdx = (unsigned)-1;
3705 /* Sanity check all hard disks in the chain. */
3706 MediumLockList::Base::iterator lockListBegin =
3707 aMediumLockList->GetBegin();
3708 MediumLockList::Base::iterator lockListEnd =
3709 aMediumLockList->GetEnd();
3710 unsigned i = 0;
3711 for (MediumLockList::Base::iterator it = lockListBegin;
3712 it != lockListEnd;
3713 ++it)
3714 {
3715 MediumLock &mediumLock = *it;
3716 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
3717
3718 if (pMedium == aSource)
3719 uSourceIdx = i;
3720 else if (pMedium == aTarget)
3721 uTargetIdx = i;
3722
3723 // In Medium::taskMergeHandler there is lots of consistency
3724 // checking which we cannot do here, as the state details are
3725 // impossible to get outside the Medium class. The locking should
3726 // have done the checks already.
3727
3728 i++;
3729 }
3730
3731 ComAssertThrow( uSourceIdx != (unsigned)-1
3732 && uTargetIdx != (unsigned)-1, E_FAIL);
3733
3734 ComPtr<IInternalSessionControl> directControl;
3735 {
3736 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3737
3738 if (mData->mSession.mState != SessionState_Locked)
3739 throw setError(VBOX_E_INVALID_VM_STATE,
3740 tr("Machine is not locked by a session (session state: %s)"),
3741 Global::stringifySessionState(mData->mSession.mState));
3742 directControl = mData->mSession.mDirectControl;
3743 }
3744
3745 // Must not hold any locks here, as this will call back to finish
3746 // updating the medium attachment, chain linking and state.
3747 rc = directControl->OnlineMergeMedium(aMediumAttachment,
3748 uSourceIdx, uTargetIdx,
3749 aProgress);
3750 if (FAILED(rc))
3751 throw rc;
3752 }
3753 catch (HRESULT aRC) { rc = aRC; }
3754
3755 // The callback mentioned above takes care of update the medium state
3756
3757 if (pfNeedsMachineSaveSettings)
3758 *pfNeedsMachineSaveSettings = true;
3759
3760 return rc;
3761}
3762
3763/**
3764 * Implementation for IInternalMachineControl::finishOnlineMergeMedium().
3765 *
3766 * Gets called after the successful completion of an online merge from
3767 * Console::onlineMergeMedium(), which gets invoked indirectly above in
3768 * the call to IInternalSessionControl::onlineMergeMedium.
3769 *
3770 * This updates the medium information and medium state so that the VM
3771 * can continue with the updated state of the medium chain.
3772 */
3773HRESULT SessionMachine::finishOnlineMergeMedium()
3774{
3775 HRESULT rc = S_OK;
3776 MediumDeleteRec *pDeleteRec = (MediumDeleteRec *)mConsoleTaskData.mDeleteSnapshotInfo;
3777 AssertReturn(pDeleteRec, E_FAIL);
3778 bool fSourceHasChildren = false;
3779
3780 // all hard disks but the target were successfully deleted by
3781 // the merge; reparent target if necessary and uninitialize media
3782
3783 AutoWriteLock treeLock(mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3784
3785 // Declare this here to make sure the object does not get uninitialized
3786 // before this method completes. Would normally happen as halfway through
3787 // we delete the last reference to the no longer existing medium object.
3788 ComObjPtr<Medium> targetChild;
3789
3790 if (pDeleteRec->mfMergeForward)
3791 {
3792 // first, unregister the target since it may become a base
3793 // hard disk which needs re-registration
3794 rc = mParent->i_unregisterMedium(pDeleteRec->mpTarget);
3795 AssertComRC(rc);
3796
3797 // then, reparent it and disconnect the deleted branch at
3798 // both ends (chain->parent() is source's parent)
3799 pDeleteRec->mpTarget->i_deparent();
3800 pDeleteRec->mpTarget->i_setParent(pDeleteRec->mpParentForTarget);
3801 if (pDeleteRec->mpParentForTarget)
3802 pDeleteRec->mpSource->i_deparent();
3803
3804 // then, register again
3805 rc = mParent->i_registerMedium(pDeleteRec->mpTarget, &pDeleteRec->mpTarget, treeLock);
3806 AssertComRC(rc);
3807 }
3808 else
3809 {
3810 Assert(pDeleteRec->mpTarget->i_getChildren().size() == 1);
3811 targetChild = pDeleteRec->mpTarget->i_getChildren().front();
3812
3813 // disconnect the deleted branch at the elder end
3814 targetChild->i_deparent();
3815
3816 // Update parent UUIDs of the source's children, reparent them and
3817 // disconnect the deleted branch at the younger end
3818 if (pDeleteRec->mpChildrenToReparent && !pDeleteRec->mpChildrenToReparent->IsEmpty())
3819 {
3820 fSourceHasChildren = true;
3821 // Fix the parent UUID of the images which needs to be moved to
3822 // underneath target. The running machine has the images opened,
3823 // but only for reading since the VM is paused. If anything fails
3824 // we must continue. The worst possible result is that the images
3825 // need manual fixing via VBoxManage to adjust the parent UUID.
3826 treeLock.release();
3827 pDeleteRec->mpTarget->i_fixParentUuidOfChildren(pDeleteRec->mpChildrenToReparent);
3828 // The childen are still write locked, unlock them now and don't
3829 // rely on the destructor doing it very late.
3830 pDeleteRec->mpChildrenToReparent->Unlock();
3831 treeLock.acquire();
3832
3833 // obey {parent,child} lock order
3834 AutoWriteLock sourceLock(pDeleteRec->mpSource COMMA_LOCKVAL_SRC_POS);
3835
3836 MediumLockList::Base::iterator childrenBegin = pDeleteRec->mpChildrenToReparent->GetBegin();
3837 MediumLockList::Base::iterator childrenEnd = pDeleteRec->mpChildrenToReparent->GetEnd();
3838 for (MediumLockList::Base::iterator it = childrenBegin;
3839 it != childrenEnd;
3840 ++it)
3841 {
3842 Medium *pMedium = it->GetMedium();
3843 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
3844
3845 pMedium->i_deparent(); // removes pMedium from source
3846 pMedium->i_setParent(pDeleteRec->mpTarget);
3847 }
3848 }
3849 }
3850
3851 /* unregister and uninitialize all hard disks removed by the merge */
3852 MediumLockList *pMediumLockList = NULL;
3853 rc = mData->mSession.mLockedMedia.Get(pDeleteRec->mpOnlineMediumAttachment, pMediumLockList);
3854 const ComObjPtr<Medium> &pLast = pDeleteRec->mfMergeForward ? pDeleteRec->mpTarget : pDeleteRec->mpSource;
3855 AssertReturn(SUCCEEDED(rc) && pMediumLockList, E_FAIL);
3856 MediumLockList::Base::iterator lockListBegin =
3857 pMediumLockList->GetBegin();
3858 MediumLockList::Base::iterator lockListEnd =
3859 pMediumLockList->GetEnd();
3860 for (MediumLockList::Base::iterator it = lockListBegin;
3861 it != lockListEnd;
3862 )
3863 {
3864 MediumLock &mediumLock = *it;
3865 /* Create a real copy of the medium pointer, as the medium
3866 * lock deletion below would invalidate the referenced object. */
3867 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
3868
3869 /* The target and all images not merged (readonly) are skipped */
3870 if ( pMedium == pDeleteRec->mpTarget
3871 || pMedium->i_getState() == MediumState_LockedRead)
3872 {
3873 ++it;
3874 }
3875 else
3876 {
3877 rc = mParent->i_unregisterMedium(pMedium);
3878 AssertComRC(rc);
3879
3880 /* now, uninitialize the deleted hard disk (note that
3881 * due to the Deleting state, uninit() will not touch
3882 * the parent-child relationship so we need to
3883 * uninitialize each disk individually) */
3884
3885 /* note that the operation initiator hard disk (which is
3886 * normally also the source hard disk) is a special case
3887 * -- there is one more caller added by Task to it which
3888 * we must release. Also, if we are in sync mode, the
3889 * caller may still hold an AutoCaller instance for it
3890 * and therefore we cannot uninit() it (it's therefore
3891 * the caller's responsibility) */
3892 if (pMedium == pDeleteRec->mpSource)
3893 {
3894 Assert(pDeleteRec->mpSource->i_getChildren().size() == 0);
3895 Assert(pDeleteRec->mpSource->i_getFirstMachineBackrefId() == NULL);
3896 }
3897
3898 /* Delete the medium lock list entry, which also releases the
3899 * caller added by MergeChain before uninit() and updates the
3900 * iterator to point to the right place. */
3901 rc = pMediumLockList->RemoveByIterator(it);
3902 AssertComRC(rc);
3903
3904 treeLock.release();
3905 pMedium->uninit();
3906 treeLock.acquire();
3907 }
3908
3909 /* Stop as soon as we reached the last medium affected by the merge.
3910 * The remaining images must be kept unchanged. */
3911 if (pMedium == pLast)
3912 break;
3913 }
3914
3915 /* Could be in principle folded into the previous loop, but let's keep
3916 * things simple. Update the medium locking to be the standard state:
3917 * all parent images locked for reading, just the last diff for writing. */
3918 lockListBegin = pMediumLockList->GetBegin();
3919 lockListEnd = pMediumLockList->GetEnd();
3920 MediumLockList::Base::iterator lockListLast = lockListEnd;
3921 --lockListLast;
3922 for (MediumLockList::Base::iterator it = lockListBegin;
3923 it != lockListEnd;
3924 ++it)
3925 {
3926 it->UpdateLock(it == lockListLast);
3927 }
3928
3929 /* If this is a backwards merge of the only remaining snapshot (i.e. the
3930 * source has no children) then update the medium associated with the
3931 * attachment, as the previously associated one (source) is now deleted.
3932 * Without the immediate update the VM could not continue running. */
3933 if (!pDeleteRec->mfMergeForward && !fSourceHasChildren)
3934 {
3935 AutoWriteLock attLock(pDeleteRec->mpOnlineMediumAttachment COMMA_LOCKVAL_SRC_POS);
3936 pDeleteRec->mpOnlineMediumAttachment->i_updateMedium(pDeleteRec->mpTarget);
3937 }
3938
3939 return S_OK;
3940}
3941
Note: See TracBrowser for help on using the repository browser.

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