VirtualBox

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

Last change on this file since 38120 was 38120, checked in by vboxsync, 14 years ago

Main-CloneVM: remove old comment

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