VirtualBox

source: vbox/trunk/src/VBox/Main/SnapshotImpl.cpp@ 28774

Last change on this file since 28774 was 28774, checked in by vboxsync, 15 years ago

Main: mark machine as dirty when snapshot name or description are changed

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 101.3 KB
Line 
1/* $Id: SnapshotImpl.cpp 28774 2010-04-26 17:23:41Z vboxsync $ */
2
3/** @file
4 *
5 * COM class implementation for Snapshot and SnapshotMachine in VBoxSVC.
6 */
7
8/*
9 * Copyright (C) 2006-2010 Sun Microsystems, Inc.
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.215389.xyz. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
20 * Clara, CA 95054 USA or visit http://www.sun.com if you need
21 * additional information or have any questions.
22 */
23
24#include "Logging.h"
25#include "SnapshotImpl.h"
26
27#include "MachineImpl.h"
28#include "MediumImpl.h"
29#include "Global.h"
30#include "ProgressImpl.h"
31
32// @todo these three includes are required for about one or two lines, try
33// to remove them and put that code in shared code in MachineImplcpp
34#include "SharedFolderImpl.h"
35#include "USBControllerImpl.h"
36#include "VirtualBoxImpl.h"
37
38#include "AutoCaller.h"
39
40#include <iprt/path.h>
41#include <VBox/param.h>
42#include <VBox/err.h>
43
44#include <VBox/settings.h>
45
46////////////////////////////////////////////////////////////////////////////////
47//
48// Globals
49//
50////////////////////////////////////////////////////////////////////////////////
51
52/**
53 * Progress callback handler for lengthy operations
54 * (corresponds to the FNRTPROGRESS typedef).
55 *
56 * @param uPercentage Completetion precentage (0-100).
57 * @param pvUser Pointer to the Progress instance.
58 */
59static DECLCALLBACK(int) progressCallback(unsigned uPercentage, void *pvUser)
60{
61 IProgress *progress = static_cast<IProgress*>(pvUser);
62
63 /* update the progress object */
64 if (progress)
65 progress->SetCurrentOperationProgress(uPercentage);
66
67 return VINF_SUCCESS;
68}
69
70////////////////////////////////////////////////////////////////////////////////
71//
72// Snapshot private data definition
73//
74////////////////////////////////////////////////////////////////////////////////
75
76typedef std::list< ComObjPtr<Snapshot> > SnapshotsList;
77
78struct Snapshot::Data
79{
80 Data()
81 : pVirtualBox(NULL)
82 {
83 RTTimeSpecSetMilli(&timeStamp, 0);
84 };
85
86 ~Data()
87 {}
88
89 const Guid uuid;
90 Utf8Str strName;
91 Utf8Str strDescription;
92 RTTIMESPEC timeStamp;
93 ComObjPtr<SnapshotMachine> pMachine;
94
95 /** weak VirtualBox parent */
96 VirtualBox * const pVirtualBox;
97
98 // pParent and llChildren are protected by Machine::snapshotsTreeLockHandle()
99 ComObjPtr<Snapshot> pParent;
100 SnapshotsList llChildren;
101};
102
103////////////////////////////////////////////////////////////////////////////////
104//
105// Constructor / destructor
106//
107////////////////////////////////////////////////////////////////////////////////
108
109HRESULT Snapshot::FinalConstruct()
110{
111 LogFlowThisFunc(("\n"));
112 return S_OK;
113}
114
115void Snapshot::FinalRelease()
116{
117 LogFlowThisFunc(("\n"));
118 uninit();
119}
120
121/**
122 * Initializes the instance
123 *
124 * @param aId id of the snapshot
125 * @param aName name of the snapshot
126 * @param aDescription name of the snapshot (NULL if no description)
127 * @param aTimeStamp timestamp of the snapshot, in ms since 1970-01-01 UTC
128 * @param aMachine machine associated with this snapshot
129 * @param aParent parent snapshot (NULL if no parent)
130 */
131HRESULT Snapshot::init(VirtualBox *aVirtualBox,
132 const Guid &aId,
133 const Utf8Str &aName,
134 const Utf8Str &aDescription,
135 const RTTIMESPEC &aTimeStamp,
136 SnapshotMachine *aMachine,
137 Snapshot *aParent)
138{
139 LogFlowThisFunc(("uuid=%s aParent->uuid=%s\n", aId.toString().c_str(), (aParent) ? aParent->m->uuid.toString().c_str() : ""));
140
141 ComAssertRet(!aId.isEmpty() && !aName.isEmpty() && aMachine, E_INVALIDARG);
142
143 /* Enclose the state transition NotReady->InInit->Ready */
144 AutoInitSpan autoInitSpan(this);
145 AssertReturn(autoInitSpan.isOk(), E_FAIL);
146
147 m = new Data;
148
149 /* share parent weakly */
150 unconst(m->pVirtualBox) = aVirtualBox;
151
152 m->pParent = aParent;
153
154 unconst(m->uuid) = aId;
155 m->strName = aName;
156 m->strDescription = aDescription;
157 m->timeStamp = aTimeStamp;
158 m->pMachine = aMachine;
159
160 if (aParent)
161 aParent->m->llChildren.push_back(this);
162
163 /* Confirm a successful initialization when it's the case */
164 autoInitSpan.setSucceeded();
165
166 return S_OK;
167}
168
169/**
170 * Uninitializes the instance and sets the ready flag to FALSE.
171 * Called either from FinalRelease(), by the parent when it gets destroyed,
172 * or by a third party when it decides this object is no more valid.
173 *
174 * Since this manipulates the snapshots tree, the caller must hold the
175 * machine lock in write mode (which protects the snapshots tree)!
176 */
177void Snapshot::uninit()
178{
179 LogFlowThisFunc(("\n"));
180
181 /* Enclose the state transition Ready->InUninit->NotReady */
182 AutoUninitSpan autoUninitSpan(this);
183 if (autoUninitSpan.uninitDone())
184 return;
185
186 Assert(m->pMachine->isWriteLockOnCurrentThread());
187
188 // uninit all children
189 SnapshotsList::iterator it;
190 for (it = m->llChildren.begin();
191 it != m->llChildren.end();
192 ++it)
193 {
194 Snapshot *pChild = *it;
195 pChild->m->pParent.setNull();
196 pChild->uninit();
197 }
198 m->llChildren.clear(); // this unsets all the ComPtrs and probably calls delete
199
200 if (m->pParent)
201 deparent();
202
203 if (m->pMachine)
204 {
205 m->pMachine->uninit();
206 m->pMachine.setNull();
207 }
208
209 delete m;
210 m = NULL;
211}
212
213/**
214 * Delete the current snapshot by removing it from the tree of snapshots
215 * and reparenting its children.
216 *
217 * After this, the caller must call uninit() on the snapshot. We can't call
218 * that from here because if we do, the AutoUninitSpan waits forever for
219 * the number of callers to become 0 (it is 1 because of the AutoCaller in here).
220 *
221 * NOTE: this does NOT lock the snapshot, it is assumed that the machine state
222 * (and the snapshots tree) is protected by the caller having requested the machine
223 * lock in write mode AND the machine state must be DeletingSnapshot.
224 */
225void Snapshot::beginSnapshotDelete()
226{
227 AutoCaller autoCaller(this);
228 if (FAILED(autoCaller.rc()))
229 return;
230
231 // caller must have acquired the machine's write lock
232 Assert(m->pMachine->mData->mMachineState == MachineState_DeletingSnapshot);
233 Assert(m->pMachine->isWriteLockOnCurrentThread());
234
235 // the snapshot must have only one child when being deleted or no children at all
236 AssertReturnVoid(m->llChildren.size() <= 1);
237
238 ComObjPtr<Snapshot> parentSnapshot = m->pParent;
239
240 /// @todo (dmik):
241 // when we introduce clones later, deleting the snapshot will affect
242 // the current and first snapshots of clones, if they are direct children
243 // of this snapshot. So we will need to lock machines associated with
244 // child snapshots as well and update mCurrentSnapshot and/or
245 // mFirstSnapshot fields.
246
247 if (this == m->pMachine->mData->mCurrentSnapshot)
248 {
249 m->pMachine->mData->mCurrentSnapshot = parentSnapshot;
250
251 /* we've changed the base of the current state so mark it as
252 * modified as it no longer guaranteed to be its copy */
253 m->pMachine->mData->mCurrentStateModified = TRUE;
254 }
255
256 if (this == m->pMachine->mData->mFirstSnapshot)
257 {
258 if (m->llChildren.size() == 1)
259 {
260 ComObjPtr<Snapshot> childSnapshot = m->llChildren.front();
261 m->pMachine->mData->mFirstSnapshot = childSnapshot;
262 }
263 else
264 m->pMachine->mData->mFirstSnapshot.setNull();
265 }
266
267 // reparent our children
268 for (SnapshotsList::const_iterator it = m->llChildren.begin();
269 it != m->llChildren.end();
270 ++it)
271 {
272 ComObjPtr<Snapshot> child = *it;
273 // no need to lock, snapshots tree is protected by machine lock
274 child->m->pParent = m->pParent;
275 if (m->pParent)
276 m->pParent->m->llChildren.push_back(child);
277 }
278
279 // clear our own children list (since we reparented the children)
280 m->llChildren.clear();
281}
282
283/**
284 * Internal helper that removes "this" from the list of children of its
285 * parent. Used in uninit() and other places when reparenting is necessary.
286 *
287 * The caller must hold the machine lock in write mode (which protects the snapshots tree)!
288 */
289void Snapshot::deparent()
290{
291 Assert(m->pMachine->isWriteLockOnCurrentThread());
292
293 SnapshotsList &llParent = m->pParent->m->llChildren;
294 for (SnapshotsList::iterator it = llParent.begin();
295 it != llParent.end();
296 ++it)
297 {
298 Snapshot *pParentsChild = *it;
299 if (this == pParentsChild)
300 {
301 llParent.erase(it);
302 break;
303 }
304 }
305
306 m->pParent.setNull();
307}
308
309////////////////////////////////////////////////////////////////////////////////
310//
311// ISnapshot public methods
312//
313////////////////////////////////////////////////////////////////////////////////
314
315STDMETHODIMP Snapshot::COMGETTER(Id)(BSTR *aId)
316{
317 CheckComArgOutPointerValid(aId);
318
319 AutoCaller autoCaller(this);
320 if (FAILED(autoCaller.rc())) return autoCaller.rc();
321
322 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
323
324 m->uuid.toUtf16().cloneTo(aId);
325 return S_OK;
326}
327
328STDMETHODIMP Snapshot::COMGETTER(Name)(BSTR *aName)
329{
330 CheckComArgOutPointerValid(aName);
331
332 AutoCaller autoCaller(this);
333 if (FAILED(autoCaller.rc())) return autoCaller.rc();
334
335 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
336
337 m->strName.cloneTo(aName);
338 return S_OK;
339}
340
341/**
342 * @note Locks this object for writing, then calls Machine::onSnapshotChange()
343 * (see its lock requirements).
344 */
345STDMETHODIMP Snapshot::COMSETTER(Name)(IN_BSTR aName)
346{
347 CheckComArgStrNotEmptyOrNull(aName);
348
349 AutoCaller autoCaller(this);
350 if (FAILED(autoCaller.rc())) return autoCaller.rc();
351
352 Utf8Str strName(aName);
353
354 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
355
356 if (m->strName != strName)
357 {
358 m->strName = strName;
359
360 alock.leave(); /* Important! (child->parent locks are forbidden) */
361
362 // flag the machine as dirty or change won't get saved
363 AutoWriteLock mlock(m->pMachine COMMA_LOCKVAL_SRC_POS);
364 m->pMachine->setModified(Machine::IsModified_Snapshots);
365 mlock.leave();
366
367 return m->pMachine->onSnapshotChange(this);
368 }
369
370 return S_OK;
371}
372
373STDMETHODIMP Snapshot::COMGETTER(Description)(BSTR *aDescription)
374{
375 CheckComArgOutPointerValid(aDescription);
376
377 AutoCaller autoCaller(this);
378 if (FAILED(autoCaller.rc())) return autoCaller.rc();
379
380 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
381
382 m->strDescription.cloneTo(aDescription);
383 return S_OK;
384}
385
386STDMETHODIMP Snapshot::COMSETTER(Description)(IN_BSTR aDescription)
387{
388 AutoCaller autoCaller(this);
389 if (FAILED(autoCaller.rc())) return autoCaller.rc();
390
391 Utf8Str strDescription(aDescription);
392
393 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
394
395 if (m->strDescription != strDescription)
396 {
397 m->strDescription = strDescription;
398
399 alock.leave(); /* Important! (child->parent locks are forbidden) */
400
401 // flag the machine as dirty or change won't get saved
402 AutoWriteLock mlock(m->pMachine COMMA_LOCKVAL_SRC_POS);
403 m->pMachine->setModified(Machine::IsModified_Snapshots);
404 mlock.leave();
405
406 return m->pMachine->onSnapshotChange(this);
407 }
408
409 return S_OK;
410}
411
412STDMETHODIMP Snapshot::COMGETTER(TimeStamp)(LONG64 *aTimeStamp)
413{
414 CheckComArgOutPointerValid(aTimeStamp);
415
416 AutoCaller autoCaller(this);
417 if (FAILED(autoCaller.rc())) return autoCaller.rc();
418
419 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
420
421 *aTimeStamp = RTTimeSpecGetMilli(&m->timeStamp);
422 return S_OK;
423}
424
425STDMETHODIMP Snapshot::COMGETTER(Online)(BOOL *aOnline)
426{
427 CheckComArgOutPointerValid(aOnline);
428
429 AutoCaller autoCaller(this);
430 if (FAILED(autoCaller.rc())) return autoCaller.rc();
431
432 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
433
434 *aOnline = !stateFilePath().isEmpty();
435 return S_OK;
436}
437
438STDMETHODIMP Snapshot::COMGETTER(Machine)(IMachine **aMachine)
439{
440 CheckComArgOutPointerValid(aMachine);
441
442 AutoCaller autoCaller(this);
443 if (FAILED(autoCaller.rc())) return autoCaller.rc();
444
445 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
446
447 m->pMachine.queryInterfaceTo(aMachine);
448 return S_OK;
449}
450
451STDMETHODIMP Snapshot::COMGETTER(Parent)(ISnapshot **aParent)
452{
453 CheckComArgOutPointerValid(aParent);
454
455 AutoCaller autoCaller(this);
456 if (FAILED(autoCaller.rc())) return autoCaller.rc();
457
458 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
459
460 m->pParent.queryInterfaceTo(aParent);
461 return S_OK;
462}
463
464STDMETHODIMP Snapshot::COMGETTER(Children)(ComSafeArrayOut(ISnapshot *, aChildren))
465{
466 CheckComArgOutSafeArrayPointerValid(aChildren);
467
468 AutoCaller autoCaller(this);
469 if (FAILED(autoCaller.rc())) return autoCaller.rc();
470
471 // snapshots tree is protected by machine lock
472 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
473
474 SafeIfaceArray<ISnapshot> collection(m->llChildren);
475 collection.detachTo(ComSafeArrayOutArg(aChildren));
476
477 return S_OK;
478}
479
480////////////////////////////////////////////////////////////////////////////////
481//
482// Snapshot public internal methods
483//
484////////////////////////////////////////////////////////////////////////////////
485
486/**
487 * Returns the parent snapshot or NULL if there's none. Must have caller + locking!
488 * @return
489 */
490const ComObjPtr<Snapshot>& Snapshot::getParent() const
491{
492 return m->pParent;
493}
494
495/**
496 * @note
497 * Must be called from under the object's lock!
498 */
499const Utf8Str& Snapshot::stateFilePath() const
500{
501 return m->pMachine->mSSData->mStateFilePath;
502}
503
504/**
505 * @note
506 * Must be called from under the object's write lock!
507 */
508HRESULT Snapshot::deleteStateFile()
509{
510 int vrc = RTFileDelete(m->pMachine->mSSData->mStateFilePath.raw());
511 if (RT_SUCCESS(vrc))
512 m->pMachine->mSSData->mStateFilePath.setNull();
513 return RT_SUCCESS(vrc) ? S_OK : E_FAIL;
514}
515
516/**
517 * Returns the number of direct child snapshots, without grandchildren.
518 * Does not recurse.
519 * @return
520 */
521ULONG Snapshot::getChildrenCount()
522{
523 AutoCaller autoCaller(this);
524 AssertComRC(autoCaller.rc());
525
526 // snapshots tree is protected by machine lock
527 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
528
529 return (ULONG)m->llChildren.size();
530}
531
532/**
533 * Implementation method for getAllChildrenCount() so we request the
534 * tree lock only once before recursing. Don't call directly.
535 * @return
536 */
537ULONG Snapshot::getAllChildrenCountImpl()
538{
539 AutoCaller autoCaller(this);
540 AssertComRC(autoCaller.rc());
541
542 ULONG count = (ULONG)m->llChildren.size();
543 for (SnapshotsList::const_iterator it = m->llChildren.begin();
544 it != m->llChildren.end();
545 ++it)
546 {
547 count += (*it)->getAllChildrenCountImpl();
548 }
549
550 return count;
551}
552
553/**
554 * Returns the number of child snapshots including all grandchildren.
555 * Recurses into the snapshots tree.
556 * @return
557 */
558ULONG Snapshot::getAllChildrenCount()
559{
560 AutoCaller autoCaller(this);
561 AssertComRC(autoCaller.rc());
562
563 // snapshots tree is protected by machine lock
564 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
565
566 return getAllChildrenCountImpl();
567}
568
569/**
570 * Returns the SnapshotMachine that this snapshot belongs to.
571 * Caller must hold the snapshot's object lock!
572 * @return
573 */
574const ComObjPtr<SnapshotMachine>& Snapshot::getSnapshotMachine() const
575{
576 return m->pMachine;
577}
578
579/**
580 * Returns the UUID of this snapshot.
581 * Caller must hold the snapshot's object lock!
582 * @return
583 */
584Guid Snapshot::getId() const
585{
586 return m->uuid;
587}
588
589/**
590 * Returns the name of this snapshot.
591 * Caller must hold the snapshot's object lock!
592 * @return
593 */
594const Utf8Str& Snapshot::getName() const
595{
596 return m->strName;
597}
598
599/**
600 * Returns the time stamp of this snapshot.
601 * Caller must hold the snapshot's object lock!
602 * @return
603 */
604RTTIMESPEC Snapshot::getTimeStamp() const
605{
606 return m->timeStamp;
607}
608
609/**
610 * Searches for a snapshot with the given ID among children, grand-children,
611 * etc. of this snapshot. This snapshot itself is also included in the search.
612 *
613 * Caller must hold the machine lock (which protects the snapshots tree!)
614 */
615ComObjPtr<Snapshot> Snapshot::findChildOrSelf(IN_GUID aId)
616{
617 ComObjPtr<Snapshot> child;
618
619 AutoCaller autoCaller(this);
620 AssertComRC(autoCaller.rc());
621
622 // no need to lock, uuid is const
623 if (m->uuid == aId)
624 child = this;
625 else
626 {
627 for (SnapshotsList::const_iterator it = m->llChildren.begin();
628 it != m->llChildren.end();
629 ++it)
630 {
631 if ((child = (*it)->findChildOrSelf(aId)))
632 break;
633 }
634 }
635
636 return child;
637}
638
639/**
640 * Searches for a first snapshot with the given name among children,
641 * grand-children, etc. of this snapshot. This snapshot itself is also included
642 * in the search.
643 *
644 * Caller must hold the machine lock (which protects the snapshots tree!)
645 */
646ComObjPtr<Snapshot> Snapshot::findChildOrSelf(const Utf8Str &aName)
647{
648 ComObjPtr<Snapshot> child;
649 AssertReturn(!aName.isEmpty(), child);
650
651 AutoCaller autoCaller(this);
652 AssertComRC(autoCaller.rc());
653
654 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
655
656 if (m->strName == aName)
657 child = this;
658 else
659 {
660 alock.release();
661 for (SnapshotsList::const_iterator it = m->llChildren.begin();
662 it != m->llChildren.end();
663 ++it)
664 {
665 if ((child = (*it)->findChildOrSelf(aName)))
666 break;
667 }
668 }
669
670 return child;
671}
672
673/**
674 * Internal implementation for Snapshot::updateSavedStatePaths (below).
675 * @param aOldPath
676 * @param aNewPath
677 */
678void Snapshot::updateSavedStatePathsImpl(const char *aOldPath, const char *aNewPath)
679{
680 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
681
682 const Utf8Str &path = m->pMachine->mSSData->mStateFilePath;
683 LogFlowThisFunc(("Snap[%s].statePath={%s}\n", m->strName.c_str(), path.c_str()));
684
685 /* state file may be NULL (for offline snapshots) */
686 if ( path.length()
687 && RTPathStartsWith(path.c_str(), aOldPath)
688 )
689 {
690 m->pMachine->mSSData->mStateFilePath = Utf8StrFmt("%s%s", aNewPath, path.raw() + strlen(aOldPath));
691
692 LogFlowThisFunc(("-> updated: {%s}\n", path.raw()));
693 }
694
695 for (SnapshotsList::const_iterator it = m->llChildren.begin();
696 it != m->llChildren.end();
697 ++it)
698 {
699 Snapshot *pChild = *it;
700 pChild->updateSavedStatePathsImpl(aOldPath, aNewPath);
701 }
702}
703
704/**
705 * Checks if the specified path change affects the saved state file path of
706 * this snapshot or any of its (grand-)children and updates it accordingly.
707 *
708 * Intended to be called by Machine::openConfigLoader() only.
709 *
710 * @param aOldPath old path (full)
711 * @param aNewPath new path (full)
712 *
713 * @note Locks the machine (for the snapshots tree) + this object + children for writing.
714 */
715void Snapshot::updateSavedStatePaths(const char *aOldPath, const char *aNewPath)
716{
717 LogFlowThisFunc(("aOldPath={%s} aNewPath={%s}\n", aOldPath, aNewPath));
718
719 AssertReturnVoid(aOldPath);
720 AssertReturnVoid(aNewPath);
721
722 AutoCaller autoCaller(this);
723 AssertComRC(autoCaller.rc());
724
725 // snapshots tree is protected by machine lock
726 AutoWriteLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
727
728 // call the implementation under the tree lock
729 updateSavedStatePathsImpl(aOldPath, aNewPath);
730}
731
732/**
733 * Internal implementation for Snapshot::saveSnapshot (below). Caller has
734 * requested the snapshots tree (machine) lock.
735 *
736 * @param aNode
737 * @param aAttrsOnly
738 * @return
739 */
740HRESULT Snapshot::saveSnapshotImpl(settings::Snapshot &data, bool aAttrsOnly)
741{
742 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
743
744 data.uuid = m->uuid;
745 data.strName = m->strName;
746 data.timestamp = m->timeStamp;
747 data.strDescription = m->strDescription;
748
749 if (aAttrsOnly)
750 return S_OK;
751
752 /* stateFile (optional) */
753 if (!stateFilePath().isEmpty())
754 /* try to make the file name relative to the settings file dir */
755 m->pMachine->calculateRelativePath(stateFilePath(), data.strStateFile);
756 else
757 data.strStateFile.setNull();
758
759 HRESULT rc = m->pMachine->saveHardware(data.hardware);
760 if (FAILED(rc)) return rc;
761
762 rc = m->pMachine->saveStorageControllers(data.storage);
763 if (FAILED(rc)) return rc;
764
765 alock.release();
766
767 data.llChildSnapshots.clear();
768
769 if (m->llChildren.size())
770 {
771 for (SnapshotsList::const_iterator it = m->llChildren.begin();
772 it != m->llChildren.end();
773 ++it)
774 {
775 settings::Snapshot snap;
776 rc = (*it)->saveSnapshotImpl(snap, aAttrsOnly);
777 if (FAILED(rc)) return rc;
778
779 data.llChildSnapshots.push_back(snap);
780 }
781 }
782
783 return S_OK;
784}
785
786/**
787 * Saves the given snapshot and all its children (unless \a aAttrsOnly is true).
788 * It is assumed that the given node is empty (unless \a aAttrsOnly is true).
789 *
790 * @param aNode <Snapshot> node to save the snapshot to.
791 * @param aSnapshot Snapshot to save.
792 * @param aAttrsOnly If true, only updatge user-changeable attrs.
793 */
794HRESULT Snapshot::saveSnapshot(settings::Snapshot &data, bool aAttrsOnly)
795{
796 // snapshots tree is protected by machine lock
797 AutoReadLock alock(m->pMachine COMMA_LOCKVAL_SRC_POS);
798
799 return saveSnapshotImpl(data, aAttrsOnly);
800}
801
802////////////////////////////////////////////////////////////////////////////////
803//
804// SnapshotMachine implementation
805//
806////////////////////////////////////////////////////////////////////////////////
807
808DEFINE_EMPTY_CTOR_DTOR(SnapshotMachine)
809
810HRESULT SnapshotMachine::FinalConstruct()
811{
812 LogFlowThisFunc(("\n"));
813
814 return S_OK;
815}
816
817void SnapshotMachine::FinalRelease()
818{
819 LogFlowThisFunc(("\n"));
820
821 uninit();
822}
823
824/**
825 * Initializes the SnapshotMachine object when taking a snapshot.
826 *
827 * @param aSessionMachine machine to take a snapshot from
828 * @param aSnapshotId snapshot ID of this snapshot machine
829 * @param aStateFilePath file where the execution state will be later saved
830 * (or NULL for the offline snapshot)
831 *
832 * @note The aSessionMachine must be locked for writing.
833 */
834HRESULT SnapshotMachine::init(SessionMachine *aSessionMachine,
835 IN_GUID aSnapshotId,
836 const Utf8Str &aStateFilePath)
837{
838 LogFlowThisFuncEnter();
839 LogFlowThisFunc(("mName={%ls}\n", aSessionMachine->mUserData->mName.raw()));
840
841 AssertReturn(aSessionMachine && !Guid(aSnapshotId).isEmpty(), E_INVALIDARG);
842
843 /* Enclose the state transition NotReady->InInit->Ready */
844 AutoInitSpan autoInitSpan(this);
845 AssertReturn(autoInitSpan.isOk(), E_FAIL);
846
847 AssertReturn(aSessionMachine->isWriteLockOnCurrentThread(), E_FAIL);
848
849 mSnapshotId = aSnapshotId;
850
851 /* memorize the primary Machine instance (i.e. not SessionMachine!) */
852 unconst(mPeer) = aSessionMachine->mPeer;
853 /* share the parent pointer */
854 unconst(mParent) = mPeer->mParent;
855
856 /* take the pointer to Data to share */
857 mData.share(mPeer->mData);
858
859 /* take the pointer to UserData to share (our UserData must always be the
860 * same as Machine's data) */
861 mUserData.share(mPeer->mUserData);
862 /* make a private copy of all other data (recent changes from SessionMachine) */
863 mHWData.attachCopy(aSessionMachine->mHWData);
864 mMediaData.attachCopy(aSessionMachine->mMediaData);
865
866 /* SSData is always unique for SnapshotMachine */
867 mSSData.allocate();
868 mSSData->mStateFilePath = aStateFilePath;
869
870 HRESULT rc = S_OK;
871
872 /* create copies of all shared folders (mHWData after attiching a copy
873 * contains just references to original objects) */
874 for (HWData::SharedFolderList::iterator it = mHWData->mSharedFolders.begin();
875 it != mHWData->mSharedFolders.end();
876 ++it)
877 {
878 ComObjPtr<SharedFolder> folder;
879 folder.createObject();
880 rc = folder->initCopy(this, *it);
881 if (FAILED(rc)) return rc;
882 *it = folder;
883 }
884
885 /* associate hard disks with the snapshot
886 * (Machine::uninitDataAndChildObjects() will deassociate at destruction) */
887 for (MediaData::AttachmentList::const_iterator it = mMediaData->mAttachments.begin();
888 it != mMediaData->mAttachments.end();
889 ++it)
890 {
891 MediumAttachment *pAtt = *it;
892 Medium *pMedium = pAtt->getMedium();
893 if (pMedium) // can be NULL for non-harddisk
894 {
895 rc = pMedium->attachTo(mData->mUuid, mSnapshotId);
896 AssertComRC(rc);
897 }
898 }
899
900 /* create copies of all storage controllers (mStorageControllerData
901 * after attaching a copy contains just references to original objects) */
902 mStorageControllers.allocate();
903 for (StorageControllerList::const_iterator
904 it = aSessionMachine->mStorageControllers->begin();
905 it != aSessionMachine->mStorageControllers->end();
906 ++it)
907 {
908 ComObjPtr<StorageController> ctrl;
909 ctrl.createObject();
910 ctrl->initCopy(this, *it);
911 mStorageControllers->push_back(ctrl);
912 }
913
914 /* create all other child objects that will be immutable private copies */
915
916 unconst(mBIOSSettings).createObject();
917 mBIOSSettings->initCopy(this, mPeer->mBIOSSettings);
918
919#ifdef VBOX_WITH_VRDP
920 unconst(mVRDPServer).createObject();
921 mVRDPServer->initCopy(this, mPeer->mVRDPServer);
922#endif
923
924 unconst(mAudioAdapter).createObject();
925 mAudioAdapter->initCopy(this, mPeer->mAudioAdapter);
926
927 unconst(mUSBController).createObject();
928 mUSBController->initCopy(this, mPeer->mUSBController);
929
930 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
931 {
932 unconst(mNetworkAdapters[slot]).createObject();
933 mNetworkAdapters[slot]->initCopy(this, mPeer->mNetworkAdapters[slot]);
934 }
935
936 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
937 {
938 unconst(mSerialPorts[slot]).createObject();
939 mSerialPorts[slot]->initCopy(this, mPeer->mSerialPorts[slot]);
940 }
941
942 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
943 {
944 unconst(mParallelPorts[slot]).createObject();
945 mParallelPorts[slot]->initCopy(this, mPeer->mParallelPorts[slot]);
946 }
947
948 /* Confirm a successful initialization when it's the case */
949 autoInitSpan.setSucceeded();
950
951 LogFlowThisFuncLeave();
952 return S_OK;
953}
954
955/**
956 * Initializes the SnapshotMachine object when loading from the settings file.
957 *
958 * @param aMachine machine the snapshot belngs to
959 * @param aHWNode <Hardware> node
960 * @param aHDAsNode <HardDiskAttachments> node
961 * @param aSnapshotId snapshot ID of this snapshot machine
962 * @param aStateFilePath file where the execution state is saved
963 * (or NULL for the offline snapshot)
964 *
965 * @note Doesn't lock anything.
966 */
967HRESULT SnapshotMachine::init(Machine *aMachine,
968 const settings::Hardware &hardware,
969 const settings::Storage &storage,
970 IN_GUID aSnapshotId,
971 const Utf8Str &aStateFilePath)
972{
973 LogFlowThisFuncEnter();
974 LogFlowThisFunc(("mName={%ls}\n", aMachine->mUserData->mName.raw()));
975
976 AssertReturn(aMachine && !Guid(aSnapshotId).isEmpty(), E_INVALIDARG);
977
978 /* Enclose the state transition NotReady->InInit->Ready */
979 AutoInitSpan autoInitSpan(this);
980 AssertReturn(autoInitSpan.isOk(), E_FAIL);
981
982 /* Don't need to lock aMachine when VirtualBox is starting up */
983
984 mSnapshotId = aSnapshotId;
985
986 /* memorize the primary Machine instance */
987 unconst(mPeer) = aMachine;
988 /* share the parent pointer */
989 unconst(mParent) = mPeer->mParent;
990
991 /* take the pointer to Data to share */
992 mData.share(mPeer->mData);
993 /*
994 * take the pointer to UserData to share
995 * (our UserData must always be the same as Machine's data)
996 */
997 mUserData.share(mPeer->mUserData);
998 /* allocate private copies of all other data (will be loaded from settings) */
999 mHWData.allocate();
1000 mMediaData.allocate();
1001 mStorageControllers.allocate();
1002
1003 /* SSData is always unique for SnapshotMachine */
1004 mSSData.allocate();
1005 mSSData->mStateFilePath = aStateFilePath;
1006
1007 /* create all other child objects that will be immutable private copies */
1008
1009 unconst(mBIOSSettings).createObject();
1010 mBIOSSettings->init(this);
1011
1012#ifdef VBOX_WITH_VRDP
1013 unconst(mVRDPServer).createObject();
1014 mVRDPServer->init(this);
1015#endif
1016
1017 unconst(mAudioAdapter).createObject();
1018 mAudioAdapter->init(this);
1019
1020 unconst(mUSBController).createObject();
1021 mUSBController->init(this);
1022
1023 for (ULONG slot = 0; slot < RT_ELEMENTS(mNetworkAdapters); slot++)
1024 {
1025 unconst(mNetworkAdapters[slot]).createObject();
1026 mNetworkAdapters[slot]->init(this, slot);
1027 }
1028
1029 for (ULONG slot = 0; slot < RT_ELEMENTS(mSerialPorts); slot++)
1030 {
1031 unconst(mSerialPorts[slot]).createObject();
1032 mSerialPorts[slot]->init(this, slot);
1033 }
1034
1035 for (ULONG slot = 0; slot < RT_ELEMENTS(mParallelPorts); slot++)
1036 {
1037 unconst(mParallelPorts[slot]).createObject();
1038 mParallelPorts[slot]->init(this, slot);
1039 }
1040
1041 /* load hardware and harddisk settings */
1042
1043 HRESULT rc = loadHardware(hardware);
1044 if (SUCCEEDED(rc))
1045 rc = loadStorageControllers(storage, &mSnapshotId);
1046
1047 if (SUCCEEDED(rc))
1048 /* commit all changes made during the initialization */
1049 commit(); // @todo r=dj why do we need a commit in init?!? this is very expensive
1050
1051 /* Confirm a successful initialization when it's the case */
1052 if (SUCCEEDED(rc))
1053 autoInitSpan.setSucceeded();
1054
1055 LogFlowThisFuncLeave();
1056 return rc;
1057}
1058
1059/**
1060 * Uninitializes this SnapshotMachine object.
1061 */
1062void SnapshotMachine::uninit()
1063{
1064 LogFlowThisFuncEnter();
1065
1066 /* Enclose the state transition Ready->InUninit->NotReady */
1067 AutoUninitSpan autoUninitSpan(this);
1068 if (autoUninitSpan.uninitDone())
1069 return;
1070
1071 uninitDataAndChildObjects();
1072
1073 /* free the essential data structure last */
1074 mData.free();
1075
1076 unconst(mParent) = NULL;
1077 unconst(mPeer) = NULL;
1078
1079 LogFlowThisFuncLeave();
1080}
1081
1082/**
1083 * Overrides VirtualBoxBase::lockHandle() in order to share the lock handle
1084 * with the primary Machine instance (mPeer).
1085 */
1086RWLockHandle *SnapshotMachine::lockHandle() const
1087{
1088 AssertReturn(mPeer != NULL, NULL);
1089 return mPeer->lockHandle();
1090}
1091
1092////////////////////////////////////////////////////////////////////////////////
1093//
1094// SnapshotMachine public internal methods
1095//
1096////////////////////////////////////////////////////////////////////////////////
1097
1098/**
1099 * Called by the snapshot object associated with this SnapshotMachine when
1100 * snapshot data such as name or description is changed.
1101 *
1102 * @note Locks this object for writing.
1103 */
1104HRESULT SnapshotMachine::onSnapshotChange(Snapshot *aSnapshot)
1105{
1106 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1107
1108 // mPeer->saveAllSnapshots(); @todo
1109
1110 /* inform callbacks */
1111 mParent->onSnapshotChange(mData->mUuid, aSnapshot->getId());
1112
1113 return S_OK;
1114}
1115
1116////////////////////////////////////////////////////////////////////////////////
1117//
1118// SessionMachine task records
1119//
1120////////////////////////////////////////////////////////////////////////////////
1121
1122/**
1123 * Abstract base class for SessionMachine::RestoreSnapshotTask and
1124 * SessionMachine::DeleteSnapshotTask. This is necessary since
1125 * RTThreadCreate cannot call a method as its thread function, so
1126 * instead we have it call the static SessionMachine::taskHandler,
1127 * which can then call the handler() method in here (implemented
1128 * by the children).
1129 */
1130struct SessionMachine::SnapshotTask
1131{
1132 SnapshotTask(SessionMachine *m,
1133 Progress *p,
1134 Snapshot *s)
1135 : pMachine(m),
1136 pProgress(p),
1137 machineStateBackup(m->mData->mMachineState), // save the current machine state
1138 pSnapshot(s)
1139 {}
1140
1141 void modifyBackedUpState(MachineState_T s)
1142 {
1143 *const_cast<MachineState_T*>(&machineStateBackup) = s;
1144 }
1145
1146 virtual void handler() = 0;
1147
1148 ComObjPtr<SessionMachine> pMachine;
1149 ComObjPtr<Progress> pProgress;
1150 const MachineState_T machineStateBackup;
1151 ComObjPtr<Snapshot> pSnapshot;
1152};
1153
1154/** Restore snapshot state task */
1155struct SessionMachine::RestoreSnapshotTask
1156 : public SessionMachine::SnapshotTask
1157{
1158 RestoreSnapshotTask(SessionMachine *m,
1159 Progress *p,
1160 Snapshot *s,
1161 ULONG ulStateFileSizeMB)
1162 : SnapshotTask(m, p, s),
1163 m_ulStateFileSizeMB(ulStateFileSizeMB)
1164 {}
1165
1166 void handler()
1167 {
1168 pMachine->restoreSnapshotHandler(*this);
1169 }
1170
1171 ULONG m_ulStateFileSizeMB;
1172};
1173
1174/** Delete snapshot task */
1175struct SessionMachine::DeleteSnapshotTask
1176 : public SessionMachine::SnapshotTask
1177{
1178 DeleteSnapshotTask(SessionMachine *m,
1179 Progress *p,
1180 bool fDeleteOnline,
1181 Snapshot *s)
1182 : SnapshotTask(m, p, s),
1183 m_fDeleteOnline(fDeleteOnline)
1184 {}
1185
1186 void handler()
1187 {
1188 pMachine->deleteSnapshotHandler(*this);
1189 }
1190
1191 bool m_fDeleteOnline;
1192};
1193
1194/**
1195 * Static SessionMachine method that can get passed to RTThreadCreate to
1196 * have a thread started for a SnapshotTask. See SnapshotTask above.
1197 *
1198 * This calls either RestoreSnapshotTask::handler() or DeleteSnapshotTask::handler().
1199 */
1200
1201/* static */ DECLCALLBACK(int) SessionMachine::taskHandler(RTTHREAD /* thread */, void *pvUser)
1202{
1203 AssertReturn(pvUser, VERR_INVALID_POINTER);
1204
1205 SnapshotTask *task = static_cast<SnapshotTask*>(pvUser);
1206 task->handler();
1207
1208 // it's our responsibility to delete the task
1209 delete task;
1210
1211 return 0;
1212}
1213
1214////////////////////////////////////////////////////////////////////////////////
1215//
1216// TakeSnapshot methods (SessionMachine and related tasks)
1217//
1218////////////////////////////////////////////////////////////////////////////////
1219
1220/**
1221 * Implementation for IInternalMachineControl::beginTakingSnapshot().
1222 *
1223 * Gets called indirectly from Console::TakeSnapshot, which creates a
1224 * progress object in the client and then starts a thread
1225 * (Console::fntTakeSnapshotWorker) which then calls this.
1226 *
1227 * In other words, the asynchronous work for taking snapshots takes place
1228 * on the _client_ (in the Console). This is different from restoring
1229 * or deleting snapshots, which start threads on the server.
1230 *
1231 * This does the server-side work of taking a snapshot: it creates diffencing
1232 * images for all hard disks attached to the machine and then creates a
1233 * Snapshot object with a corresponding SnapshotMachine to save the VM settings.
1234 *
1235 * The client's fntTakeSnapshotWorker() blocks while this takes place.
1236 * After this returns successfully, fntTakeSnapshotWorker() will begin
1237 * saving the machine state to the snapshot object and reconfigure the
1238 * hard disks.
1239 *
1240 * When the console is done, it calls SessionMachine::EndTakingSnapshot().
1241 *
1242 * @note Locks mParent + this object for writing.
1243 *
1244 * @param aInitiator in: The console on which Console::TakeSnapshot was called.
1245 * @param aName in: The name for the new snapshot.
1246 * @param aDescription in: A description for the new snapshot.
1247 * @param aConsoleProgress in: The console's (client's) progress object.
1248 * @param fTakingSnapshotOnline in: True if an online snapshot is being taken (i.e. machine is running).
1249 * @param aStateFilePath out: name of file in snapshots folder to which the console should write the VM state.
1250 * @return
1251 */
1252STDMETHODIMP SessionMachine::BeginTakingSnapshot(IConsole *aInitiator,
1253 IN_BSTR aName,
1254 IN_BSTR aDescription,
1255 IProgress *aConsoleProgress,
1256 BOOL fTakingSnapshotOnline,
1257 BSTR *aStateFilePath)
1258{
1259 LogFlowThisFuncEnter();
1260
1261 AssertReturn(aInitiator && aName, E_INVALIDARG);
1262 AssertReturn(aStateFilePath, E_POINTER);
1263
1264 LogFlowThisFunc(("aName='%ls' fTakingSnapshotOnline=%RTbool\n", aName, fTakingSnapshotOnline));
1265
1266 AutoCaller autoCaller(this);
1267 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
1268
1269 // if this becomes true, we need to call VirtualBox::saveSettings() in the end
1270 bool fNeedsSaveSettings = false;
1271
1272 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1273
1274 AssertReturn( !Global::IsOnlineOrTransient(mData->mMachineState)
1275 || mData->mMachineState == MachineState_Running
1276 || mData->mMachineState == MachineState_Paused, E_FAIL);
1277 AssertReturn(mSnapshotData.mLastState == MachineState_Null, E_FAIL);
1278 AssertReturn(mSnapshotData.mSnapshot.isNull(), E_FAIL);
1279
1280 if ( !fTakingSnapshotOnline
1281 && mData->mMachineState != MachineState_Saved
1282 )
1283 {
1284 /* save all current settings to ensure current changes are committed and
1285 * hard disks are fixed up */
1286 HRESULT rc = saveSettings(NULL);
1287 // no need to check for whether VirtualBox.xml needs changing since
1288 // we can't have a machine XML rename pending at this point
1289 if (FAILED(rc)) return rc;
1290 }
1291
1292 /* create an ID for the snapshot */
1293 Guid snapshotId;
1294 snapshotId.create();
1295
1296 Utf8Str strStateFilePath;
1297 /* stateFilePath is null when the machine is not online nor saved */
1298 if ( fTakingSnapshotOnline
1299 || mData->mMachineState == MachineState_Saved)
1300 {
1301 strStateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
1302 mUserData->mSnapshotFolderFull.raw(),
1303 RTPATH_DELIMITER,
1304 snapshotId.ptr());
1305 /* ensure the directory for the saved state file exists */
1306 HRESULT rc = VirtualBox::ensureFilePathExists(strStateFilePath);
1307 if (FAILED(rc)) return rc;
1308 }
1309
1310 /* create a snapshot machine object */
1311 ComObjPtr<SnapshotMachine> snapshotMachine;
1312 snapshotMachine.createObject();
1313 HRESULT rc = snapshotMachine->init(this, snapshotId, strStateFilePath);
1314 AssertComRCReturn(rc, rc);
1315
1316 /* create a snapshot object */
1317 RTTIMESPEC time;
1318 ComObjPtr<Snapshot> pSnapshot;
1319 pSnapshot.createObject();
1320 rc = pSnapshot->init(mParent,
1321 snapshotId,
1322 aName,
1323 aDescription,
1324 *RTTimeNow(&time),
1325 snapshotMachine,
1326 mData->mCurrentSnapshot);
1327 AssertComRCReturnRC(rc);
1328
1329 /* fill in the snapshot data */
1330 mSnapshotData.mLastState = mData->mMachineState;
1331 mSnapshotData.mSnapshot = pSnapshot;
1332
1333 try
1334 {
1335 LogFlowThisFunc(("Creating differencing hard disks (online=%d)...\n",
1336 fTakingSnapshotOnline));
1337
1338 // backup the media data so we can recover if things goes wrong along the day;
1339 // the matching commit() is in fixupMedia() during endSnapshot()
1340 setModified(IsModified_Storage);
1341 mMediaData.backup();
1342
1343 /* Console::fntTakeSnapshotWorker and friends expects this. */
1344 if (mSnapshotData.mLastState == MachineState_Running)
1345 setMachineState(MachineState_LiveSnapshotting);
1346 else
1347 setMachineState(MachineState_Saving); /** @todo Confusing! Saving is used for both online and offline snapshots. */
1348
1349 /* create new differencing hard disks and attach them to this machine */
1350 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
1351 aConsoleProgress,
1352 1, // operation weight; must be the same as in Console::TakeSnapshot()
1353 !!fTakingSnapshotOnline,
1354 &fNeedsSaveSettings);
1355 if (FAILED(rc))
1356 throw rc;
1357
1358 if (mSnapshotData.mLastState == MachineState_Saved)
1359 {
1360 Utf8Str stateFrom = mSSData->mStateFilePath;
1361 Utf8Str stateTo = mSnapshotData.mSnapshot->stateFilePath();
1362
1363 LogFlowThisFunc(("Copying the execution state from '%s' to '%s'...\n",
1364 stateFrom.raw(), stateTo.raw()));
1365
1366 aConsoleProgress->SetNextOperation(Bstr(tr("Copying the execution state")),
1367 1); // weight
1368
1369 /* Leave the lock before a lengthy operation (machine is protected
1370 * by "Saving" machine state now) */
1371 alock.release();
1372
1373 /* copy the state file */
1374 int vrc = RTFileCopyEx(stateFrom.c_str(),
1375 stateTo.c_str(),
1376 0,
1377 progressCallback,
1378 aConsoleProgress);
1379 alock.acquire();
1380
1381 if (RT_FAILURE(vrc))
1382 /** @todo r=bird: Delete stateTo when appropriate. */
1383 throw setError(E_FAIL,
1384 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1385 stateFrom.raw(),
1386 stateTo.raw(),
1387 vrc);
1388 }
1389 }
1390 catch (HRESULT hrc)
1391 {
1392 LogThisFunc(("Caught %Rhrc [%s]\n", hrc, Global::stringifyMachineState(mData->mMachineState) ));
1393 if ( mSnapshotData.mLastState != mData->mMachineState
1394 && ( mSnapshotData.mLastState == MachineState_Running
1395 ? mData->mMachineState == MachineState_LiveSnapshotting
1396 : mData->mMachineState == MachineState_Saving)
1397 )
1398 setMachineState(mSnapshotData.mLastState);
1399
1400 pSnapshot->uninit();
1401 pSnapshot.setNull();
1402 mSnapshotData.mLastState = MachineState_Null;
1403 mSnapshotData.mSnapshot.setNull();
1404
1405 rc = hrc;
1406
1407 // @todo r=dj what with the implicit diff that we created above? this is never cleaned up
1408 }
1409
1410 if (fTakingSnapshotOnline && SUCCEEDED(rc))
1411 strStateFilePath.cloneTo(aStateFilePath);
1412 else
1413 *aStateFilePath = NULL;
1414
1415 // @todo r=dj normally we would need to save the settings if fNeedsSaveSettings was set to true,
1416 // but since we have no error handling that cleans up the diff image that might have gotten created,
1417 // there's no point in saving the disk registry at this point either... this needs fixing.
1418
1419 LogFlowThisFunc(("LEAVE - %Rhrc [%s]\n", rc, Global::stringifyMachineState(mData->mMachineState) ));
1420 return rc;
1421}
1422
1423/**
1424 * Implementation for IInternalMachineControl::endTakingSnapshot().
1425 *
1426 * Called by the Console when it's done saving the VM state into the snapshot
1427 * (if online) and reconfiguring the hard disks. See BeginTakingSnapshot() above.
1428 *
1429 * This also gets called if the console part of snapshotting failed after the
1430 * BeginTakingSnapshot() call, to clean up the server side.
1431 *
1432 * @note Locks VirtualBox and this object for writing.
1433 *
1434 * @param aSuccess Whether Console was successful with the client-side snapshot things.
1435 * @return
1436 */
1437STDMETHODIMP SessionMachine::EndTakingSnapshot(BOOL aSuccess)
1438{
1439 LogFlowThisFunc(("\n"));
1440
1441 AutoCaller autoCaller(this);
1442 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
1443
1444 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
1445
1446 AssertReturn( !aSuccess
1447 || ( ( mData->mMachineState == MachineState_Saving
1448 || mData->mMachineState == MachineState_LiveSnapshotting)
1449 && mSnapshotData.mLastState != MachineState_Null
1450 && !mSnapshotData.mSnapshot.isNull()
1451 )
1452 , E_FAIL);
1453
1454 /*
1455 * Restore the state we had when BeginTakingSnapshot() was called,
1456 * Console::fntTakeSnapshotWorker restores its local copy when we return.
1457 * If the state was Running, then let Console::fntTakeSnapshotWorker do it
1458 * all to avoid races.
1459 */
1460 if ( mData->mMachineState != mSnapshotData.mLastState
1461 && mSnapshotData.mLastState != MachineState_Running
1462 )
1463 setMachineState(mSnapshotData.mLastState);
1464
1465 ComObjPtr<Snapshot> pOldFirstSnap = mData->mFirstSnapshot;
1466 ComObjPtr<Snapshot> pOldCurrentSnap = mData->mCurrentSnapshot;
1467
1468 bool fOnline = Global::IsOnline(mSnapshotData.mLastState);
1469
1470 HRESULT rc = S_OK;
1471
1472 if (aSuccess)
1473 {
1474 // new snapshot becomes the current one
1475 mData->mCurrentSnapshot = mSnapshotData.mSnapshot;
1476
1477 /* memorize the first snapshot if necessary */
1478 if (!mData->mFirstSnapshot)
1479 mData->mFirstSnapshot = mData->mCurrentSnapshot;
1480
1481 int flSaveSettings = SaveS_Force; // do not do a deep compare in machine settings,
1482 // snapshots change, so we know we need to save
1483 if (!fOnline)
1484 /* the machine was powered off or saved when taking a snapshot, so
1485 * reset the mCurrentStateModified flag */
1486 flSaveSettings |= SaveS_ResetCurStateModified;
1487
1488 rc = saveSettings(NULL, flSaveSettings);
1489 // no need to change for whether VirtualBox.xml needs saving since
1490 // we'll save the global settings below anyway
1491 }
1492
1493 if (aSuccess && SUCCEEDED(rc))
1494 {
1495 /* associate old hard disks with the snapshot and do locking/unlocking*/
1496 commitMedia(fOnline);
1497
1498 /* inform callbacks */
1499 mParent->onSnapshotTaken(mData->mUuid,
1500 mSnapshotData.mSnapshot->getId());
1501 }
1502 else
1503 {
1504 /* delete all differencing hard disks created (this will also attach
1505 * their parents back by rolling back mMediaData) */
1506 rollbackMedia();
1507
1508 mData->mFirstSnapshot = pOldFirstSnap; // might have been changed above
1509 mData->mCurrentSnapshot = pOldCurrentSnap; // might have been changed above
1510
1511 /* delete the saved state file (it might have been already created) */
1512 if (mSnapshotData.mSnapshot->stateFilePath().length())
1513 RTFileDelete(mSnapshotData.mSnapshot->stateFilePath().c_str());
1514
1515 mSnapshotData.mSnapshot->uninit();
1516 }
1517
1518 /* clear out the snapshot data */
1519 mSnapshotData.mLastState = MachineState_Null;
1520 mSnapshotData.mSnapshot.setNull();
1521
1522 // save VirtualBox.xml (media registry most probably changed with diff image)
1523 machineLock.release();
1524 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
1525 mParent->saveSettings();
1526
1527 return rc;
1528}
1529
1530////////////////////////////////////////////////////////////////////////////////
1531//
1532// RestoreSnapshot methods (SessionMachine and related tasks)
1533//
1534////////////////////////////////////////////////////////////////////////////////
1535
1536/**
1537 * Implementation for IInternalMachineControl::restoreSnapshot().
1538 *
1539 * Gets called from Console::RestoreSnapshot(), and that's basically the
1540 * only thing Console does. Restoring a snapshot happens entirely on the
1541 * server side since the machine cannot be running.
1542 *
1543 * This creates a new thread that does the work and returns a progress
1544 * object to the client which is then returned to the caller of
1545 * Console::RestoreSnapshot().
1546 *
1547 * Actual work then takes place in RestoreSnapshotTask::handler().
1548 *
1549 * @note Locks this + children objects for writing!
1550 *
1551 * @param aInitiator in: rhe console on which Console::RestoreSnapshot was called.
1552 * @param aSnapshot in: the snapshot to restore.
1553 * @param aMachineState in: client-side machine state.
1554 * @param aProgress out: progress object to monitor restore thread.
1555 * @return
1556 */
1557STDMETHODIMP SessionMachine::RestoreSnapshot(IConsole *aInitiator,
1558 ISnapshot *aSnapshot,
1559 MachineState_T *aMachineState,
1560 IProgress **aProgress)
1561{
1562 LogFlowThisFuncEnter();
1563
1564 AssertReturn(aInitiator, E_INVALIDARG);
1565 AssertReturn(aSnapshot && aMachineState && aProgress, E_POINTER);
1566
1567 AutoCaller autoCaller(this);
1568 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
1569
1570 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1571
1572 // machine must not be running
1573 ComAssertRet(!Global::IsOnlineOrTransient(mData->mMachineState),
1574 E_FAIL);
1575
1576 ComObjPtr<Snapshot> pSnapshot(static_cast<Snapshot*>(aSnapshot));
1577 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
1578
1579 // create a progress object. The number of operations is:
1580 // 1 (preparing) + # of hard disks + 1 (if we need to copy the saved state file) */
1581 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
1582
1583 ULONG ulOpCount = 1; // one for preparations
1584 ULONG ulTotalWeight = 1; // one for preparations
1585 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
1586 it != pSnapMachine->mMediaData->mAttachments.end();
1587 ++it)
1588 {
1589 ComObjPtr<MediumAttachment> &pAttach = *it;
1590 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
1591 if (pAttach->getType() == DeviceType_HardDisk)
1592 {
1593 ++ulOpCount;
1594 ++ulTotalWeight; // assume one MB weight for each differencing hard disk to manage
1595 Assert(pAttach->getMedium());
1596 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pAttach->getMedium()->getName().c_str()));
1597 }
1598 }
1599
1600 ULONG ulStateFileSizeMB = 0;
1601 if (pSnapshot->stateFilePath().length())
1602 {
1603 ++ulOpCount; // one for the saved state
1604
1605 uint64_t ullSize;
1606 int irc = RTFileQuerySize(pSnapshot->stateFilePath().c_str(), &ullSize);
1607 if (!RT_SUCCESS(irc))
1608 // if we can't access the file here, then we'll be doomed later also, so fail right away
1609 setError(E_FAIL, tr("Cannot access state file '%s', runtime error, %Rra"), pSnapshot->stateFilePath().c_str(), irc);
1610 if (ullSize == 0) // avoid division by zero
1611 ullSize = _1M;
1612
1613 ulStateFileSizeMB = (ULONG)(ullSize / _1M);
1614 LogFlowThisFunc(("op %d: saved state file '%s' has %RI64 bytes (%d MB)\n",
1615 ulOpCount, pSnapshot->stateFilePath().raw(), ullSize, ulStateFileSizeMB));
1616
1617 ulTotalWeight += ulStateFileSizeMB;
1618 }
1619
1620 ComObjPtr<Progress> pProgress;
1621 pProgress.createObject();
1622 pProgress->init(mParent, aInitiator,
1623 BstrFmt(tr("Restoring snapshot '%s'"), pSnapshot->getName().c_str()),
1624 FALSE /* aCancelable */,
1625 ulOpCount,
1626 ulTotalWeight,
1627 Bstr(tr("Restoring machine settings")),
1628 1);
1629
1630 /* create and start the task on a separate thread (note that it will not
1631 * start working until we release alock) */
1632 RestoreSnapshotTask *task = new RestoreSnapshotTask(this,
1633 pProgress,
1634 pSnapshot,
1635 ulStateFileSizeMB);
1636 int vrc = RTThreadCreate(NULL,
1637 taskHandler,
1638 (void*)task,
1639 0,
1640 RTTHREADTYPE_MAIN_WORKER,
1641 0,
1642 "RestoreSnap");
1643 if (RT_FAILURE(vrc))
1644 {
1645 delete task;
1646 ComAssertRCRet(vrc, E_FAIL);
1647 }
1648
1649 /* set the proper machine state (note: after creating a Task instance) */
1650 setMachineState(MachineState_RestoringSnapshot);
1651
1652 /* return the progress to the caller */
1653 pProgress.queryInterfaceTo(aProgress);
1654
1655 /* return the new state to the caller */
1656 *aMachineState = mData->mMachineState;
1657
1658 LogFlowThisFuncLeave();
1659
1660 return S_OK;
1661}
1662
1663/**
1664 * Worker method for the restore snapshot thread created by SessionMachine::RestoreSnapshot().
1665 * This method gets called indirectly through SessionMachine::taskHandler() which then
1666 * calls RestoreSnapshotTask::handler().
1667 *
1668 * The RestoreSnapshotTask contains the progress object returned to the console by
1669 * SessionMachine::RestoreSnapshot, through which progress and results are reported.
1670 *
1671 * @note Locks mParent + this object for writing.
1672 *
1673 * @param aTask Task data.
1674 */
1675void SessionMachine::restoreSnapshotHandler(RestoreSnapshotTask &aTask)
1676{
1677 LogFlowThisFuncEnter();
1678
1679 AutoCaller autoCaller(this);
1680
1681 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
1682 if (!autoCaller.isOk())
1683 {
1684 /* we might have been uninitialized because the session was accidentally
1685 * closed by the client, so don't assert */
1686 aTask.pProgress->notifyComplete(E_FAIL,
1687 COM_IIDOF(IMachine),
1688 getComponentName(),
1689 tr("The session has been accidentally closed"));
1690
1691 LogFlowThisFuncLeave();
1692 return;
1693 }
1694
1695 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1696
1697 /* discard all current changes to mUserData (name, OSType etc.) (note that
1698 * the machine is powered off, so there is no need to inform the direct
1699 * session) */
1700 if (mData->flModifications)
1701 rollback(false /* aNotify */);
1702
1703 HRESULT rc = S_OK;
1704
1705 bool stateRestored = false;
1706 bool fNeedsSaveSettings = false;
1707
1708 try
1709 {
1710 /* Delete the saved state file if the machine was Saved prior to this
1711 * operation */
1712 if (aTask.machineStateBackup == MachineState_Saved)
1713 {
1714 Assert(!mSSData->mStateFilePath.isEmpty());
1715 RTFileDelete(mSSData->mStateFilePath.c_str());
1716 mSSData->mStateFilePath.setNull();
1717 aTask.modifyBackedUpState(MachineState_PoweredOff);
1718 rc = saveStateSettings(SaveSTS_StateFilePath);
1719 if (FAILED(rc))
1720 throw rc;
1721 }
1722
1723 RTTIMESPEC snapshotTimeStamp;
1724 RTTimeSpecSetMilli(&snapshotTimeStamp, 0);
1725
1726 {
1727 AutoReadLock snapshotLock(aTask.pSnapshot COMMA_LOCKVAL_SRC_POS);
1728
1729 /* remember the timestamp of the snapshot we're restoring from */
1730 snapshotTimeStamp = aTask.pSnapshot->getTimeStamp();
1731
1732 ComPtr<SnapshotMachine> pSnapshotMachine(aTask.pSnapshot->getSnapshotMachine());
1733
1734 /* copy all hardware data from the snapshot */
1735 copyFrom(pSnapshotMachine);
1736
1737 LogFlowThisFunc(("Restoring hard disks from the snapshot...\n"));
1738
1739 // restore the attachments from the snapshot
1740 setModified(IsModified_Storage);
1741 mMediaData.backup();
1742 mMediaData->mAttachments = pSnapshotMachine->mMediaData->mAttachments;
1743
1744 /* leave the locks before the potentially lengthy operation */
1745 snapshotLock.release();
1746 alock.leave();
1747
1748 rc = createImplicitDiffs(mUserData->mSnapshotFolderFull,
1749 aTask.pProgress,
1750 1,
1751 false /* aOnline */,
1752 &fNeedsSaveSettings);
1753 if (FAILED(rc))
1754 throw rc;
1755
1756 alock.enter();
1757 snapshotLock.acquire();
1758
1759 /* Note: on success, current (old) hard disks will be
1760 * deassociated/deleted on #commit() called from #saveSettings() at
1761 * the end. On failure, newly created implicit diffs will be
1762 * deleted by #rollback() at the end. */
1763
1764 /* should not have a saved state file associated at this point */
1765 Assert(mSSData->mStateFilePath.isEmpty());
1766
1767 if (!aTask.pSnapshot->stateFilePath().isEmpty())
1768 {
1769 Utf8Str snapStateFilePath = aTask.pSnapshot->stateFilePath();
1770
1771 Utf8Str stateFilePath = Utf8StrFmt("%ls%c{%RTuuid}.sav",
1772 mUserData->mSnapshotFolderFull.raw(),
1773 RTPATH_DELIMITER,
1774 mData->mUuid.raw());
1775
1776 LogFlowThisFunc(("Copying saved state file from '%s' to '%s'...\n",
1777 snapStateFilePath.raw(), stateFilePath.raw()));
1778
1779 aTask.pProgress->SetNextOperation(Bstr(tr("Restoring the execution state")),
1780 aTask.m_ulStateFileSizeMB); // weight
1781
1782 /* leave the lock before the potentially lengthy operation */
1783 snapshotLock.release();
1784 alock.leave();
1785
1786 /* copy the state file */
1787 int vrc = RTFileCopyEx(snapStateFilePath.c_str(),
1788 stateFilePath.c_str(),
1789 0,
1790 progressCallback,
1791 static_cast<IProgress*>(aTask.pProgress));
1792
1793 alock.enter();
1794 snapshotLock.acquire();
1795
1796 if (RT_SUCCESS(vrc))
1797 mSSData->mStateFilePath = stateFilePath;
1798 else
1799 throw setError(E_FAIL,
1800 tr("Could not copy the state file '%s' to '%s' (%Rrc)"),
1801 snapStateFilePath.raw(),
1802 stateFilePath.raw(),
1803 vrc);
1804 }
1805
1806 LogFlowThisFunc(("Setting new current snapshot {%RTuuid}\n", aTask.pSnapshot->getId().raw()));
1807 /* make the snapshot we restored from the current snapshot */
1808 mData->mCurrentSnapshot = aTask.pSnapshot;
1809 }
1810
1811 /* grab differencing hard disks from the old attachments that will
1812 * become unused and need to be auto-deleted */
1813 std::list< ComObjPtr<MediumAttachment> > llDiffAttachmentsToDelete;
1814
1815 for (MediaData::AttachmentList::const_iterator it = mMediaData.backedUpData()->mAttachments.begin();
1816 it != mMediaData.backedUpData()->mAttachments.end();
1817 ++it)
1818 {
1819 ComObjPtr<MediumAttachment> pAttach = *it;
1820 ComObjPtr<Medium> pMedium = pAttach->getMedium();
1821
1822 /* while the hard disk is attached, the number of children or the
1823 * parent cannot change, so no lock */
1824 if ( !pMedium.isNull()
1825 && pAttach->getType() == DeviceType_HardDisk
1826 && !pMedium->getParent().isNull()
1827 && pMedium->getChildren().size() == 0
1828 )
1829 {
1830 LogFlowThisFunc(("Picked differencing image '%s' for deletion\n", pMedium->getName().raw()));
1831
1832 llDiffAttachmentsToDelete.push_back(pAttach);
1833 }
1834 }
1835
1836 int saveFlags = 0;
1837
1838 /* we have already deleted the current state, so set the execution
1839 * state accordingly no matter of the delete snapshot result */
1840 if (!mSSData->mStateFilePath.isEmpty())
1841 setMachineState(MachineState_Saved);
1842 else
1843 setMachineState(MachineState_PoweredOff);
1844
1845 updateMachineStateOnClient();
1846 stateRestored = true;
1847
1848 /* assign the timestamp from the snapshot */
1849 Assert(RTTimeSpecGetMilli (&snapshotTimeStamp) != 0);
1850 mData->mLastStateChange = snapshotTimeStamp;
1851
1852 // detach the current-state diffs that we detected above and build a list of
1853 // image files to delete _after_ saveSettings()
1854
1855 MediaList llDiffsToDelete;
1856
1857 for (std::list< ComObjPtr<MediumAttachment> >::iterator it = llDiffAttachmentsToDelete.begin();
1858 it != llDiffAttachmentsToDelete.end();
1859 ++it)
1860 {
1861 ComObjPtr<MediumAttachment> pAttach = *it; // guaranteed to have only attachments where medium != NULL
1862 ComObjPtr<Medium> pMedium = pAttach->getMedium();
1863
1864 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
1865
1866 LogFlowThisFunc(("Detaching old current state in differencing image '%s'\n", pMedium->getName().raw()));
1867
1868 // Normally we "detach" the medium by removing the attachment object
1869 // from the current machine data; saveSettings() below would then
1870 // compare the current machine data with the one in the backup
1871 // and actually call Medium::detachFrom(). But that works only half
1872 // the time in our case so instead we force a detachment here:
1873 // remove from machine data
1874 mMediaData->mAttachments.remove(pAttach);
1875 // remove it from the backup or else saveSettings will try to detach
1876 // it again and assert
1877 mMediaData.backedUpData()->mAttachments.remove(pAttach);
1878 // then clean up backrefs
1879 pMedium->detachFrom(mData->mUuid);
1880
1881 llDiffsToDelete.push_back(pMedium);
1882 }
1883
1884 // save machine settings, reset the modified flag and commit;
1885 rc = saveSettings(&fNeedsSaveSettings, SaveS_ResetCurStateModified | saveFlags);
1886 if (FAILED(rc))
1887 throw rc;
1888
1889 // let go of the locks while we're deleting image files below
1890 alock.leave();
1891 // from here on we cannot roll back on failure any more
1892
1893 for (MediaList::iterator it = llDiffsToDelete.begin();
1894 it != llDiffsToDelete.end();
1895 ++it)
1896 {
1897 ComObjPtr<Medium> &pMedium = *it;
1898 LogFlowThisFunc(("Deleting old current state in differencing image '%s'\n", pMedium->getName().raw()));
1899
1900 HRESULT rc2 = pMedium->deleteStorage(NULL /* aProgress */,
1901 true /* aWait */,
1902 &fNeedsSaveSettings);
1903 // ignore errors here because we cannot roll back after saveSettings() above
1904 if (SUCCEEDED(rc2))
1905 pMedium->uninit();
1906 }
1907
1908 if (fNeedsSaveSettings)
1909 {
1910 // finally, VirtualBox.xml needs saving too
1911 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
1912 mParent->saveSettings();
1913 }
1914 }
1915 catch (HRESULT aRC)
1916 {
1917 rc = aRC;
1918 }
1919
1920 if (FAILED(rc))
1921 {
1922 /* preserve existing error info */
1923 ErrorInfoKeeper eik;
1924
1925 /* undo all changes on failure */
1926 rollback(false /* aNotify */);
1927
1928 if (!stateRestored)
1929 {
1930 /* restore the machine state */
1931 setMachineState(aTask.machineStateBackup);
1932 updateMachineStateOnClient();
1933 }
1934 }
1935
1936 /* set the result (this will try to fetch current error info on failure) */
1937 aTask.pProgress->notifyComplete(rc);
1938
1939 if (SUCCEEDED(rc))
1940 mParent->onSnapshotDeleted(mData->mUuid, Guid());
1941
1942 LogFlowThisFunc(("Done restoring snapshot (rc=%08X)\n", rc));
1943
1944 LogFlowThisFuncLeave();
1945}
1946
1947////////////////////////////////////////////////////////////////////////////////
1948//
1949// DeleteSnapshot methods (SessionMachine and related tasks)
1950//
1951////////////////////////////////////////////////////////////////////////////////
1952
1953/**
1954 * Implementation for IInternalMachineControl::deleteSnapshot().
1955 *
1956 * Gets called from Console::DeleteSnapshot(), and that's basically the
1957 * only thing Console does. Deleting a snapshot happens entirely on the
1958 * server side since the machine cannot be running.
1959 *
1960 * This creates a new thread that does the work and returns a progress
1961 * object to the client which is then returned to the caller of
1962 * Console::DeleteSnapshot().
1963 *
1964 * Actual work then takes place in DeleteSnapshotTask::handler().
1965 *
1966 * @note Locks mParent + this + children objects for writing!
1967 */
1968STDMETHODIMP SessionMachine::DeleteSnapshot(IConsole *aInitiator,
1969 IN_BSTR aId,
1970 MachineState_T *aMachineState,
1971 IProgress **aProgress)
1972{
1973 LogFlowThisFuncEnter();
1974
1975 Guid id(aId);
1976 AssertReturn(aInitiator && !id.isEmpty(), E_INVALIDARG);
1977 AssertReturn(aMachineState && aProgress, E_POINTER);
1978
1979 AutoCaller autoCaller(this);
1980 AssertComRCReturn(autoCaller.rc(), autoCaller.rc());
1981
1982 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1983
1984 // machine must not be changing state
1985 ComAssertRet(!Global::IsTransient(mData->mMachineState), E_FAIL);
1986
1987 ComObjPtr<Snapshot> pSnapshot;
1988 HRESULT rc = findSnapshot(id, pSnapshot, true /* aSetError */);
1989 if (FAILED(rc)) return rc;
1990
1991 AutoWriteLock snapshotLock(pSnapshot COMMA_LOCKVAL_SRC_POS);
1992
1993 size_t childrenCount = pSnapshot->getChildrenCount();
1994 if (childrenCount > 1)
1995 return setError(VBOX_E_INVALID_OBJECT_STATE,
1996 tr("Snapshot '%s' of the machine '%ls' cannot be deleted. because it has %d child snapshots, which is more than the one snapshot allowed for deletion"),
1997 pSnapshot->getName().c_str(),
1998 mUserData->mName.raw(),
1999 childrenCount);
2000
2001 /* If the snapshot being deleted is the current one, ensure current
2002 * settings are committed and saved.
2003 */
2004 if (pSnapshot == mData->mCurrentSnapshot)
2005 {
2006 if (mData->flModifications)
2007 {
2008 rc = saveSettings(NULL);
2009 // no need to change for whether VirtualBox.xml needs saving since
2010 // we can't have a machine XML rename pending at this point
2011 if (FAILED(rc)) return rc;
2012 }
2013 }
2014
2015 ComObjPtr<SnapshotMachine> pSnapMachine = pSnapshot->getSnapshotMachine();
2016
2017 /* create a progress object. The number of operations is:
2018 * 1 (preparing) + 1 if the snapshot is online + # of normal hard disks
2019 */
2020 LogFlowThisFunc(("Going thru snapshot machine attachments to determine progress setup\n"));
2021
2022 ULONG ulOpCount = 1; // one for preparations
2023 ULONG ulTotalWeight = 1; // one for preparations
2024
2025 if (pSnapshot->stateFilePath().length())
2026 {
2027 ++ulOpCount;
2028 ++ulTotalWeight; // assume 1 MB for deleting the state file
2029 }
2030
2031 // count normal hard disks and add their sizes to the weight
2032 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2033 it != pSnapMachine->mMediaData->mAttachments.end();
2034 ++it)
2035 {
2036 ComObjPtr<MediumAttachment> &pAttach = *it;
2037 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2038 if (pAttach->getType() == DeviceType_HardDisk)
2039 {
2040 ComObjPtr<Medium> pHD = pAttach->getMedium();
2041 Assert(pHD);
2042 AutoReadLock mlock(pHD COMMA_LOCKVAL_SRC_POS);
2043
2044 MediumType_T type = pHD->getType();
2045 if (type != MediumType_Writethrough) // writethrough images are unaffected by snapshots, so do nothing for them
2046 {
2047 // normal or immutable media need attention
2048 ++ulOpCount;
2049 ulTotalWeight += (ULONG)(pHD->getSize() / _1M);
2050 }
2051 LogFlowThisFunc(("op %d: considering hard disk attachment %s\n", ulOpCount, pHD->getName().c_str()));
2052 }
2053 }
2054
2055 ComObjPtr<Progress> pProgress;
2056 pProgress.createObject();
2057 pProgress->init(mParent, aInitiator,
2058 BstrFmt(tr("Deleting snapshot '%s'"), pSnapshot->getName().c_str()),
2059 FALSE /* aCancelable */,
2060 ulOpCount,
2061 ulTotalWeight,
2062 Bstr(tr("Setting up")),
2063 1);
2064
2065 bool fDeleteOnline = ( (mData->mMachineState == MachineState_Running)
2066 || (mData->mMachineState == MachineState_Paused));
2067
2068 /* create and start the task on a separate thread */
2069 DeleteSnapshotTask *task = new DeleteSnapshotTask(this, pProgress,
2070 fDeleteOnline, pSnapshot);
2071 int vrc = RTThreadCreate(NULL,
2072 taskHandler,
2073 (void*)task,
2074 0,
2075 RTTHREADTYPE_MAIN_WORKER,
2076 0,
2077 "DeleteSnapshot");
2078 if (RT_FAILURE(vrc))
2079 {
2080 delete task;
2081 return E_FAIL;
2082 }
2083
2084 // the task might start running but will block on acquiring the machine's write lock
2085 // which we acquired above; once this function leaves, the task will be unblocked;
2086 // set the proper machine state here now (note: after creating a Task instance)
2087 /// @todo introduce a separate state for online snapshot deletion
2088 setMachineState(MachineState_DeletingSnapshot);
2089
2090 /* return the progress to the caller */
2091 pProgress.queryInterfaceTo(aProgress);
2092
2093 /* return the new state to the caller */
2094 *aMachineState = mData->mMachineState;
2095
2096 LogFlowThisFuncLeave();
2097
2098 return S_OK;
2099}
2100
2101/**
2102 * Helper struct for SessionMachine::deleteSnapshotHandler().
2103 */
2104struct MediumDeleteRec
2105{
2106 MediumDeleteRec()
2107 : mfNeedsOnlineMerge(false),
2108 mpMediumLockList(NULL)
2109 {}
2110
2111 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2112 const ComObjPtr<Medium> &aSource,
2113 const ComObjPtr<Medium> &aTarget,
2114 bool fMergeForward,
2115 const ComObjPtr<Medium> &aParentForTarget,
2116 const MediaList &aChildrenToReparent,
2117 bool fNeedsOnlineMerge,
2118 MediumLockList *aMediumLockList)
2119 : mpHD(aHd),
2120 mpSource(aSource),
2121 mpTarget(aTarget),
2122 mfMergeForward(fMergeForward),
2123 mpParentForTarget(aParentForTarget),
2124 mChildrenToReparent(aChildrenToReparent),
2125 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2126 mpMediumLockList(aMediumLockList)
2127 {}
2128
2129 MediumDeleteRec(const ComObjPtr<Medium> &aHd,
2130 const ComObjPtr<Medium> &aSource,
2131 const ComObjPtr<Medium> &aTarget,
2132 bool fMergeForward,
2133 const ComObjPtr<Medium> &aParentForTarget,
2134 const MediaList &aChildrenToReparent,
2135 bool fNeedsOnlineMerge,
2136 MediumLockList *aMediumLockList,
2137 const Guid &aMachineId,
2138 const Guid &aSnapshotId)
2139 : mpHD(aHd),
2140 mpSource(aSource),
2141 mpTarget(aTarget),
2142 mfMergeForward(fMergeForward),
2143 mpParentForTarget(aParentForTarget),
2144 mChildrenToReparent(aChildrenToReparent),
2145 mfNeedsOnlineMerge(fNeedsOnlineMerge),
2146 mpMediumLockList(aMediumLockList),
2147 mMachineId(aMachineId),
2148 mSnapshotId(aSnapshotId)
2149 {}
2150
2151 ComObjPtr<Medium> mpHD;
2152 ComObjPtr<Medium> mpSource;
2153 ComObjPtr<Medium> mpTarget;
2154 bool mfMergeForward;
2155 ComObjPtr<Medium> mpParentForTarget;
2156 MediaList mChildrenToReparent;
2157 bool mfNeedsOnlineMerge;
2158 MediumLockList *mpMediumLockList;
2159 /* these are for reattaching the hard disk in case of a failure: */
2160 Guid mMachineId;
2161 Guid mSnapshotId;
2162};
2163
2164typedef std::list<MediumDeleteRec> MediumDeleteRecList;
2165
2166/**
2167 * Worker method for the delete snapshot thread created by
2168 * SessionMachine::DeleteSnapshot(). This method gets called indirectly
2169 * through SessionMachine::taskHandler() which then calls
2170 * DeleteSnapshotTask::handler().
2171 *
2172 * The DeleteSnapshotTask contains the progress object returned to the console
2173 * by SessionMachine::DeleteSnapshot, through which progress and results are
2174 * reported.
2175 *
2176 * SessionMachine::DeleteSnapshot() has set the machne state to
2177 * MachineState_DeletingSnapshot right after creating this task. Since we block
2178 * on the machine write lock at the beginning, once that has been acquired, we
2179 * can assume that the machine state is indeed that.
2180 *
2181 * @note Locks the machine + the snapshot + the media tree for writing!
2182 *
2183 * @param aTask Task data.
2184 */
2185
2186void SessionMachine::deleteSnapshotHandler(DeleteSnapshotTask &aTask)
2187{
2188 LogFlowThisFuncEnter();
2189
2190 AutoCaller autoCaller(this);
2191
2192 LogFlowThisFunc(("state=%d\n", autoCaller.state()));
2193 if (!autoCaller.isOk())
2194 {
2195 /* we might have been uninitialized because the session was accidentally
2196 * closed by the client, so don't assert */
2197 aTask.pProgress->notifyComplete(E_FAIL,
2198 COM_IIDOF(IMachine),
2199 getComponentName(),
2200 tr("The session has been accidentally closed"));
2201 LogFlowThisFuncLeave();
2202 return;
2203 }
2204
2205 MediumDeleteRecList toDelete;
2206
2207 HRESULT rc = S_OK;
2208
2209 bool fMachineSettingsChanged = false; // Machine
2210 bool fNeedsSaveSettings = false; // VirtualBox.xml
2211
2212 Guid snapshotId;
2213
2214 try
2215 {
2216 /* Locking order: */
2217 AutoMultiWriteLock3 multiLock(this->lockHandle(), // machine
2218 aTask.pSnapshot->lockHandle(), // snapshot
2219 &mParent->getMediaTreeLockHandle() // media tree
2220 COMMA_LOCKVAL_SRC_POS);
2221 // once we have this lock, we know that SessionMachine::DeleteSnapshot()
2222 // has exited after setting the machine state to MachineState_DeletingSnapshot
2223
2224 ComObjPtr<SnapshotMachine> pSnapMachine = aTask.pSnapshot->getSnapshotMachine();
2225 // no need to lock the snapshot machine since it is const by definiton
2226 Guid machineId = pSnapMachine->getId();
2227
2228 // save the snapshot ID (for callbacks)
2229 snapshotId = aTask.pSnapshot->getId();
2230
2231 // first pass:
2232 LogFlowThisFunc(("1: Checking hard disk merge prerequisites...\n"));
2233
2234 // Go thru the attachments of the snapshot machine (the media in here
2235 // point to the disk states _before_ the snapshot was taken, i.e. the
2236 // state we're restoring to; for each such medium, we will need to
2237 // merge it with its one and only child (the diff image holding the
2238 // changes written after the snapshot was taken).
2239 for (MediaData::AttachmentList::iterator it = pSnapMachine->mMediaData->mAttachments.begin();
2240 it != pSnapMachine->mMediaData->mAttachments.end();
2241 ++it)
2242 {
2243 ComObjPtr<MediumAttachment> &pAttach = *it;
2244 AutoReadLock attachLock(pAttach COMMA_LOCKVAL_SRC_POS);
2245 if (pAttach->getType() != DeviceType_HardDisk)
2246 continue;
2247
2248 ComObjPtr<Medium> pHD = pAttach->getMedium();
2249 Assert(!pHD.isNull());
2250
2251 {
2252 // writethrough images are unaffected by snapshots, skip them
2253 AutoReadLock medlock(pHD COMMA_LOCKVAL_SRC_POS);
2254 MediumType_T type = pHD->getType();
2255 if (type == MediumType_Writethrough)
2256 continue;
2257 }
2258
2259#ifdef DEBUG
2260 pHD->dumpBackRefs();
2261#endif
2262
2263 // needs to be merged with child or deleted, check prerequisites
2264 ComObjPtr<Medium> pTarget;
2265 ComObjPtr<Medium> pSource;
2266 bool fMergeForward = false;
2267 ComObjPtr<Medium> pParentForTarget;
2268 MediaList childrenToReparent;
2269 bool fNeedsOnlineMerge = false;
2270 bool fOnlineMergePossible = aTask.m_fDeleteOnline;
2271 MediumLockList *pMediumLockList = NULL;
2272 MediumLockList *pVMMALockList = NULL;
2273 if (fOnlineMergePossible)
2274 {
2275 // Look up the corresponding medium attachment in the currently
2276 // running VM. Any failure prevents a live merge. Could be made
2277 // a tad smarter by trying a few candidates, so that e.g. disks
2278 // which are simply moved to a different controller slot do not
2279 // prevent online merging in general.
2280 MediumAttachment *pMachAtt =
2281 findAttachment(mMediaData->mAttachments,
2282 pAttach->getControllerName(),
2283 pAttach->getPort(),
2284 pAttach->getDevice());
2285 if (pMachAtt)
2286 {
2287 rc = mData->mSession.mLockedMedia.Get(pMachAtt,
2288 pVMMALockList);
2289 if (FAILED(rc))
2290 fOnlineMergePossible = false;
2291 }
2292 else
2293 fOnlineMergePossible = false;
2294 }
2295 rc = prepareDeleteSnapshotMedium(pHD, machineId, snapshotId,
2296 fOnlineMergePossible,
2297 pVMMALockList, pSource, pTarget,
2298 fMergeForward, pParentForTarget,
2299 childrenToReparent,
2300 fNeedsOnlineMerge,
2301 pMediumLockList);
2302 if (FAILED(rc))
2303 throw rc;
2304
2305 // no need to hold the lock any longer
2306 attachLock.release();
2307
2308 // For simplicity, prepareDeleteSnapshotMedium selects the merge
2309 // direction in the following way: we merge pHD onto its child
2310 // (forward merge), not the other way round, because that saves us
2311 // from unnecessarily shuffling around the attachments for the
2312 // machine that follows the snapshot (next snapshot or current
2313 // state), unless it's a base image. Backwards merges of the first
2314 // snapshot into the base image is essential, as it ensures that
2315 // when all snapshots are deleted the only remaining image is a
2316 // base image. Important e.g. for medium formats which do not have
2317 // a file representation such as iSCSI.
2318
2319 // a couple paranoia checks for backward merges
2320 if (pMediumLockList != NULL && !fMergeForward)
2321 {
2322 // parent is null -> this disk is a base hard disk: we will
2323 // then do a backward merge, i.e. merge its only child onto the
2324 // base disk. Here we need then to update the attachment that
2325 // refers to the child and have it point to the parent instead
2326 Assert(pHD->getParent().isNull());
2327 Assert(pHD->getChildren().size() == 1);
2328
2329 ComObjPtr<Medium> pReplaceHD = pHD->getChildren().front();
2330
2331 ComAssertThrow(pReplaceHD == pSource, E_FAIL);
2332 }
2333
2334 Guid replaceMachineId;
2335 Guid replaceSnapshotId;
2336
2337 const Guid *pReplaceMachineId = pSource->getFirstMachineBackrefId();
2338 // minimal sanity checking
2339 Assert(!pReplaceMachineId || *pReplaceMachineId == mData->mUuid);
2340 if (pReplaceMachineId)
2341 replaceMachineId = *pReplaceMachineId;
2342
2343 const Guid *pSnapshotId = pSource->getFirstMachineBackrefSnapshotId();
2344 if (pSnapshotId)
2345 replaceSnapshotId = *pSnapshotId;
2346
2347 if (!replaceMachineId.isEmpty())
2348 {
2349 // Adjust the backreferences, otherwise merging will assert.
2350 // Note that the medium attachment object stays associated
2351 // with the snapshot until the merge was successful.
2352 HRESULT rc2 = S_OK;
2353 rc2 = pSource->detachFrom(replaceMachineId, replaceSnapshotId);
2354 AssertComRC(rc2);
2355
2356 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2357 fMergeForward,
2358 pParentForTarget,
2359 childrenToReparent,
2360 fNeedsOnlineMerge,
2361 pMediumLockList,
2362 replaceMachineId,
2363 replaceSnapshotId));
2364 }
2365 else
2366 toDelete.push_back(MediumDeleteRec(pHD, pSource, pTarget,
2367 fMergeForward,
2368 pParentForTarget,
2369 childrenToReparent,
2370 fNeedsOnlineMerge,
2371 pMediumLockList));
2372 }
2373
2374 // we can release the lock now since the machine state is MachineState_DeletingSnapshot
2375 multiLock.release();
2376
2377 /* Now we checked that we can successfully merge all normal hard disks
2378 * (unless a runtime error like end-of-disc happens). Now get rid of
2379 * the saved state (if present), as that will free some disk space.
2380 * The snapshot itself will be deleted as late as possible, so that
2381 * the user can repeat the delete operation if he runs out of disk
2382 * space or cancels the delete operation. */
2383
2384 /* second pass: */
2385 LogFlowThisFunc(("2: Deleting snapshot...\n"));
2386
2387 {
2388 // saveAllSnapshots() needs a machine lock, and the snapshots
2389 // tree is protected by the machine lock as well
2390 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2391
2392 Utf8Str stateFilePath = aTask.pSnapshot->stateFilePath();
2393 if (!stateFilePath.isEmpty())
2394 {
2395 aTask.pProgress->SetNextOperation(Bstr(tr("Deleting the execution state")),
2396 1); // weight
2397
2398 aTask.pSnapshot->deleteStateFile();
2399 fMachineSettingsChanged = true;
2400 }
2401 }
2402
2403 /* third pass: */
2404 LogFlowThisFunc(("3: Performing actual hard disk merging...\n"));
2405
2406 /// @todo NEWMEDIA turn the following errors into warnings because the
2407 /// snapshot itself has been already deleted (and interpret these
2408 /// warnings properly on the GUI side)
2409 for (MediumDeleteRecList::iterator it = toDelete.begin();
2410 it != toDelete.end();)
2411 {
2412 const ComObjPtr<Medium> &pMedium(it->mpHD);
2413 ULONG ulWeight;
2414
2415 {
2416 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
2417 ulWeight = (ULONG)(pMedium->getSize() / _1M);
2418 }
2419
2420 aTask.pProgress->SetNextOperation(BstrFmt(tr("Merging differencing image '%s'"),
2421 pMedium->getName().raw()),
2422 ulWeight);
2423
2424 /// @todo not yet implemented, to be continued
2425 if (it->mfNeedsOnlineMerge)
2426 throw setError(E_NOTIMPL,
2427 tr("Live merge not implemented"));
2428
2429 bool fNeedSourceUninit = false;
2430 bool fReparentTarget = false;
2431 if (it->mpMediumLockList == NULL)
2432 {
2433 /* no real merge needed, just updating state and delete
2434 * diff files if necessary */
2435 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), pMedium->lockHandle() COMMA_LOCKVAL_SRC_POS);
2436
2437 Assert( !it->mfMergeForward
2438 || pMedium->getChildren().size() == 0);
2439
2440 /* Delete the differencing hard disk (has no children). Two
2441 * exceptions: if it's the last medium in the chain or if it's
2442 * a backward merge we don't want to handle due to complextity.
2443 * In both cases leave the image in place. If it's the first
2444 * exception the user can delete it later if he wants. */
2445 if (!pMedium->getParent().isNull())
2446 {
2447 Assert(pMedium->getState() == MediumState_Deleting);
2448 /* No need to hold the lock any longer. */
2449 mLock.release();
2450 rc = pMedium->deleteStorage(&aTask.pProgress,
2451 true /* aWait */,
2452 &fNeedsSaveSettings);
2453 if (FAILED(rc))
2454 throw rc;
2455
2456 // need to uninit the deleted medium
2457 fNeedSourceUninit = true;
2458 }
2459 }
2460 else
2461 {
2462 // normal merge operation, in the direction decided earlier
2463 rc = it->mpSource->mergeTo(it->mpTarget, it->mfMergeForward,
2464 it->mpParentForTarget,
2465 it->mChildrenToReparent,
2466 it->mpMediumLockList,
2467 &aTask.pProgress, true /* aWait */,
2468 &fNeedsSaveSettings);
2469
2470 if (FAILED(rc))
2471 throw rc;
2472
2473 // need to uninit the medium deleted by the merge
2474 fNeedSourceUninit = true;
2475
2476 // need to change the medium attachment for backward merges
2477 fReparentTarget = !it->mfMergeForward;
2478
2479 /* On success delete the no longer needed medium lock
2480 * list. This unlocks the media as well. */
2481 delete it->mpMediumLockList;
2482 it->mpMediumLockList = NULL;
2483 }
2484
2485 // Now that the medium is successfully merged/deleted/whatever,
2486 // remove the medium attachment from the snapshot. For a backwards
2487 // merge the target attachment needs to be removed from the
2488 // snapshot, as the VM will take it over. For forward merges the
2489 // source medium attachment needs to be removed.
2490 ComObjPtr<MediumAttachment> pAtt;
2491 if (fReparentTarget)
2492 {
2493 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2494 it->mpTarget);
2495 it->mpTarget->detachFrom(machineId, snapshotId);
2496 }
2497 else
2498 pAtt = findAttachment(pSnapMachine->mMediaData->mAttachments,
2499 it->mpSource);
2500 pSnapMachine->mMediaData->mAttachments.remove(pAtt);
2501
2502 if (fReparentTarget)
2503 {
2504 // search for old source attachment and replace with target
2505 pAtt = findAttachment(mMediaData->mAttachments, it->mpSource);
2506 AutoWriteLock attLock(pAtt COMMA_LOCKVAL_SRC_POS);
2507 pAtt->updateMedium(it->mpTarget, false /* aImplicit */);
2508 it->mpTarget->attachTo(mData->mUuid);
2509 }
2510
2511 if (fNeedSourceUninit)
2512 it->mpSource->uninit();
2513
2514 // One attachment is merged, must save the settings
2515 fMachineSettingsChanged = true;
2516
2517 /* prevent from calling cancelDeleteSnapshotMedium() */
2518 it = toDelete.erase(it);
2519 }
2520
2521 {
2522 // beginSnapshotDelete() needs the machine lock, and the snapshots
2523 // tree is protected by the machine lock as well
2524 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2525
2526 aTask.pSnapshot->beginSnapshotDelete();
2527 aTask.pSnapshot->uninit();
2528
2529 fMachineSettingsChanged = true;
2530 }
2531 }
2532 catch (HRESULT aRC) { rc = aRC; }
2533
2534 if (FAILED(rc))
2535 {
2536 // preserve existing error info so that the result can
2537 // be properly reported to the progress object below
2538 ErrorInfoKeeper eik;
2539
2540 AutoMultiWriteLock2 multiLock(this->lockHandle(), // machine
2541 &mParent->getMediaTreeLockHandle() // media tree
2542 COMMA_LOCKVAL_SRC_POS);
2543
2544 // un-prepare the remaining hard disks
2545 for (MediumDeleteRecList::const_iterator it = toDelete.begin();
2546 it != toDelete.end();
2547 ++it)
2548 {
2549 cancelDeleteSnapshotMedium(it->mpHD, it->mpSource,
2550 it->mChildrenToReparent,
2551 it->mfNeedsOnlineMerge,
2552 it->mpMediumLockList, it->mMachineId,
2553 it->mSnapshotId);
2554 }
2555 }
2556
2557 // whether we were successful or not, we need to set the machine
2558 // state and save the machine settings;
2559 {
2560 // preserve existing error info so that the result can
2561 // be properly reported to the progress object below
2562 ErrorInfoKeeper eik;
2563
2564 // restore the machine state that was saved when the
2565 // task was started
2566 setMachineState(aTask.machineStateBackup);
2567 updateMachineStateOnClient();
2568
2569 if (fMachineSettingsChanged || fNeedsSaveSettings)
2570 {
2571 if (fMachineSettingsChanged)
2572 {
2573 AutoWriteLock machineLock(this COMMA_LOCKVAL_SRC_POS);
2574 saveSettings(&fNeedsSaveSettings, SaveS_InformCallbacksAnyway);
2575 }
2576
2577 if (fNeedsSaveSettings)
2578 {
2579 AutoWriteLock vboxLock(mParent COMMA_LOCKVAL_SRC_POS);
2580 mParent->saveSettings();
2581 }
2582 }
2583 }
2584
2585 // report the result (this will try to fetch current error info on failure)
2586 aTask.pProgress->notifyComplete(rc);
2587
2588 if (SUCCEEDED(rc))
2589 mParent->onSnapshotDeleted(mData->mUuid, snapshotId);
2590
2591 LogFlowThisFunc(("Done deleting snapshot (rc=%08X)\n", rc));
2592 LogFlowThisFuncLeave();
2593}
2594
2595/**
2596 * Checks that this hard disk (part of a snapshot) may be deleted/merged and
2597 * performs necessary state changes. Must not be called for writethrough disks
2598 * because there is nothing to delete/merge then.
2599 *
2600 * This method is to be called prior to calling #deleteSnapshotMedium().
2601 * If #deleteSnapshotMedium() is not called or fails, the state modifications
2602 * performed by this method must be undone by #cancelDeleteSnapshotMedium().
2603 *
2604 * @param aHD Hard disk which is connected to the snapshot.
2605 * @param aMachineId UUID of machine this hard disk is attached to.
2606 * @param aSnapshotId UUID of snapshot this hard disk is attached to. May
2607 * be a zero UUID if no snapshot is applicable.
2608 * @param fOnlineMergePossible Flag whether an online merge is possible.
2609 * @param aVMMALockList Medium lock list for the medium attachment of this VM.
2610 * Only used if @a fOnlineMergePossible is @c true, and
2611 * must be non-NULL in this case.
2612 * @param aSource Source hard disk for merge (out).
2613 * @param aTarget Target hard disk for merge (out).
2614 * @param aMergeForward Merge direction decision (out).
2615 * @param aParentForTarget New parent if target needs to be reparented (out).
2616 * @param aChildrenToReparent Children which have to be reparented to the
2617 * target (out).
2618 * @param fNeedsOnlineMerge Whether this merge needs to be done online (out).
2619 * If this is set to @a true then the @a aVMMALockList
2620 * parameter has been modified and is returned as
2621 * @a aMediumLockList.
2622 * @param aMediumLockList Where to store the created medium lock list (may
2623 * return NULL if no real merge is necessary).
2624 *
2625 * @note Caller must hold media tree lock for writing. This locks this object
2626 * and every medium object on the merge chain for writing.
2627 */
2628HRESULT SessionMachine::prepareDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
2629 const Guid &aMachineId,
2630 const Guid &aSnapshotId,
2631 bool fOnlineMergePossible,
2632 MediumLockList *aVMMALockList,
2633 ComObjPtr<Medium> &aSource,
2634 ComObjPtr<Medium> &aTarget,
2635 bool &aMergeForward,
2636 ComObjPtr<Medium> &aParentForTarget,
2637 MediaList &aChildrenToReparent,
2638 bool &fNeedsOnlineMerge,
2639 MediumLockList * &aMediumLockList)
2640{
2641 Assert(mParent->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
2642 Assert(!fOnlineMergePossible || VALID_PTR(aVMMALockList));
2643
2644 AutoWriteLock alock(aHD COMMA_LOCKVAL_SRC_POS);
2645
2646 // Medium must not be writethrough at this point
2647 AssertReturn(aHD->getType() != MediumType_Writethrough, E_FAIL);
2648
2649 aMediumLockList = NULL;
2650 fNeedsOnlineMerge = false;
2651
2652 if (aHD->getChildren().size() == 0)
2653 {
2654 /* This technically is no merge, set those values nevertheless.
2655 * Helps with updating the medium attachments. */
2656 aSource = aHD;
2657 aTarget = aHD;
2658
2659 /* special treatment of the last hard disk in the chain: */
2660 if (aHD->getParent().isNull())
2661 {
2662 /* lock only, to prevent any usage until the snapshot deletion
2663 * is completed */
2664 return aHD->LockWrite(NULL);
2665 }
2666
2667 /* the differencing hard disk w/o children will be deleted, protect it
2668 * from attaching to other VMs (this is why Deleting) */
2669 return aHD->markForDeletion();
2670 }
2671
2672 /* not going multi-merge as it's too expensive */
2673 if (aHD->getChildren().size() > 1)
2674 return setError(E_FAIL,
2675 tr("Hard disk '%s' has more than one child hard disk (%d)"),
2676 aHD->getLocationFull().raw(),
2677 aHD->getChildren().size());
2678
2679 ComObjPtr<Medium> pChild = aHD->getChildren().front();
2680
2681 /* we keep this locked, so lock the affected child to make sure the lock
2682 * order is correct when calling prepareMergeTo() */
2683 AutoWriteLock childLock(pChild COMMA_LOCKVAL_SRC_POS);
2684
2685 /* the rest is a normal merge setup */
2686 if (aHD->getParent().isNull())
2687 {
2688 /* base hard disk, backward merge */
2689 const Guid *pMachineId1 = pChild->getFirstMachineBackrefId();
2690 const Guid *pMachineId2 = aHD->getFirstMachineBackrefId();
2691 if (pMachineId1 && pMachineId2 && *pMachineId1 != *pMachineId2)
2692 {
2693 /* backward merge is too tricky, we'll just detach on snapshot
2694 * deletion, so lock only, to prevent any usage */
2695 return aHD->LockWrite(NULL);
2696 }
2697
2698 aSource = pChild;
2699 aTarget = aHD;
2700 }
2701 else
2702 {
2703 /* forward merge */
2704 aSource = aHD;
2705 aTarget = pChild;
2706 }
2707
2708 HRESULT rc;
2709 rc = aSource->prepareMergeTo(aTarget, &aMachineId, &aSnapshotId, false,
2710 aMergeForward, aParentForTarget,
2711 aChildrenToReparent, aMediumLockList);
2712 if (SUCCEEDED(rc))
2713 {
2714 /* Try to lock the newly constructed medium lock list. If it succeeds
2715 * this can be handled as an offline merge, i.e. without the need of
2716 * asking the VM to do the merging. Only continue with the online
2717 * merging preparation if applicable. */
2718 rc = aMediumLockList->Lock();
2719 if (FAILED(rc) && fOnlineMergePossible)
2720 {
2721 /* Locking failed, this cannot be done as an offline merge. Try to
2722 * combine the locking information into the lock list of the medium
2723 * attachment in the running VM. If that fails or locking the
2724 * resulting lock list fails then the merge cannot be done online.
2725 * It can be repeated by the user when the VM is shut down. */
2726 MediumLockList::Base::iterator lockListVMMABegin =
2727 aVMMALockList->GetBegin();
2728 MediumLockList::Base::iterator lockListVMMAEnd =
2729 aVMMALockList->GetEnd();
2730 MediumLockList::Base::iterator lockListBegin =
2731 aMediumLockList->GetBegin();
2732 MediumLockList::Base::iterator lockListEnd =
2733 aMediumLockList->GetEnd();
2734 for (MediumLockList::Base::iterator it = lockListVMMABegin,
2735 it2 = lockListBegin;
2736 it2 != lockListEnd;
2737 ++it, ++it2)
2738 {
2739 if ( it == lockListVMMAEnd
2740 || it->GetMedium() != it2->GetMedium())
2741 {
2742 fOnlineMergePossible = false;
2743 break;
2744 }
2745 bool fLockReq = (it2->GetLockRequest() || it->GetLockRequest());
2746 rc = it->UpdateLock(fLockReq);
2747 if (FAILED(rc))
2748 {
2749 // could not update the lock, trigger cleanup below
2750 fOnlineMergePossible = false;
2751 break;
2752 }
2753 }
2754 if (fOnlineMergePossible)
2755 {
2756 rc = aVMMALockList->Lock();
2757 if (FAILED(rc))
2758 {
2759 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2760 rc = setError(rc,
2761 tr("Cannot lock hard disk '%s' for a live merge"),
2762 aHD->getLocationFull().raw());
2763 }
2764 else
2765 {
2766 delete aMediumLockList;
2767 aMediumLockList = aVMMALockList;
2768 fNeedsOnlineMerge = true;
2769 }
2770 }
2771 else
2772 {
2773 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2774 rc = setError(rc,
2775 tr("Failed to construct lock list for a live merge of hard disk '%s'"),
2776 aHD->getLocationFull().raw());
2777 }
2778
2779 // fix the VM's lock list if anything failed
2780 if (FAILED(rc))
2781 {
2782 lockListVMMABegin = aVMMALockList->GetBegin();
2783 lockListVMMAEnd = aVMMALockList->GetEnd();
2784 MediumLockList::Base::iterator lockListLast = lockListVMMAEnd;
2785 lockListLast--;
2786 for (MediumLockList::Base::iterator it = lockListVMMABegin;
2787 it != lockListVMMAEnd;
2788 ++it)
2789 {
2790 it->UpdateLock(it == lockListLast);
2791 ComObjPtr<Medium> pMedium = it->GetMedium();
2792 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
2793 // blindly apply this, only needed for medium objects which
2794 // would be deleted as part of the merge
2795 pMedium->unmarkLockedForDeletion();
2796 }
2797 }
2798
2799 }
2800 else
2801 {
2802 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2803 rc = setError(rc,
2804 tr("Cannot lock hard disk '%s' for an offline merge"),
2805 aHD->getLocationFull().raw());
2806 }
2807 }
2808
2809 return rc;
2810}
2811
2812/**
2813 * Cancels the deletion/merging of this hard disk (part of a snapshot). Undoes
2814 * what #prepareDeleteSnapshotMedium() did. Must be called if
2815 * #deleteSnapshotMedium() is not called or fails.
2816 *
2817 * @param aHD Hard disk which is connected to the snapshot.
2818 * @param aSource Source hard disk for merge.
2819 * @param aChildrenToReparent Children to unlock.
2820 * @param fNeedsOnlineMerge Whether this merge needs to be done online.
2821 * @param aMediumLockList Medium locks to cancel.
2822 * @param aMachineId Machine id to attach the medium to.
2823 * @param aSnapshotId Snapshot id to attach the medium to.
2824 *
2825 * @note Locks the medium tree and the hard disks in the chain for writing.
2826 */
2827void SessionMachine::cancelDeleteSnapshotMedium(const ComObjPtr<Medium> &aHD,
2828 const ComObjPtr<Medium> &aSource,
2829 const MediaList &aChildrenToReparent,
2830 bool fNeedsOnlineMerge,
2831 MediumLockList *aMediumLockList,
2832 const Guid &aMachineId,
2833 const Guid &aSnapshotId)
2834{
2835 if (aMediumLockList == NULL)
2836 {
2837 AutoMultiWriteLock2 mLock(&mParent->getMediaTreeLockHandle(), aHD->lockHandle() COMMA_LOCKVAL_SRC_POS);
2838
2839 Assert(aHD->getChildren().size() == 0);
2840
2841 if (aHD->getParent().isNull())
2842 {
2843 HRESULT rc = aHD->UnlockWrite(NULL);;
2844 AssertComRC(rc);
2845 }
2846 else
2847 {
2848 HRESULT rc = aHD->unmarkForDeletion();
2849 AssertComRC(rc);
2850 }
2851 }
2852 else
2853 {
2854 if (fNeedsOnlineMerge)
2855 {
2856 // Online merge uses the medium lock list of the VM, so give
2857 // an empty list to cancelMergeTo so that it works as designed.
2858 aSource->cancelMergeTo(aChildrenToReparent, new MediumLockList());
2859
2860 // clean up the VM medium lock list ourselves
2861 MediumLockList::Base::iterator lockListBegin =
2862 aMediumLockList->GetBegin();
2863 MediumLockList::Base::iterator lockListEnd =
2864 aMediumLockList->GetEnd();
2865 MediumLockList::Base::iterator lockListLast = lockListEnd;
2866 lockListLast--;
2867 for (MediumLockList::Base::iterator it = lockListBegin;
2868 it != lockListEnd;
2869 ++it)
2870 {
2871 it->UpdateLock(it == lockListLast);
2872 ComObjPtr<Medium> pMedium = it->GetMedium();
2873 AutoWriteLock mediumLock(pMedium COMMA_LOCKVAL_SRC_POS);
2874 // blindly apply this, only needed for medium objects which
2875 // would be deleted as part of the merge
2876 pMedium->unmarkLockedForDeletion();
2877 }
2878 }
2879 else
2880 {
2881 aSource->cancelMergeTo(aChildrenToReparent, aMediumLockList);
2882 }
2883 }
2884
2885 if (!aMachineId.isEmpty())
2886 {
2887 // reattach the source media to the snapshot
2888 HRESULT rc = aSource->attachTo(aMachineId, aSnapshotId);
2889 AssertComRC(rc);
2890 }
2891}
Note: See TracBrowser for help on using the repository browser.

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