VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxManageSnapshot.cpp@ 55443

Last change on this file since 55443 was 55234, checked in by vboxsync, 10 years ago

VBoxManage: ISession->GetMachine() should not overwrite 'machine' but use a separate 'sessionMachine' variable

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 18.4 KB
Line 
1/* $Id: VBoxManageSnapshot.cpp 55234 2015-04-14 09:13:33Z vboxsync $ */
2/** @file
3 * VBoxManage - The 'snapshot' command.
4 */
5
6/*
7 * Copyright (C) 2006-2014 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21#include <VBox/com/com.h>
22#include <VBox/com/string.h>
23#include <VBox/com/array.h>
24#include <VBox/com/ErrorInfo.h>
25#include <VBox/com/errorprint.h>
26
27#include <VBox/com/VirtualBox.h>
28
29#include <iprt/stream.h>
30#include <iprt/getopt.h>
31
32#include "VBoxManage.h"
33using namespace com;
34
35/**
36 * Helper function used with "VBoxManage snapshot ... dump". Gets called to find the
37 * snapshot in the machine's snapshot tree that uses a particular diff image child of
38 * a medium.
39 * Horribly inefficient since we keep re-querying the snapshots tree for each image,
40 * but this is for quick debugging only.
41 * @param pMedium
42 * @param pThisSnapshot
43 * @param pCurrentSnapshot
44 * @param uMediumLevel
45 * @param uSnapshotLevel
46 * @return
47 */
48bool FindAndPrintSnapshotUsingMedium(ComPtr<IMedium> &pMedium,
49 ComPtr<ISnapshot> &pThisSnapshot,
50 ComPtr<ISnapshot> &pCurrentSnapshot,
51 uint32_t uMediumLevel,
52 uint32_t uSnapshotLevel)
53{
54 HRESULT rc;
55
56 do
57 {
58 // get snapshot machine so we can figure out which diff image this created
59 ComPtr<IMachine> pSnapshotMachine;
60 CHECK_ERROR_BREAK(pThisSnapshot, COMGETTER(Machine)(pSnapshotMachine.asOutParam()));
61
62 // get media attachments
63 SafeIfaceArray<IMediumAttachment> aAttachments;
64 CHECK_ERROR_BREAK(pSnapshotMachine, COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(aAttachments)));
65
66 for (uint32_t i = 0;
67 i < aAttachments.size();
68 ++i)
69 {
70 ComPtr<IMediumAttachment> pAttach(aAttachments[i]);
71 DeviceType_T type;
72 CHECK_ERROR_BREAK(pAttach, COMGETTER(Type)(&type));
73 if (type == DeviceType_HardDisk)
74 {
75 ComPtr<IMedium> pMediumInSnapshot;
76 CHECK_ERROR_BREAK(pAttach, COMGETTER(Medium)(pMediumInSnapshot.asOutParam()));
77
78 if (pMediumInSnapshot == pMedium)
79 {
80 // get snapshot name
81 Bstr bstrSnapshotName;
82 CHECK_ERROR_BREAK(pThisSnapshot, COMGETTER(Name)(bstrSnapshotName.asOutParam()));
83
84 RTPrintf("%*s \"%ls\"%s\n",
85 50 + uSnapshotLevel * 2, "", // indent
86 bstrSnapshotName.raw(),
87 (pThisSnapshot == pCurrentSnapshot) ? " (CURSNAP)" : "");
88 return true; // found
89 }
90 }
91 }
92
93 // not found: then recurse into child snapshots
94 SafeIfaceArray<ISnapshot> aSnapshots;
95 CHECK_ERROR_BREAK(pThisSnapshot, COMGETTER(Children)(ComSafeArrayAsOutParam(aSnapshots)));
96
97 for (uint32_t i = 0;
98 i < aSnapshots.size();
99 ++i)
100 {
101 ComPtr<ISnapshot> pChild(aSnapshots[i]);
102 if (FindAndPrintSnapshotUsingMedium(pMedium,
103 pChild,
104 pCurrentSnapshot,
105 uMediumLevel,
106 uSnapshotLevel + 1))
107 // found:
108 break;
109 }
110 } while (0);
111
112 return false;
113}
114
115/**
116 * Helper function used with "VBoxManage snapshot ... dump". Called from DumpSnapshot()
117 * for each hard disk attachment found in a virtual machine. This then writes out the
118 * root (base) medium for that hard disk attachment and recurses into the children
119 * tree of that medium, correlating it with the snapshots of the machine.
120 * @param pCurrentStateMedium constant, the medium listed in the current machine data (latest diff image).
121 * @param pMedium variant, initially the base medium, then a child of the base medium when recursing.
122 * @param pRootSnapshot constant, the root snapshot of the machine, if any; this then looks into the child snapshots.
123 * @param pCurrentSnapshot constant, the machine's current snapshot (so we can mark it in the output).
124 * @param uLevel variant, the recursion level for output indentation.
125 */
126void DumpMediumWithChildren(ComPtr<IMedium> &pCurrentStateMedium,
127 ComPtr<IMedium> &pMedium,
128 ComPtr<ISnapshot> &pRootSnapshot,
129 ComPtr<ISnapshot> &pCurrentSnapshot,
130 uint32_t uLevel)
131{
132 HRESULT rc;
133 do
134 {
135 // print this medium
136 Bstr bstrMediumName;
137 CHECK_ERROR_BREAK(pMedium, COMGETTER(Name)(bstrMediumName.asOutParam()));
138 RTPrintf("%*s \"%ls\"%s\n",
139 uLevel * 2, "", // indent
140 bstrMediumName.raw(),
141 (pCurrentStateMedium == pMedium) ? " (CURSTATE)" : "");
142
143 // find and print the snapshot that uses this particular medium (diff image)
144 FindAndPrintSnapshotUsingMedium(pMedium, pRootSnapshot, pCurrentSnapshot, uLevel, 0);
145
146 // recurse into children
147 SafeIfaceArray<IMedium> aChildren;
148 CHECK_ERROR_BREAK(pMedium, COMGETTER(Children)(ComSafeArrayAsOutParam(aChildren)));
149 for (uint32_t i = 0;
150 i < aChildren.size();
151 ++i)
152 {
153 ComPtr<IMedium> pChild(aChildren[i]);
154 DumpMediumWithChildren(pCurrentStateMedium, pChild, pRootSnapshot, pCurrentSnapshot, uLevel + 1);
155 }
156 } while (0);
157}
158
159
160/**
161 * Handles the 'snapshot myvm list' sub-command.
162 * @returns Exit code.
163 * @param pArgs The handler argument package.
164 * @param pMachine Reference to the VM (locked) we're operating on.
165 */
166static RTEXITCODE handleSnapshotList(HandlerArg *pArgs, ComPtr<IMachine> &pMachine)
167{
168 static const RTGETOPTDEF g_aOptions[] =
169 {
170 { "--details", 'D', RTGETOPT_REQ_NOTHING },
171 { "--machinereadable", 'M', RTGETOPT_REQ_NOTHING },
172 };
173
174 VMINFO_DETAILS enmDetails = VMINFO_STANDARD;
175
176 int c;
177 RTGETOPTUNION ValueUnion;
178 RTGETOPTSTATE GetState;
179 RTGetOptInit(&GetState, pArgs->argc, pArgs->argv, g_aOptions, RT_ELEMENTS(g_aOptions), 2 /*iArg*/, 0 /*fFlags*/);
180 while ((c = RTGetOpt(&GetState, &ValueUnion)))
181 {
182 switch (c)
183 {
184 case 'D': enmDetails = VMINFO_FULL; break;
185 case 'M': enmDetails = VMINFO_MACHINEREADABLE; break;
186 default: return errorGetOpt(USAGE_SNAPSHOT, c, &ValueUnion);
187 }
188 }
189
190 ComPtr<ISnapshot> pSnapshot;
191 HRESULT hrc = pMachine->FindSnapshot(Bstr().raw(), pSnapshot.asOutParam());
192 if (FAILED(hrc))
193 {
194 RTPrintf("This machine does not have any snapshots\n");
195 return RTEXITCODE_FAILURE;
196 }
197 if (pSnapshot)
198 {
199 ComPtr<ISnapshot> pCurrentSnapshot;
200 CHECK_ERROR2_RET(pMachine, COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam()), RTEXITCODE_FAILURE);
201 hrc = showSnapshots(pSnapshot, pCurrentSnapshot, enmDetails);
202 if (FAILED(hrc))
203 return RTEXITCODE_FAILURE;
204 }
205 return RTEXITCODE_SUCCESS;
206}
207
208/**
209 * Implementation for "VBoxManage snapshot ... dump". This goes thru the machine's
210 * medium attachments and calls DumpMediumWithChildren() for each hard disk medium found,
211 * which then dumps the parent/child tree of that medium together with the corresponding
212 * snapshots.
213 * @param pMachine Machine to dump snapshots for.
214 */
215void DumpSnapshot(ComPtr<IMachine> &pMachine)
216{
217 HRESULT rc;
218
219 do
220 {
221 // get root snapshot
222 ComPtr<ISnapshot> pSnapshot;
223 CHECK_ERROR_BREAK(pMachine, FindSnapshot(Bstr("").raw(), pSnapshot.asOutParam()));
224
225 // get current snapshot
226 ComPtr<ISnapshot> pCurrentSnapshot;
227 CHECK_ERROR_BREAK(pMachine, COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam()));
228
229 // get media attachments
230 SafeIfaceArray<IMediumAttachment> aAttachments;
231 CHECK_ERROR_BREAK(pMachine, COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(aAttachments)));
232 for (uint32_t i = 0;
233 i < aAttachments.size();
234 ++i)
235 {
236 ComPtr<IMediumAttachment> pAttach(aAttachments[i]);
237 DeviceType_T type;
238 CHECK_ERROR_BREAK(pAttach, COMGETTER(Type)(&type));
239 if (type == DeviceType_HardDisk)
240 {
241 ComPtr<IMedium> pCurrentStateMedium;
242 CHECK_ERROR_BREAK(pAttach, COMGETTER(Medium)(pCurrentStateMedium.asOutParam()));
243
244 ComPtr<IMedium> pBaseMedium;
245 CHECK_ERROR_BREAK(pCurrentStateMedium, COMGETTER(Base)(pBaseMedium.asOutParam()));
246
247 Bstr bstrBaseMediumName;
248 CHECK_ERROR_BREAK(pBaseMedium, COMGETTER(Name)(bstrBaseMediumName.asOutParam()));
249
250 RTPrintf("[%RI32] Images and snapshots for medium \"%ls\"\n", i, bstrBaseMediumName.raw());
251
252 DumpMediumWithChildren(pCurrentStateMedium,
253 pBaseMedium,
254 pSnapshot,
255 pCurrentSnapshot,
256 0);
257 }
258 }
259 } while (0);
260}
261
262/**
263 * Implementation for all VBoxManage snapshot ... subcommands.
264 * @param a
265 * @return
266 */
267int handleSnapshot(HandlerArg *a)
268{
269 HRESULT rc;
270
271 /* we need at least a VM and a command */
272 if (a->argc < 2)
273 return errorSyntax(USAGE_SNAPSHOT, "Not enough parameters");
274
275 /* the first argument must be the VM */
276 Bstr bstrMachine(a->argv[0]);
277 ComPtr<IMachine> pMachine;
278 CHECK_ERROR(a->virtualBox, FindMachine(bstrMachine.raw(),
279 pMachine.asOutParam()));
280 if (!pMachine)
281 return 1;
282
283 /* we have to open a session for this task (new or shared) */
284 CHECK_ERROR_RET(pMachine, LockMachine(a->session, LockType_Shared), 1);
285 do
286 {
287 /* replace the (read-only) IMachine object by a writable one */
288 ComPtr<IMachine> sessionMachine;
289 CHECK_ERROR_BREAK(a->session, COMGETTER(Machine)(sessionMachine.asOutParam()));
290
291 /* switch based on the command */
292 bool fDelete = false,
293 fRestore = false,
294 fRestoreCurrent = false;
295
296 if (!strcmp(a->argv[1], "take"))
297 {
298 /* there must be a name */
299 if (a->argc < 3)
300 {
301 errorSyntax(USAGE_SNAPSHOT, "Missing snapshot name");
302 rc = E_FAIL;
303 break;
304 }
305 Bstr name(a->argv[2]);
306
307 /* parse the optional arguments */
308 Bstr desc;
309 bool fPause = true; /* default is NO live snapshot */
310 static const RTGETOPTDEF s_aTakeOptions[] =
311 {
312 { "--description", 'd', RTGETOPT_REQ_STRING },
313 { "-description", 'd', RTGETOPT_REQ_STRING },
314 { "-desc", 'd', RTGETOPT_REQ_STRING },
315 { "--pause", 'p', RTGETOPT_REQ_NOTHING },
316 { "--live", 'l', RTGETOPT_REQ_NOTHING }
317 };
318 RTGETOPTSTATE GetOptState;
319 RTGetOptInit(&GetOptState, a->argc, a->argv, s_aTakeOptions, RT_ELEMENTS(s_aTakeOptions),
320 3, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
321 int ch;
322 RTGETOPTUNION Value;
323 while ( SUCCEEDED(rc)
324 && (ch = RTGetOpt(&GetOptState, &Value)))
325 {
326 switch (ch)
327 {
328 case 'p':
329 fPause = true;
330 break;
331
332 case 'l':
333 fPause = false;
334 break;
335
336 case 'd':
337 desc = Value.psz;
338 break;
339
340 default:
341 errorGetOpt(USAGE_SNAPSHOT, ch, &Value);
342 rc = E_FAIL;
343 break;
344 }
345 }
346 if (FAILED(rc))
347 break;
348
349 ComPtr<IProgress> progress;
350 CHECK_ERROR_BREAK(sessionMachine, TakeSnapshot(name.raw(), desc.raw(),
351 fPause,
352 progress.asOutParam()));
353
354 rc = showProgress(progress);
355 CHECK_PROGRESS_ERROR(progress, ("Failed to take snapshot"));
356 }
357 else if ( (fDelete = !strcmp(a->argv[1], "delete"))
358 || (fRestore = !strcmp(a->argv[1], "restore"))
359 || (fRestoreCurrent = !strcmp(a->argv[1], "restorecurrent"))
360 )
361 {
362 if (fRestoreCurrent)
363 {
364 if (a->argc > 2)
365 {
366 errorSyntax(USAGE_SNAPSHOT, "Too many arguments");
367 rc = E_FAIL;
368 break;
369 }
370 }
371 /* exactly one parameter: snapshot name */
372 else if (a->argc != 3)
373 {
374 errorSyntax(USAGE_SNAPSHOT, "Expecting snapshot name only");
375 rc = E_FAIL;
376 break;
377 }
378
379 ComPtr<ISnapshot> pSnapshot;
380 ComPtr<IProgress> pProgress;
381 Bstr bstrSnapGuid;
382
383 if (fRestoreCurrent)
384 {
385 CHECK_ERROR_BREAK(sessionMachine, COMGETTER(CurrentSnapshot)(pSnapshot.asOutParam()));
386 }
387 else
388 {
389 // restore or delete snapshot: then resolve cmd line argument to snapshot instance
390 CHECK_ERROR_BREAK(sessionMachine, FindSnapshot(Bstr(a->argv[2]).raw(),
391 pSnapshot.asOutParam()));
392 }
393
394 CHECK_ERROR_BREAK(pSnapshot, COMGETTER(Id)(bstrSnapGuid.asOutParam()));
395
396 if (fDelete)
397 {
398 CHECK_ERROR_BREAK(sessionMachine, DeleteSnapshot(bstrSnapGuid.raw(),
399 pProgress.asOutParam()));
400 }
401 else
402 {
403 // restore or restore current
404 RTPrintf("Restoring snapshot %ls\n", bstrSnapGuid.raw());
405 CHECK_ERROR_BREAK(sessionMachine, RestoreSnapshot(pSnapshot, pProgress.asOutParam()));
406 }
407
408 rc = showProgress(pProgress);
409 CHECK_PROGRESS_ERROR(pProgress, ("Snapshot operation failed"));
410 }
411 else if (!strcmp(a->argv[1], "edit"))
412 {
413 if (a->argc < 3)
414 {
415 errorSyntax(USAGE_SNAPSHOT, "Missing snapshot name");
416 rc = E_FAIL;
417 break;
418 }
419
420 ComPtr<ISnapshot> pSnapshot;
421
422 if ( !strcmp(a->argv[2], "--current")
423 || !strcmp(a->argv[2], "-current"))
424 {
425 CHECK_ERROR_BREAK(sessionMachine, COMGETTER(CurrentSnapshot)(pSnapshot.asOutParam()));
426 }
427 else
428 {
429 CHECK_ERROR_BREAK(sessionMachine, FindSnapshot(Bstr(a->argv[2]).raw(),
430 pSnapshot.asOutParam()));
431 }
432
433 /* parse options */
434 for (int i = 3; i < a->argc; i++)
435 {
436 if ( !strcmp(a->argv[i], "--name")
437 || !strcmp(a->argv[i], "-name")
438 || !strcmp(a->argv[i], "-newname"))
439 {
440 if (a->argc <= i + 1)
441 {
442 errorArgument("Missing argument to '%s'", a->argv[i]);
443 rc = E_FAIL;
444 break;
445 }
446 i++;
447 pSnapshot->COMSETTER(Name)(Bstr(a->argv[i]).raw());
448 }
449 else if ( !strcmp(a->argv[i], "--description")
450 || !strcmp(a->argv[i], "-description")
451 || !strcmp(a->argv[i], "-newdesc"))
452 {
453 if (a->argc <= i + 1)
454 {
455 errorArgument("Missing argument to '%s'", a->argv[i]);
456 rc = E_FAIL;
457 break;
458 }
459 i++;
460 pSnapshot->COMSETTER(Description)(Bstr(a->argv[i]).raw());
461 }
462 else
463 {
464 errorSyntax(USAGE_SNAPSHOT, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
465 rc = E_FAIL;
466 break;
467 }
468 }
469
470 }
471 else if (!strcmp(a->argv[1], "showvminfo"))
472 {
473 /* exactly one parameter: snapshot name */
474 if (a->argc != 3)
475 {
476 errorSyntax(USAGE_SNAPSHOT, "Expecting snapshot name only");
477 rc = E_FAIL;
478 break;
479 }
480
481 ComPtr<ISnapshot> pSnapshot;
482
483 CHECK_ERROR_BREAK(sessionMachine, FindSnapshot(Bstr(a->argv[2]).raw(),
484 pSnapshot.asOutParam()));
485
486 /* get the machine of the given snapshot */
487 ComPtr<IMachine> pMachine2;
488 pSnapshot->COMGETTER(Machine)(pMachine2.asOutParam());
489 showVMInfo(a->virtualBox, pMachine2, NULL, VMINFO_NONE);
490 }
491 else if (!strcmp(a->argv[1], "list"))
492 rc = handleSnapshotList(a, sessionMachine) == RTEXITCODE_SUCCESS ? S_OK : E_FAIL;
493 else if (!strcmp(a->argv[1], "dump")) // undocumented parameter to debug snapshot info
494 DumpSnapshot(sessionMachine);
495 else
496 {
497 errorSyntax(USAGE_SNAPSHOT, "Invalid parameter '%s'", Utf8Str(a->argv[1]).c_str());
498 rc = E_FAIL;
499 }
500 } while (0);
501
502 a->session->UnlockMachine();
503
504 return SUCCEEDED(rc) ? 0 : 1;
505}
506
Note: See TracBrowser for help on using the repository browser.

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