VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/MachineImplCloneVM.cpp@ 53517

Last change on this file since 53517 was 53354, checked in by vboxsync, 10 years ago

R7524 - needs testing in VBoxManage.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 61.1 KB
Line 
1/* $Id: MachineImplCloneVM.cpp 53354 2014-11-19 18:32:03Z vboxsync $ */
2/** @file
3 * Implementation of MachineCloneVM
4 */
5
6/*
7 * Copyright (C) 2011-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#include "MachineImplCloneVM.h"
19
20#include "VirtualBoxImpl.h"
21#include "MediumImpl.h"
22#include "HostImpl.h"
23
24#include <iprt/path.h>
25#include <iprt/dir.h>
26#include <iprt/cpp/utils.h>
27#ifdef DEBUG_poetzsch
28# include <iprt/stream.h>
29#endif
30
31#include <VBox/com/list.h>
32#include <VBox/com/MultiResult.h>
33
34// typedefs
35/////////////////////////////////////////////////////////////////////////////
36
37typedef struct
38{
39 Utf8Str strBaseName;
40 ComPtr<IMedium> pMedium;
41 uint32_t uIdx;
42 ULONG uWeight;
43} MEDIUMTASK;
44
45typedef struct
46{
47 RTCList<MEDIUMTASK> chain;
48 bool fCreateDiffs;
49 bool fAttachLinked;
50} MEDIUMTASKCHAIN;
51
52typedef struct
53{
54 Guid snapshotUuid;
55 Utf8Str strSaveStateFile;
56 ULONG uWeight;
57} SAVESTATETASK;
58
59// The private class
60/////////////////////////////////////////////////////////////////////////////
61
62struct MachineCloneVMPrivate
63{
64 MachineCloneVMPrivate(MachineCloneVM *a_q, ComObjPtr<Machine> &a_pSrcMachine, ComObjPtr<Machine> &a_pTrgMachine,
65 CloneMode_T a_mode, const RTCList<CloneOptions_T> &opts)
66 : q_ptr(a_q)
67 , p(a_pSrcMachine)
68 , pSrcMachine(a_pSrcMachine)
69 , pTrgMachine(a_pTrgMachine)
70 , mode(a_mode)
71 , options(opts)
72 {}
73
74 /* Thread management */
75 int startWorker()
76 {
77 return RTThreadCreate(NULL,
78 MachineCloneVMPrivate::workerThread,
79 static_cast<void*>(this),
80 0,
81 RTTHREADTYPE_MAIN_WORKER,
82 0,
83 "MachineClone");
84 }
85
86 static int workerThread(RTTHREAD /* Thread */, void *pvUser)
87 {
88 MachineCloneVMPrivate *pTask = static_cast<MachineCloneVMPrivate*>(pvUser);
89 AssertReturn(pTask, VERR_INVALID_POINTER);
90
91 HRESULT rc = pTask->q_ptr->run();
92
93 pTask->pProgress->i_notifyComplete(rc);
94
95 pTask->q_ptr->destroy();
96
97 return VINF_SUCCESS;
98 }
99
100 /* Private helper methods */
101
102 /* MachineCloneVM::start helper: */
103 HRESULT createMachineList(const ComPtr<ISnapshot> &pSnapshot, RTCList< ComObjPtr<Machine> > &machineList) const;
104 inline void updateProgressStats(MEDIUMTASKCHAIN &mtc, bool fAttachLinked, ULONG &uCount, ULONG &uTotalWeight) const;
105 inline HRESULT addSaveState(const ComObjPtr<Machine> &machine, ULONG &uCount, ULONG &uTotalWeight);
106 inline HRESULT queryBaseName(const ComPtr<IMedium> &pMedium, Utf8Str &strBaseName) const;
107 HRESULT queryMediasForMachineState(const RTCList<ComObjPtr<Machine> > &machineList,
108 bool fAttachLinked, ULONG &uCount, ULONG &uTotalWeight);
109 HRESULT queryMediasForMachineAndChildStates(const RTCList<ComObjPtr<Machine> > &machineList,
110 bool fAttachLinked, ULONG &uCount, ULONG &uTotalWeight);
111 HRESULT queryMediasForAllStates(const RTCList<ComObjPtr<Machine> > &machineList, bool fAttachLinked, ULONG &uCount,
112 ULONG &uTotalWeight);
113
114 /* MachineCloneVM::run helper: */
115 bool findSnapshot(const settings::SnapshotsList &snl, const Guid &id, settings::Snapshot &sn) const;
116 void updateMACAddresses(settings::NetworkAdaptersList &nwl) const;
117 void updateMACAddresses(settings::SnapshotsList &sl) const;
118 void updateStorageLists(settings::StorageControllersList &sc, const Bstr &bstrOldId, const Bstr &bstrNewId) const;
119 void updateSnapshotStorageLists(settings::SnapshotsList &sl, const Bstr &bstrOldId, const Bstr &bstrNewId) const;
120 void updateStateFile(settings::SnapshotsList &snl, const Guid &id, const Utf8Str &strFile) const;
121 HRESULT createDifferencingMedium(const ComObjPtr<Machine> &pMachine, const ComObjPtr<Medium> &pParent,
122 const Utf8Str &strSnapshotFolder, RTCList<ComObjPtr<Medium> > &newMedia,
123 ComObjPtr<Medium> *ppDiff) const;
124 static int copyStateFileProgress(unsigned uPercentage, void *pvUser);
125
126 /* Private q and parent pointer */
127 MachineCloneVM *q_ptr;
128 ComObjPtr<Machine> p;
129
130 /* Private helper members */
131 ComObjPtr<Machine> pSrcMachine;
132 ComObjPtr<Machine> pTrgMachine;
133 ComPtr<IMachine> pOldMachineState;
134 ComObjPtr<Progress> pProgress;
135 Guid snapshotId;
136 CloneMode_T mode;
137 RTCList<CloneOptions_T> options;
138 RTCList<MEDIUMTASKCHAIN> llMedias;
139 RTCList<SAVESTATETASK> llSaveStateFiles; /* Snapshot UUID -> File path */
140};
141
142HRESULT MachineCloneVMPrivate::createMachineList(const ComPtr<ISnapshot> &pSnapshot,
143 RTCList< ComObjPtr<Machine> > &machineList) const
144{
145 HRESULT rc = S_OK;
146 Bstr name;
147 rc = pSnapshot->COMGETTER(Name)(name.asOutParam());
148 if (FAILED(rc)) return rc;
149
150 ComPtr<IMachine> pMachine;
151 rc = pSnapshot->COMGETTER(Machine)(pMachine.asOutParam());
152 if (FAILED(rc)) return rc;
153 machineList.append((Machine*)(IMachine*)pMachine);
154
155 SafeIfaceArray<ISnapshot> sfaChilds;
156 rc = pSnapshot->COMGETTER(Children)(ComSafeArrayAsOutParam(sfaChilds));
157 if (FAILED(rc)) return rc;
158 for (size_t i = 0; i < sfaChilds.size(); ++i)
159 {
160 rc = createMachineList(sfaChilds[i], machineList);
161 if (FAILED(rc)) return rc;
162 }
163
164 return rc;
165}
166
167void MachineCloneVMPrivate::updateProgressStats(MEDIUMTASKCHAIN &mtc, bool fAttachLinked,
168 ULONG &uCount, ULONG &uTotalWeight) const
169{
170 if (fAttachLinked)
171 {
172 /* Implicit diff creation as part of attach is a pretty cheap
173 * operation, and does only need one operation per attachment. */
174 ++uCount;
175 uTotalWeight += 1; /* 1MB per attachment */
176 }
177 else
178 {
179 /* Currently the copying of diff images involves reading at least
180 * the biggest parent in the previous chain. So even if the new
181 * diff image is small in size, it could need some time to create
182 * it. Adding the biggest size in the chain should balance this a
183 * little bit more, i.e. the weight is the sum of the data which
184 * needs to be read and written. */
185 ULONG uMaxWeight = 0;
186 for (size_t e = mtc.chain.size(); e > 0; --e)
187 {
188 MEDIUMTASK &mt = mtc.chain.at(e - 1);
189 mt.uWeight += uMaxWeight;
190
191 /* Calculate progress data */
192 ++uCount;
193 uTotalWeight += mt.uWeight;
194
195 /* Save the max size for better weighting of diff image
196 * creation. */
197 uMaxWeight = RT_MAX(uMaxWeight, mt.uWeight);
198 }
199 }
200}
201
202HRESULT MachineCloneVMPrivate::addSaveState(const ComObjPtr<Machine> &machine, ULONG &uCount, ULONG &uTotalWeight)
203{
204 Bstr bstrSrcSaveStatePath;
205 HRESULT rc = machine->COMGETTER(StateFilePath)(bstrSrcSaveStatePath.asOutParam());
206 if (FAILED(rc)) return rc;
207 if (!bstrSrcSaveStatePath.isEmpty())
208 {
209 SAVESTATETASK sst;
210 sst.snapshotUuid = machine->i_getSnapshotId();
211 sst.strSaveStateFile = bstrSrcSaveStatePath;
212 uint64_t cbSize;
213 int vrc = RTFileQuerySize(sst.strSaveStateFile.c_str(), &cbSize);
214 if (RT_FAILURE(vrc))
215 return p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not query file size of '%s' (%Rrc)"),
216 sst.strSaveStateFile.c_str(), vrc);
217 /* same rule as above: count both the data which needs to
218 * be read and written */
219 sst.uWeight = (ULONG)(2 * (cbSize + _1M - 1) / _1M);
220 llSaveStateFiles.append(sst);
221 ++uCount;
222 uTotalWeight += sst.uWeight;
223 }
224 return S_OK;
225}
226
227HRESULT MachineCloneVMPrivate::queryBaseName(const ComPtr<IMedium> &pMedium, Utf8Str &strBaseName) const
228{
229 ComPtr<IMedium> pBaseMedium;
230 HRESULT rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
231 if (FAILED(rc)) return rc;
232 Bstr bstrBaseName;
233 rc = pBaseMedium->COMGETTER(Name)(bstrBaseName.asOutParam());
234 if (FAILED(rc)) return rc;
235 strBaseName = bstrBaseName;
236 return rc;
237}
238
239HRESULT MachineCloneVMPrivate::queryMediasForMachineState(const RTCList<ComObjPtr<Machine> > &machineList,
240 bool fAttachLinked, ULONG &uCount, ULONG &uTotalWeight)
241{
242 /* This mode is pretty straightforward. We didn't need to know about any
243 * parent/children relationship and therefor simply adding all directly
244 * attached images of the source VM as cloning targets. The IMedium code
245 * take than care to merge any (possibly) existing parents into the new
246 * image. */
247 HRESULT rc = S_OK;
248 for (size_t i = 0; i < machineList.size(); ++i)
249 {
250 const ComObjPtr<Machine> &machine = machineList.at(i);
251 /* If this is the Snapshot Machine we want to clone, we need to
252 * create a new diff file for the new "current state". */
253 const bool fCreateDiffs = (machine == pOldMachineState);
254 /* Add all attachments of the different machines to a worker list. */
255 SafeIfaceArray<IMediumAttachment> sfaAttachments;
256 rc = machine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
257 if (FAILED(rc)) return rc;
258 for (size_t a = 0; a < sfaAttachments.size(); ++a)
259 {
260 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
261 DeviceType_T type;
262 rc = pAtt->COMGETTER(Type)(&type);
263 if (FAILED(rc)) return rc;
264
265 /* Only harddisk's are of interest. */
266 if (type != DeviceType_HardDisk)
267 continue;
268
269 /* Valid medium attached? */
270 ComPtr<IMedium> pSrcMedium;
271 rc = pAtt->COMGETTER(Medium)(pSrcMedium.asOutParam());
272 if (FAILED(rc)) return rc;
273 if (pSrcMedium.isNull())
274 continue;
275
276 /* Create the medium task chain. In this case it will always
277 * contain one image only. */
278 MEDIUMTASKCHAIN mtc;
279 mtc.fCreateDiffs = fCreateDiffs;
280 mtc.fAttachLinked = fAttachLinked;
281
282 /* Refresh the state so that the file size get read. */
283 MediumState_T e;
284 rc = pSrcMedium->RefreshState(&e);
285 if (FAILED(rc)) return rc;
286 LONG64 lSize;
287 rc = pSrcMedium->COMGETTER(Size)(&lSize);
288 if (FAILED(rc)) return rc;
289
290 MEDIUMTASK mt;
291 mt.uIdx = UINT32_MAX; /* No read/write optimization possible. */
292
293 /* Save the base name. */
294 rc = queryBaseName(pSrcMedium, mt.strBaseName);
295 if (FAILED(rc)) return rc;
296
297 /* Save the current medium, for later cloning. */
298 mt.pMedium = pSrcMedium;
299 if (fAttachLinked)
300 mt.uWeight = 0; /* dummy */
301 else
302 mt.uWeight = (ULONG)((lSize + _1M - 1) / _1M);
303 mtc.chain.append(mt);
304
305 /* Update the progress info. */
306 updateProgressStats(mtc, fAttachLinked, uCount, uTotalWeight);
307 /* Append the list of images which have to be cloned. */
308 llMedias.append(mtc);
309 }
310 /* Add the save state files of this machine if there is one. */
311 rc = addSaveState(machine, uCount, uTotalWeight);
312 if (FAILED(rc)) return rc;
313 }
314
315 return rc;
316}
317
318HRESULT MachineCloneVMPrivate::queryMediasForMachineAndChildStates(const RTCList<ComObjPtr<Machine> > &machineList,
319 bool fAttachLinked, ULONG &uCount, ULONG &uTotalWeight)
320{
321 /* This is basically a three step approach. First select all medias
322 * directly or indirectly involved in the clone. Second create a histogram
323 * of the usage of all that medias. Third select the medias which are
324 * directly attached or have more than one directly/indirectly used child
325 * in the new clone. Step one and two are done in the first loop.
326 *
327 * Example of the histogram counts after going through 3 attachments from
328 * bottom to top:
329 *
330 * 3
331 * |
332 * -> 3
333 * / \
334 * 2 1 <-
335 * /
336 * -> 2
337 * / \
338 * -> 1 1
339 * \
340 * 1 <-
341 *
342 * Whenever the histogram count is changing compared to the previous one we
343 * need to include that image in the cloning step (Marked with <-). If we
344 * start at zero even the directly attached images are automatically
345 * included.
346 *
347 * Note: This still leads to media chains which can have the same medium
348 * included. This case is handled in "run" and therefor not critical, but
349 * it leads to wrong progress infos which isn't nice. */
350
351 HRESULT rc = S_OK;
352 std::map<ComPtr<IMedium>, uint32_t> mediaHist; /* Our usage histogram for the medias */
353 for (size_t i = 0; i < machineList.size(); ++i)
354 {
355 const ComObjPtr<Machine> &machine = machineList.at(i);
356 /* If this is the Snapshot Machine we want to clone, we need to
357 * create a new diff file for the new "current state". */
358 const bool fCreateDiffs = (machine == pOldMachineState);
359 /* Add all attachments (and their parents) of the different
360 * machines to a worker list. */
361 SafeIfaceArray<IMediumAttachment> sfaAttachments;
362 rc = machine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
363 if (FAILED(rc)) return rc;
364 for (size_t a = 0; a < sfaAttachments.size(); ++a)
365 {
366 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
367 DeviceType_T type;
368 rc = pAtt->COMGETTER(Type)(&type);
369 if (FAILED(rc)) return rc;
370
371 /* Only harddisk's are of interest. */
372 if (type != DeviceType_HardDisk)
373 continue;
374
375 /* Valid medium attached? */
376 ComPtr<IMedium> pSrcMedium;
377 rc = pAtt->COMGETTER(Medium)(pSrcMedium.asOutParam());
378 if (FAILED(rc)) return rc;
379
380 if (pSrcMedium.isNull())
381 continue;
382
383 MEDIUMTASKCHAIN mtc;
384 mtc.fCreateDiffs = fCreateDiffs;
385 mtc.fAttachLinked = fAttachLinked;
386
387 while (!pSrcMedium.isNull())
388 {
389 /* Build a histogram of used medias and the parent chain. */
390 ++mediaHist[pSrcMedium];
391
392 /* Refresh the state so that the file size get read. */
393 MediumState_T e;
394 rc = pSrcMedium->RefreshState(&e);
395 if (FAILED(rc)) return rc;
396 LONG64 lSize;
397 rc = pSrcMedium->COMGETTER(Size)(&lSize);
398 if (FAILED(rc)) return rc;
399
400 MEDIUMTASK mt;
401 mt.uIdx = UINT32_MAX;
402 mt.pMedium = pSrcMedium;
403 mt.uWeight = (ULONG)((lSize + _1M - 1) / _1M);
404 mtc.chain.append(mt);
405
406 /* Query next parent. */
407 rc = pSrcMedium->COMGETTER(Parent)(pSrcMedium.asOutParam());
408 if (FAILED(rc)) return rc;
409 }
410
411 llMedias.append(mtc);
412 }
413 /* Add the save state files of this machine if there is one. */
414 rc = addSaveState(machine, uCount, uTotalWeight);
415 if (FAILED(rc)) return rc;
416 }
417 /* Build up the index list of the image chain. Unfortunately we can't do
418 * that in the previous loop, cause there we go from child -> parent and
419 * didn't know how many are between. */
420 for (size_t i = 0; i < llMedias.size(); ++i)
421 {
422 uint32_t uIdx = 0;
423 MEDIUMTASKCHAIN &mtc = llMedias.at(i);
424 for (size_t a = mtc.chain.size(); a > 0; --a)
425 mtc.chain[a - 1].uIdx = uIdx++;
426 }
427#ifdef DEBUG_poetzsch
428 /* Print the histogram */
429 std::map<ComPtr<IMedium>, uint32_t>::iterator it;
430 for (it = mediaHist.begin(); it != mediaHist.end(); ++it)
431 {
432 Bstr bstrSrcName;
433 rc = (*it).first->COMGETTER(Name)(bstrSrcName.asOutParam());
434 if (FAILED(rc)) return rc;
435 RTPrintf("%ls: %d\n", bstrSrcName.raw(), (*it).second);
436 }
437#endif
438 /* Go over every medium in the list and check if it either a directly
439 * attached disk or has more than one children. If so it needs to be
440 * replicated. Also we have to make sure that any direct or indirect
441 * children knows of the new parent (which doesn't necessarily mean it
442 * is a direct children in the source chain). */
443 for (size_t i = 0; i < llMedias.size(); ++i)
444 {
445 MEDIUMTASKCHAIN &mtc = llMedias.at(i);
446 RTCList<MEDIUMTASK> newChain;
447 uint32_t used = 0;
448 for (size_t a = 0; a < mtc.chain.size(); ++a)
449 {
450 const MEDIUMTASK &mt = mtc.chain.at(a);
451 uint32_t hist = mediaHist[mt.pMedium];
452#ifdef DEBUG_poetzsch
453 Bstr bstrSrcName;
454 rc = mt.pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
455 if (FAILED(rc)) return rc;
456 RTPrintf("%ls: %d (%d)\n", bstrSrcName.raw(), hist, used);
457#endif
458 /* Check if there is a "step" in the histogram when going the chain
459 * upwards. If so, we need this image, cause there is another branch
460 * from here in the cloned VM. */
461 if (hist > used)
462 {
463 newChain.append(mt);
464 used = hist;
465 }
466 }
467 /* Make sure we always using the old base name as new base name, even
468 * if the base is a differencing image in the source VM (with the UUID
469 * as name). */
470 rc = queryBaseName(newChain.last().pMedium, newChain.last().strBaseName);
471 if (FAILED(rc)) return rc;
472 /* Update the old medium chain with the updated one. */
473 mtc.chain = newChain;
474 /* Update the progress info. */
475 updateProgressStats(mtc, fAttachLinked, uCount, uTotalWeight);
476 }
477
478 return rc;
479}
480
481HRESULT MachineCloneVMPrivate::queryMediasForAllStates(const RTCList<ComObjPtr<Machine> > &machineList,
482 bool fAttachLinked, ULONG &uCount, ULONG &uTotalWeight)
483{
484 /* In this case we create a exact copy of the original VM. This means just
485 * adding all directly and indirectly attached disk images to the worker
486 * list. */
487 HRESULT rc = S_OK;
488 for (size_t i = 0; i < machineList.size(); ++i)
489 {
490 const ComObjPtr<Machine> &machine = machineList.at(i);
491 /* If this is the Snapshot Machine we want to clone, we need to
492 * create a new diff file for the new "current state". */
493 const bool fCreateDiffs = (machine == pOldMachineState);
494 /* Add all attachments (and their parents) of the different
495 * machines to a worker list. */
496 SafeIfaceArray<IMediumAttachment> sfaAttachments;
497 rc = machine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
498 if (FAILED(rc)) return rc;
499 for (size_t a = 0; a < sfaAttachments.size(); ++a)
500 {
501 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
502 DeviceType_T type;
503 rc = pAtt->COMGETTER(Type)(&type);
504 if (FAILED(rc)) return rc;
505
506 /* Only harddisk's are of interest. */
507 if (type != DeviceType_HardDisk)
508 continue;
509
510 /* Valid medium attached? */
511 ComPtr<IMedium> pSrcMedium;
512 rc = pAtt->COMGETTER(Medium)(pSrcMedium.asOutParam());
513 if (FAILED(rc)) return rc;
514 if (pSrcMedium.isNull())
515 continue;
516
517 /* Build up a child->parent list of this attachment. (Note: we are
518 * not interested of any child's not attached to this VM. So this
519 * will not create a full copy of the base/child relationship.) */
520 MEDIUMTASKCHAIN mtc;
521 mtc.fCreateDiffs = fCreateDiffs;
522 mtc.fAttachLinked = fAttachLinked;
523
524 while (!pSrcMedium.isNull())
525 {
526 /* Refresh the state so that the file size get read. */
527 MediumState_T e;
528 rc = pSrcMedium->RefreshState(&e);
529 if (FAILED(rc)) return rc;
530 LONG64 lSize;
531 rc = pSrcMedium->COMGETTER(Size)(&lSize);
532 if (FAILED(rc)) return rc;
533
534 /* Save the current medium, for later cloning. */
535 MEDIUMTASK mt;
536 mt.uIdx = UINT32_MAX;
537 mt.pMedium = pSrcMedium;
538 mt.uWeight = (ULONG)((lSize + _1M - 1) / _1M);
539 mtc.chain.append(mt);
540
541 /* Query next parent. */
542 rc = pSrcMedium->COMGETTER(Parent)(pSrcMedium.asOutParam());
543 if (FAILED(rc)) return rc;
544 }
545 /* Update the progress info. */
546 updateProgressStats(mtc, fAttachLinked, uCount, uTotalWeight);
547 /* Append the list of images which have to be cloned. */
548 llMedias.append(mtc);
549 }
550 /* Add the save state files of this machine if there is one. */
551 rc = addSaveState(machine, uCount, uTotalWeight);
552 if (FAILED(rc)) return rc;
553 }
554 /* Build up the index list of the image chain. Unfortunately we can't do
555 * that in the previous loop, cause there we go from child -> parent and
556 * didn't know how many are between. */
557 for (size_t i = 0; i < llMedias.size(); ++i)
558 {
559 uint32_t uIdx = 0;
560 MEDIUMTASKCHAIN &mtc = llMedias.at(i);
561 for (size_t a = mtc.chain.size(); a > 0; --a)
562 mtc.chain[a - 1].uIdx = uIdx++;
563 }
564
565 return rc;
566}
567
568bool MachineCloneVMPrivate::findSnapshot(const settings::SnapshotsList &snl, const Guid &id, settings::Snapshot &sn) const
569{
570 settings::SnapshotsList::const_iterator it;
571 for (it = snl.begin(); it != snl.end(); ++it)
572 {
573 if (it->uuid == id)
574 {
575 sn = (*it);
576 return true;
577 }
578 else if (!it->llChildSnapshots.empty())
579 {
580 if (findSnapshot(it->llChildSnapshots, id, sn))
581 return true;
582 }
583 }
584 return false;
585}
586
587void MachineCloneVMPrivate::updateMACAddresses(settings::NetworkAdaptersList &nwl) const
588{
589 const bool fNotNAT = options.contains(CloneOptions_KeepNATMACs);
590 settings::NetworkAdaptersList::iterator it;
591 for (it = nwl.begin(); it != nwl.end(); ++it)
592 {
593 if ( fNotNAT
594 && it->mode == NetworkAttachmentType_NAT)
595 continue;
596 Host::i_generateMACAddress(it->strMACAddress);
597 }
598}
599
600void MachineCloneVMPrivate::updateMACAddresses(settings::SnapshotsList &sl) const
601{
602 settings::SnapshotsList::iterator it;
603 for (it = sl.begin(); it != sl.end(); ++it)
604 {
605 updateMACAddresses(it->hardware.llNetworkAdapters);
606 if (!it->llChildSnapshots.empty())
607 updateMACAddresses(it->llChildSnapshots);
608 }
609}
610
611void MachineCloneVMPrivate::updateStorageLists(settings::StorageControllersList &sc,
612 const Bstr &bstrOldId, const Bstr &bstrNewId) const
613{
614 settings::StorageControllersList::iterator it3;
615 for (it3 = sc.begin();
616 it3 != sc.end();
617 ++it3)
618 {
619 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
620 settings::AttachedDevicesList::iterator it4;
621 for (it4 = llAttachments.begin();
622 it4 != llAttachments.end();
623 ++it4)
624 {
625 if ( it4->deviceType == DeviceType_HardDisk
626 && it4->uuid == bstrOldId)
627 {
628 it4->uuid = bstrNewId;
629 }
630 }
631 }
632}
633
634void MachineCloneVMPrivate::updateSnapshotStorageLists(settings::SnapshotsList &sl, const Bstr &bstrOldId,
635 const Bstr &bstrNewId) const
636{
637 settings::SnapshotsList::iterator it;
638 for ( it = sl.begin();
639 it != sl.end();
640 ++it)
641 {
642 updateStorageLists(it->storage.llStorageControllers, bstrOldId, bstrNewId);
643 if (!it->llChildSnapshots.empty())
644 updateSnapshotStorageLists(it->llChildSnapshots, bstrOldId, bstrNewId);
645 }
646}
647
648void MachineCloneVMPrivate::updateStateFile(settings::SnapshotsList &snl, const Guid &id, const Utf8Str &strFile) const
649{
650 settings::SnapshotsList::iterator it;
651 for (it = snl.begin(); it != snl.end(); ++it)
652 {
653 if (it->uuid == id)
654 it->strStateFile = strFile;
655 else if (!it->llChildSnapshots.empty())
656 updateStateFile(it->llChildSnapshots, id, strFile);
657 }
658}
659
660HRESULT MachineCloneVMPrivate::createDifferencingMedium(const ComObjPtr<Machine> &pMachine, const ComObjPtr<Medium> &pParent,
661 const Utf8Str &strSnapshotFolder, RTCList<ComObjPtr<Medium> > &newMedia,
662 ComObjPtr<Medium> *ppDiff) const
663{
664 HRESULT rc = S_OK;
665 try
666 {
667 // check validity of parent object
668 {
669 AutoReadLock alock(pParent COMMA_LOCKVAL_SRC_POS);
670 Bstr bstrSrcId;
671 rc = pParent->COMGETTER(Id)(bstrSrcId.asOutParam());
672 if (FAILED(rc)) throw rc;
673 }
674 ComObjPtr<Medium> diff;
675 diff.createObject();
676 rc = diff->init(p->i_getVirtualBox(),
677 pParent->i_getPreferredDiffFormat(),
678 Utf8StrFmt("%s%c", strSnapshotFolder.c_str(), RTPATH_DELIMITER),
679 Guid::Empty /* empty media registry */,
680 DeviceType_HardDisk);
681 if (FAILED(rc)) throw rc;
682
683 MediumLockList *pMediumLockList(new MediumLockList());
684 rc = diff->i_createMediumLockList(true /* fFailIfInaccessible */,
685 true /* fMediumLockWrite */,
686 pParent,
687 *pMediumLockList);
688 if (FAILED(rc)) throw rc;
689 rc = pMediumLockList->Lock();
690 if (FAILED(rc)) throw rc;
691
692 /* this already registers the new diff image */
693 rc = pParent->i_createDiffStorage(diff, MediumVariant_Standard,
694 pMediumLockList,
695 NULL /* aProgress */,
696 true /* aWait */);
697 delete pMediumLockList;
698 if (FAILED(rc)) throw rc;
699 /* Remember created medium. */
700 newMedia.append(diff);
701 *ppDiff = diff;
702 }
703 catch (HRESULT rc2)
704 {
705 rc = rc2;
706 }
707 catch (...)
708 {
709 rc = VirtualBoxBase::handleUnexpectedExceptions(pMachine, RT_SRC_POS);
710 }
711
712 return rc;
713}
714
715/* static */
716int MachineCloneVMPrivate::copyStateFileProgress(unsigned uPercentage, void *pvUser)
717{
718 ComObjPtr<Progress> pProgress = *static_cast< ComObjPtr<Progress>* >(pvUser);
719
720 BOOL fCanceled = false;
721 HRESULT rc = pProgress->COMGETTER(Canceled)(&fCanceled);
722 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
723 /* If canceled by the user tell it to the copy operation. */
724 if (fCanceled) return VERR_CANCELLED;
725 /* Set the new process. */
726 rc = pProgress->SetCurrentOperationProgress(uPercentage);
727 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
728
729 return VINF_SUCCESS;
730}
731
732// The public class
733/////////////////////////////////////////////////////////////////////////////
734
735MachineCloneVM::MachineCloneVM(ComObjPtr<Machine> pSrcMachine, ComObjPtr<Machine> pTrgMachine, CloneMode_T mode,
736 const RTCList<CloneOptions_T> &opts) :
737 d_ptr(new MachineCloneVMPrivate(this, pSrcMachine, pTrgMachine, mode, opts))
738{
739}
740
741MachineCloneVM::~MachineCloneVM()
742{
743 delete d_ptr;
744}
745
746HRESULT MachineCloneVM::start(IProgress **pProgress)
747{
748 DPTR(MachineCloneVM);
749 ComObjPtr<Machine> &p = d->p;
750
751 HRESULT rc;
752 try
753 {
754 /** @todo r=klaus this code cannot deal with someone crazy specifying
755 * IMachine corresponding to a mutable machine as d->pSrcMachine */
756 if (d->pSrcMachine->i_isSessionMachine())
757 throw p->setError(E_INVALIDARG, "The source machine is mutable");
758
759 /* Handle the special case that someone is requesting a _full_ clone
760 * with all snapshots (and the current state), but uses a snapshot
761 * machine (and not the current one) as source machine. In this case we
762 * just replace the source (snapshot) machine with the current machine. */
763 if ( d->mode == CloneMode_AllStates
764 && d->pSrcMachine->i_isSnapshotMachine())
765 {
766 Bstr bstrSrcMachineId;
767 rc = d->pSrcMachine->COMGETTER(Id)(bstrSrcMachineId.asOutParam());
768 if (FAILED(rc)) throw rc;
769 ComPtr<IMachine> newSrcMachine;
770 rc = d->pSrcMachine->i_getVirtualBox()->FindMachine(bstrSrcMachineId.raw(), newSrcMachine.asOutParam());
771 if (FAILED(rc)) throw rc;
772 d->pSrcMachine = (Machine*)(IMachine*)newSrcMachine;
773 }
774 bool fSubtreeIncludesCurrent = false;
775 ComObjPtr<Machine> pCurrState;
776 if (d->mode == CloneMode_MachineAndChildStates)
777 {
778 if (d->pSrcMachine->i_isSnapshotMachine())
779 {
780 /* find machine object for current snapshot of current state */
781 Bstr bstrSrcMachineId;
782 rc = d->pSrcMachine->COMGETTER(Id)(bstrSrcMachineId.asOutParam());
783 if (FAILED(rc)) throw rc;
784 ComPtr<IMachine> pCurr;
785 rc = d->pSrcMachine->i_getVirtualBox()->FindMachine(bstrSrcMachineId.raw(), pCurr.asOutParam());
786 if (FAILED(rc)) throw rc;
787 if (pCurr.isNull())
788 throw p->setError(VBOX_E_OBJECT_NOT_FOUND);
789 pCurrState = (Machine *)(IMachine *)pCurr;
790 ComPtr<ISnapshot> pSnapshot;
791 rc = pCurrState->COMGETTER(CurrentSnapshot)(pSnapshot.asOutParam());
792 if (FAILED(rc)) throw rc;
793 if (pSnapshot.isNull())
794 throw p->setError(VBOX_E_OBJECT_NOT_FOUND);
795 ComPtr<IMachine> pCurrSnapMachine;
796 rc = pSnapshot->COMGETTER(Machine)(pCurrSnapMachine.asOutParam());
797 if (FAILED(rc)) throw rc;
798 if (pCurrSnapMachine.isNull())
799 throw p->setError(VBOX_E_OBJECT_NOT_FOUND);
800
801 /* now check if there is a parent chain which leads to the
802 * snapshot machine defining the subtree. */
803 while (!pSnapshot.isNull())
804 {
805 ComPtr<IMachine> pSnapMachine;
806 rc = pSnapshot->COMGETTER(Machine)(pSnapMachine.asOutParam());
807 if (FAILED(rc)) throw rc;
808 if (pSnapMachine.isNull())
809 throw p->setError(VBOX_E_OBJECT_NOT_FOUND);
810 if (pSnapMachine == d->pSrcMachine)
811 {
812 fSubtreeIncludesCurrent = true;
813 break;
814 }
815 rc = pSnapshot->COMGETTER(Parent)(pSnapshot.asOutParam());
816 if (FAILED(rc)) throw rc;
817 }
818 }
819 else
820 {
821 /* If the subtree is only the Current State simply use the
822 * 'machine' case for cloning. It is easier to understand. */
823 d->mode = CloneMode_MachineState;
824 }
825 }
826
827 /* Lock the target machine early (so nobody mess around with it in the meantime). */
828 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
829
830 if (d->pSrcMachine->i_isSnapshotMachine())
831 d->snapshotId = d->pSrcMachine->i_getSnapshotId();
832
833 /* Add the current machine and all snapshot machines below this machine
834 * in a list for further processing. */
835 RTCList< ComObjPtr<Machine> > machineList;
836
837 /* Include current state? */
838 if ( d->mode == CloneMode_MachineState
839 || d->mode == CloneMode_AllStates)
840 machineList.append(d->pSrcMachine);
841 /* Should be done a depth copy with all child snapshots? */
842 if ( d->mode == CloneMode_MachineAndChildStates
843 || d->mode == CloneMode_AllStates)
844 {
845 ULONG cSnapshots = 0;
846 rc = d->pSrcMachine->COMGETTER(SnapshotCount)(&cSnapshots);
847 if (FAILED(rc)) throw rc;
848 if (cSnapshots > 0)
849 {
850 Utf8Str id;
851 if (d->mode == CloneMode_MachineAndChildStates)
852 id = d->snapshotId.toString();
853 ComPtr<ISnapshot> pSnapshot;
854 rc = d->pSrcMachine->FindSnapshot(Bstr(id).raw(), pSnapshot.asOutParam());
855 if (FAILED(rc)) throw rc;
856 rc = d->createMachineList(pSnapshot, machineList);
857 if (FAILED(rc)) throw rc;
858 if (d->mode == CloneMode_MachineAndChildStates)
859 {
860 if (fSubtreeIncludesCurrent)
861 {
862 if (pCurrState.isNull())
863 throw p->setError(VBOX_E_OBJECT_NOT_FOUND);
864 machineList.append(pCurrState);
865 }
866 else
867 {
868 rc = pSnapshot->COMGETTER(Machine)(d->pOldMachineState.asOutParam());
869 if (FAILED(rc)) throw rc;
870 }
871 }
872 }
873 }
874
875 /* We have different approaches for getting the medias which needs to
876 * be replicated based on the clone mode the user requested (this is
877 * mostly about the full clone mode).
878 * MachineState:
879 * - Only the images which are directly attached to an source VM will
880 * be cloned. Any parent disks in the original chain will be merged
881 * into the final cloned disk.
882 * MachineAndChildStates:
883 * - In this case we search for images which have more than one
884 * children in the cloned VM or are directly attached to the new VM.
885 * All others will be merged into the remaining images which are
886 * cloned.
887 * This case is the most complicated one and needs several iterations
888 * to make sure we are only cloning images which are really
889 * necessary.
890 * AllStates:
891 * - All disks which are directly or indirectly attached to the
892 * original VM are cloned.
893 *
894 * Note: If you change something generic in one of the methods its
895 * likely that it need to be changed in the others as well! */
896 ULONG uCount = 2; /* One init task and the machine creation. */
897 ULONG uTotalWeight = 2; /* The init task and the machine creation is worth one. */
898 bool fAttachLinked = d->options.contains(CloneOptions_Link); /* Linked clones requested? */
899 switch (d->mode)
900 {
901 case CloneMode_MachineState: d->queryMediasForMachineState(machineList, fAttachLinked,
902 uCount, uTotalWeight);
903 break;
904 case CloneMode_MachineAndChildStates: d->queryMediasForMachineAndChildStates(machineList, fAttachLinked,
905 uCount, uTotalWeight);
906 break;
907 case CloneMode_AllStates: d->queryMediasForAllStates(machineList, fAttachLinked, uCount,
908 uTotalWeight);
909 break;
910 }
911
912 /* Now create the progress project, so the user knows whats going on. */
913 rc = d->pProgress.createObject();
914 if (FAILED(rc)) throw rc;
915 rc = d->pProgress->init(p->i_getVirtualBox(),
916 static_cast<IMachine*>(d->pSrcMachine) /* aInitiator */,
917 Bstr(p->tr("Cloning Machine")).raw(),
918 true /* fCancellable */,
919 uCount,
920 uTotalWeight,
921 Bstr(p->tr("Initialize Cloning")).raw(),
922 1);
923 if (FAILED(rc)) throw rc;
924
925 int vrc = d->startWorker();
926
927 if (RT_FAILURE(vrc))
928 p->setError(VBOX_E_IPRT_ERROR, "Could not create machine clone thread (%Rrc)", vrc);
929 }
930 catch (HRESULT rc2)
931 {
932 rc = rc2;
933 }
934
935 if (SUCCEEDED(rc))
936 d->pProgress.queryInterfaceTo(pProgress);
937
938 return rc;
939}
940
941HRESULT MachineCloneVM::run()
942{
943 DPTR(MachineCloneVM);
944 ComObjPtr<Machine> &p = d->p;
945
946 AutoCaller autoCaller(p);
947 if (FAILED(autoCaller.rc())) return autoCaller.rc();
948
949 AutoReadLock srcLock(p COMMA_LOCKVAL_SRC_POS);
950 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
951
952 HRESULT rc = S_OK;
953
954 /*
955 * Todo:
956 * - What about log files?
957 */
958
959 /* Where should all the media go? */
960 Utf8Str strTrgSnapshotFolder;
961 Utf8Str strTrgMachineFolder = d->pTrgMachine->i_getSettingsFileFull();
962 strTrgMachineFolder.stripFilename();
963
964 RTCList<ComObjPtr<Medium> > newMedia; /* All created images */
965 RTCList<Utf8Str> newFiles; /* All extra created files (save states, ...) */
966 try
967 {
968 /* Copy all the configuration from this machine to an empty
969 * configuration dataset. */
970 settings::MachineConfigFile trgMCF = *d->pSrcMachine->mData->pMachineConfigFile;
971
972 /* Reset media registry. */
973 trgMCF.mediaRegistry.llHardDisks.clear();
974 /* If we got a valid snapshot id, replace the hardware/storage section
975 * with the stuff from the snapshot. */
976 settings::Snapshot sn;
977
978 if (d->snapshotId.isValid() && !d->snapshotId.isZero())
979 if (!d->findSnapshot(trgMCF.llFirstSnapshot, d->snapshotId, sn))
980 throw p->setError(E_FAIL,
981 p->tr("Could not find data to snapshots '%s'"), d->snapshotId.toString().c_str());
982
983
984
985 if (d->mode == CloneMode_MachineState)
986 {
987 if (sn.uuid.isValid() && !sn.uuid.isZero())
988 {
989 trgMCF.hardwareMachine = sn.hardware;
990 trgMCF.storageMachine = sn.storage;
991 }
992
993 /* Remove any hint on snapshots. */
994 trgMCF.llFirstSnapshot.clear();
995 trgMCF.uuidCurrentSnapshot.clear();
996 }
997 else if ( d->mode == CloneMode_MachineAndChildStates
998 && sn.uuid.isValid()
999 && !sn.uuid.isZero())
1000 {
1001 if (!d->pOldMachineState.isNull())
1002 {
1003 /* Copy the snapshot data to the current machine. */
1004 trgMCF.hardwareMachine = sn.hardware;
1005 trgMCF.storageMachine = sn.storage;
1006
1007 /* Current state is under root snapshot. */
1008 trgMCF.uuidCurrentSnapshot = sn.uuid;
1009 /* There will be created a new differencing image based on this
1010 * snapshot. So reset the modified state. */
1011 trgMCF.fCurrentStateModified = false;
1012 }
1013 /* The snapshot will be the root one. */
1014 trgMCF.llFirstSnapshot.clear();
1015 trgMCF.llFirstSnapshot.push_back(sn);
1016 }
1017
1018 /* Generate new MAC addresses for all machines when not forbidden. */
1019 if (!d->options.contains(CloneOptions_KeepAllMACs))
1020 {
1021 d->updateMACAddresses(trgMCF.hardwareMachine.llNetworkAdapters);
1022 d->updateMACAddresses(trgMCF.llFirstSnapshot);
1023 }
1024
1025 /* When the current snapshot folder is absolute we reset it to the
1026 * default relative folder. */
1027 if (RTPathStartsWithRoot(trgMCF.machineUserData.strSnapshotFolder.c_str()))
1028 trgMCF.machineUserData.strSnapshotFolder = "Snapshots";
1029 trgMCF.strStateFile = "";
1030 /* Set the new name. */
1031 const Utf8Str strOldVMName = trgMCF.machineUserData.strName;
1032 trgMCF.machineUserData.strName = d->pTrgMachine->mUserData->s.strName;
1033 trgMCF.uuid = d->pTrgMachine->mData->mUuid;
1034
1035 Bstr bstrSrcSnapshotFolder;
1036 rc = d->pSrcMachine->COMGETTER(SnapshotFolder)(bstrSrcSnapshotFolder.asOutParam());
1037 if (FAILED(rc)) throw rc;
1038 /* The absolute name of the snapshot folder. */
1039 strTrgSnapshotFolder = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER,
1040 trgMCF.machineUserData.strSnapshotFolder.c_str());
1041
1042 /* Should we rename the disk names. */
1043 bool fKeepDiskNames = d->options.contains(CloneOptions_KeepDiskNames);
1044
1045 /* We need to create a map with the already created medias. This is
1046 * necessary, cause different snapshots could have the same
1047 * parents/parent chain. If a medium is in this map already, it isn't
1048 * cloned a second time, but simply used. */
1049 typedef std::map<Utf8Str, ComObjPtr<Medium> > TStrMediumMap;
1050 typedef std::pair<Utf8Str, ComObjPtr<Medium> > TStrMediumPair;
1051 TStrMediumMap map;
1052 size_t cDisks = 0;
1053 for (size_t i = 0; i < d->llMedias.size(); ++i)
1054 {
1055 const MEDIUMTASKCHAIN &mtc = d->llMedias.at(i);
1056 ComObjPtr<Medium> pNewParent;
1057 uint32_t uSrcParentIdx = UINT32_MAX;
1058 uint32_t uTrgParentIdx = UINT32_MAX;
1059 for (size_t a = mtc.chain.size(); a > 0; --a)
1060 {
1061 const MEDIUMTASK &mt = mtc.chain.at(a - 1);
1062 ComPtr<IMedium> pMedium = mt.pMedium;
1063
1064 Bstr bstrSrcName;
1065 rc = pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
1066 if (FAILED(rc)) throw rc;
1067
1068 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Cloning Disk '%ls' ..."), bstrSrcName.raw()).raw(),
1069 mt.uWeight);
1070 if (FAILED(rc)) throw rc;
1071
1072 Bstr bstrSrcId;
1073 rc = pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
1074 if (FAILED(rc)) throw rc;
1075
1076 if (mtc.fAttachLinked)
1077 {
1078 IMedium *pTmp = pMedium;
1079 ComObjPtr<Medium> pLMedium = static_cast<Medium*>(pTmp);
1080 if (pLMedium.isNull())
1081 throw p->setError(VBOX_E_OBJECT_NOT_FOUND);
1082 ComObjPtr<Medium> pBase = pLMedium->i_getBase();
1083 if (pBase->i_isReadOnly())
1084 {
1085 ComObjPtr<Medium> pDiff;
1086 /* create the diff under the snapshot medium */
1087 trgLock.release();
1088 srcLock.release();
1089 rc = d->createDifferencingMedium(p, pLMedium, strTrgSnapshotFolder,
1090 newMedia, &pDiff);
1091 srcLock.acquire();
1092 trgLock.acquire();
1093 if (FAILED(rc)) throw rc;
1094 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pDiff));
1095 /* diff image has to be used... */
1096 pNewParent = pDiff;
1097 }
1098 else
1099 {
1100 /* Attach the medium directly, as its type is not
1101 * subject to diff creation. */
1102 newMedia.append(pLMedium);
1103 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pLMedium));
1104 pNewParent = pLMedium;
1105 }
1106 }
1107 else
1108 {
1109 /* Is a clone already there? */
1110 TStrMediumMap::iterator it = map.find(Utf8Str(bstrSrcId));
1111 if (it != map.end())
1112 pNewParent = it->second;
1113 else
1114 {
1115 ComPtr<IMediumFormat> pSrcFormat;
1116 rc = pMedium->COMGETTER(MediumFormat)(pSrcFormat.asOutParam());
1117 ULONG uSrcCaps = 0;
1118 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
1119 rc = pSrcFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap));
1120
1121 if (FAILED(rc)) throw rc;
1122 else
1123 {
1124 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
1125 uSrcCaps |= mediumFormatCap[j];
1126 }
1127
1128 /* Default format? */
1129 Utf8Str strDefaultFormat;
1130 p->mParent->i_getDefaultHardDiskFormat(strDefaultFormat);
1131 Bstr bstrSrcFormat(strDefaultFormat);
1132
1133 ULONG srcVar = MediumVariant_Standard;
1134 com::SafeArray <MediumVariant_T> mediumVariant;
1135
1136 /* Is the source file based? */
1137 if ((uSrcCaps & MediumFormatCapabilities_File) == MediumFormatCapabilities_File)
1138 {
1139 /* Yes, just use the source format. Otherwise the defaults
1140 * will be used. */
1141 rc = pMedium->COMGETTER(Format)(bstrSrcFormat.asOutParam());
1142 if (FAILED(rc)) throw rc;
1143
1144 rc = pMedium->COMGETTER(Variant)(ComSafeArrayAsOutParam(mediumVariant));
1145 if (FAILED(rc)) throw rc;
1146 else
1147 {
1148 for (size_t j = 0; j < mediumVariant.size(); j++)
1149 srcVar |= mediumVariant[j];
1150 }
1151 }
1152
1153 Guid newId;
1154 newId.create();
1155 Utf8Str strNewName(bstrSrcName);
1156 if (!fKeepDiskNames)
1157 {
1158 Utf8Str strSrcTest = bstrSrcName;
1159 /* Check if we have to use another name. */
1160 if (!mt.strBaseName.isEmpty())
1161 strSrcTest = mt.strBaseName;
1162 strSrcTest.stripSuffix();
1163 /* If the old disk name was in {uuid} format we also
1164 * want the new name in this format, but with the
1165 * updated id of course. If the old disk was called
1166 * like the VM name, we change it to the new VM name.
1167 * For all other disks we rename them with this
1168 * template: "new name-disk1.vdi". */
1169 if (strSrcTest == strOldVMName)
1170 strNewName = Utf8StrFmt("%s%s", trgMCF.machineUserData.strName.c_str(),
1171 RTPathSuffix(Utf8Str(bstrSrcName).c_str()));
1172 else if ( strSrcTest.startsWith("{")
1173 && strSrcTest.endsWith("}"))
1174 {
1175 strSrcTest = strSrcTest.substr(1, strSrcTest.length() - 2);
1176
1177 Guid temp_guid(strSrcTest);
1178 if (temp_guid.isValid() && !temp_guid.isZero())
1179 strNewName = Utf8StrFmt("%s%s", newId.toStringCurly().c_str(),
1180 RTPathSuffix(strNewName.c_str()));
1181 }
1182 else
1183 strNewName = Utf8StrFmt("%s-disk%d%s", trgMCF.machineUserData.strName.c_str(), ++cDisks,
1184 RTPathSuffix(Utf8Str(bstrSrcName).c_str()));
1185 }
1186
1187 /* Check if this medium comes from the snapshot folder, if
1188 * so, put it there in the cloned machine as well.
1189 * Otherwise it goes to the machine folder. */
1190 Bstr bstrSrcPath;
1191 Utf8Str strFile = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
1192 rc = pMedium->COMGETTER(Location)(bstrSrcPath.asOutParam());
1193 if (FAILED(rc)) throw rc;
1194 if ( !bstrSrcPath.isEmpty()
1195 && RTPathStartsWith(Utf8Str(bstrSrcPath).c_str(), Utf8Str(bstrSrcSnapshotFolder).c_str())
1196 && (fKeepDiskNames || mt.strBaseName.isEmpty()))
1197 strFile = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
1198
1199 /* Start creating the clone. */
1200 ComObjPtr<Medium> pTarget;
1201 rc = pTarget.createObject();
1202 if (FAILED(rc)) throw rc;
1203
1204 rc = pTarget->init(p->mParent,
1205 Utf8Str(bstrSrcFormat),
1206 strFile,
1207 Guid::Empty /* empty media registry */,
1208 DeviceType_HardDisk);
1209 if (FAILED(rc)) throw rc;
1210
1211 /* Update the new uuid. */
1212 pTarget->i_updateId(newId);
1213
1214 srcLock.release();
1215 /* Do the disk cloning. */
1216 ComPtr<IProgress> progress2;
1217
1218 ComObjPtr<Medium> pLMedium = static_cast<Medium*>((IMedium*)pMedium);
1219 rc = pLMedium->i_cloneToEx(pTarget,
1220 srcVar,
1221 pNewParent,
1222 progress2.asOutParam(),
1223 uSrcParentIdx,
1224 uTrgParentIdx);
1225 if (FAILED(rc)) throw rc;
1226
1227 /* Wait until the async process has finished. */
1228 rc = d->pProgress->WaitForAsyncProgressCompletion(progress2);
1229 srcLock.acquire();
1230 if (FAILED(rc)) throw rc;
1231
1232 /* Check the result of the async process. */
1233 LONG iRc;
1234 rc = progress2->COMGETTER(ResultCode)(&iRc);
1235 if (FAILED(rc)) throw rc;
1236 /* If the thread of the progress object has an error, then
1237 * retrieve the error info from there, or it'll be lost. */
1238 if (FAILED(iRc))
1239 throw p->setError(ProgressErrorInfo(progress2));
1240 /* Remember created medium. */
1241 newMedia.append(pTarget);
1242 /* Get the medium type from the source and set it to the
1243 * new medium. */
1244 MediumType_T type;
1245 rc = pMedium->COMGETTER(Type)(&type);
1246 if (FAILED(rc)) throw rc;
1247 rc = pTarget->COMSETTER(Type)(type);
1248 if (FAILED(rc)) throw rc;
1249 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pTarget));
1250 /* register the new harddisk */
1251 {
1252 AutoWriteLock tlock(p->mParent->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1253 rc = p->mParent->i_registerMedium(pTarget, &pTarget,
1254 DeviceType_HardDisk,
1255 tlock);
1256 if (FAILED(rc)) throw rc;
1257 }
1258 /* This medium becomes the parent of the next medium in the
1259 * chain. */
1260 pNewParent = pTarget;
1261 }
1262 }
1263 /* Save the current source medium index as the new parent
1264 * medium index. */
1265 uSrcParentIdx = mt.uIdx;
1266 /* Simply increase the target index. */
1267 ++uTrgParentIdx;
1268 }
1269
1270 Bstr bstrSrcId;
1271 rc = mtc.chain.first().pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
1272 if (FAILED(rc)) throw rc;
1273 Bstr bstrTrgId;
1274 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
1275 if (FAILED(rc)) throw rc;
1276 /* update snapshot configuration */
1277 d->updateSnapshotStorageLists(trgMCF.llFirstSnapshot, bstrSrcId, bstrTrgId);
1278
1279 /* create new 'Current State' diff for caller defined place */
1280 if (mtc.fCreateDiffs)
1281 {
1282 const MEDIUMTASK &mt = mtc.chain.first();
1283 ComObjPtr<Medium> pLMedium = static_cast<Medium*>((IMedium*)mt.pMedium);
1284 if (pLMedium.isNull())
1285 throw p->setError(VBOX_E_OBJECT_NOT_FOUND);
1286 ComObjPtr<Medium> pBase = pLMedium->i_getBase();
1287 if (pBase->i_isReadOnly())
1288 {
1289 ComObjPtr<Medium> pDiff;
1290 trgLock.release();
1291 srcLock.release();
1292 rc = d->createDifferencingMedium(p, pNewParent, strTrgSnapshotFolder,
1293 newMedia, &pDiff);
1294 srcLock.acquire();
1295 trgLock.acquire();
1296 if (FAILED(rc)) throw rc;
1297 /* diff image has to be used... */
1298 pNewParent = pDiff;
1299 }
1300 else
1301 {
1302 /* Attach the medium directly, as its type is not
1303 * subject to diff creation. */
1304 newMedia.append(pNewParent);
1305 }
1306
1307 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
1308 if (FAILED(rc)) throw rc;
1309 }
1310 /* update 'Current State' configuration */
1311 d->updateStorageLists(trgMCF.storageMachine.llStorageControllers, bstrSrcId, bstrTrgId);
1312 }
1313 /* Make sure all disks know of the new machine uuid. We do this last to
1314 * be able to change the medium type above. */
1315 for (size_t i = newMedia.size(); i > 0; --i)
1316 {
1317 const ComObjPtr<Medium> &pMedium = newMedia.at(i - 1);
1318 AutoCaller mac(pMedium);
1319 if (FAILED(mac.rc())) throw mac.rc();
1320 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
1321 Guid uuid = d->pTrgMachine->mData->mUuid;
1322 if (d->options.contains(CloneOptions_Link))
1323 {
1324 ComObjPtr<Medium> pParent = pMedium->i_getParent();
1325 mlock.release();
1326 if (!pParent.isNull())
1327 {
1328 AutoCaller mac2(pParent);
1329 if (FAILED(mac2.rc())) throw mac2.rc();
1330 AutoReadLock mlock2(pParent COMMA_LOCKVAL_SRC_POS);
1331 if (pParent->i_getFirstRegistryMachineId(uuid))
1332 {
1333 mlock2.release();
1334 trgLock.release();
1335 srcLock.release();
1336 p->mParent->i_markRegistryModified(uuid);
1337 srcLock.acquire();
1338 trgLock.acquire();
1339 mlock2.acquire();
1340 }
1341 }
1342 mlock.acquire();
1343 }
1344 pMedium->i_addRegistry(uuid, false /* fRecurse */);
1345 }
1346 /* Check if a snapshot folder is necessary and if so doesn't already
1347 * exists. */
1348 if ( !d->llSaveStateFiles.isEmpty()
1349 && !RTDirExists(strTrgSnapshotFolder.c_str()))
1350 {
1351 int vrc = RTDirCreateFullPath(strTrgSnapshotFolder.c_str(), 0700);
1352 if (RT_FAILURE(vrc))
1353 throw p->setError(VBOX_E_IPRT_ERROR,
1354 p->tr("Could not create snapshots folder '%s' (%Rrc)"),
1355 strTrgSnapshotFolder.c_str(), vrc);
1356 }
1357 /* Clone all save state files. */
1358 for (size_t i = 0; i < d->llSaveStateFiles.size(); ++i)
1359 {
1360 SAVESTATETASK sst = d->llSaveStateFiles.at(i);
1361 const Utf8Str &strTrgSaveState = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER,
1362 RTPathFilename(sst.strSaveStateFile.c_str()));
1363
1364 /* Move to next sub-operation. */
1365 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Copy save state file '%s' ..."),
1366 RTPathFilename(sst.strSaveStateFile.c_str())).raw(), sst.uWeight);
1367 if (FAILED(rc)) throw rc;
1368 /* Copy the file only if it was not copied already. */
1369 if (!newFiles.contains(strTrgSaveState.c_str()))
1370 {
1371 int vrc = RTFileCopyEx(sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), 0,
1372 MachineCloneVMPrivate::copyStateFileProgress, &d->pProgress);
1373 if (RT_FAILURE(vrc))
1374 throw p->setError(VBOX_E_IPRT_ERROR,
1375 p->tr("Could not copy state file '%s' to '%s' (%Rrc)"),
1376 sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), vrc);
1377 newFiles.append(strTrgSaveState);
1378 }
1379 /* Update the path in the configuration either for the current
1380 * machine state or the snapshots. */
1381 if (!sst.snapshotUuid.isValid() || sst.snapshotUuid.isZero())
1382 trgMCF.strStateFile = strTrgSaveState;
1383 else
1384 d->updateStateFile(trgMCF.llFirstSnapshot, sst.snapshotUuid, strTrgSaveState);
1385 }
1386
1387 {
1388 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Create Machine Clone '%s' ..."),
1389 trgMCF.machineUserData.strName.c_str()).raw(), 1);
1390 if (FAILED(rc)) throw rc;
1391 /* After modifying the new machine config, we can copy the stuff
1392 * over to the new machine. The machine have to be mutable for
1393 * this. */
1394 rc = d->pTrgMachine->i_checkStateDependency(p->MutableStateDep);
1395 if (FAILED(rc)) throw rc;
1396 rc = d->pTrgMachine->i_loadMachineDataFromSettings(trgMCF, &d->pTrgMachine->mData->mUuid);
1397 if (FAILED(rc)) throw rc;
1398 /* save all VM data */
1399 bool fNeedsGlobalSaveSettings = false;
1400 rc = d->pTrgMachine->i_saveSettings(&fNeedsGlobalSaveSettings, Machine::SaveS_Force);
1401 if (FAILED(rc)) throw rc;
1402 /* Release all locks */
1403 trgLock.release();
1404 srcLock.release();
1405 if (fNeedsGlobalSaveSettings)
1406 {
1407 /* save the global settings; for that we should hold only the
1408 * VirtualBox lock */
1409 AutoWriteLock vlock(p->mParent COMMA_LOCKVAL_SRC_POS);
1410 rc = p->mParent->i_saveSettings();
1411 if (FAILED(rc)) throw rc;
1412 }
1413 }
1414
1415 /* Any additional machines need saving? */
1416 p->mParent->i_saveModifiedRegistries();
1417 }
1418 catch (HRESULT rc2)
1419 {
1420 rc = rc2;
1421 }
1422 catch (...)
1423 {
1424 rc = VirtualBoxBase::handleUnexpectedExceptions(p, RT_SRC_POS);
1425 }
1426
1427 MultiResult mrc(rc);
1428 /* Cleanup on failure (CANCEL also) */
1429 if (FAILED(rc))
1430 {
1431 int vrc = VINF_SUCCESS;
1432 /* Delete all created files. */
1433 for (size_t i = 0; i < newFiles.size(); ++i)
1434 {
1435 vrc = RTFileDelete(newFiles.at(i).c_str());
1436 if (RT_FAILURE(vrc))
1437 mrc = p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not delete file '%s' (%Rrc)"), newFiles.at(i).c_str(), vrc);
1438 }
1439 /* Delete all already created medias. (Reverse, cause there could be
1440 * parent->child relations.) */
1441 for (size_t i = newMedia.size(); i > 0; --i)
1442 {
1443 const ComObjPtr<Medium> &pMedium = newMedia.at(i - 1);
1444 mrc = pMedium->i_deleteStorage(NULL /* aProgress */,
1445 true /* aWait */);
1446 pMedium->Close();
1447 }
1448 /* Delete the snapshot folder when not empty. */
1449 if (!strTrgSnapshotFolder.isEmpty())
1450 RTDirRemove(strTrgSnapshotFolder.c_str());
1451 /* Delete the machine folder when not empty. */
1452 RTDirRemove(strTrgMachineFolder.c_str());
1453
1454 /* Must save the modified registries */
1455 p->mParent->i_saveModifiedRegistries();
1456 }
1457
1458 return mrc;
1459}
1460
1461void MachineCloneVM::destroy()
1462{
1463 delete this;
1464}
1465
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