VirtualBox

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

Last change on this file since 98651 was 98352, checked in by vboxsync, 22 months ago

Main: Fix identifiers containing an incorrect plural of "medium".

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

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