VirtualBox

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

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

Main-CloneVM: keep the "public" interface clean

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 55.5 KB
Line 
1/* $Id: MachineImplCloneVM.cpp 38119 2011-07-22 14:57:03Z 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.215389.xyz. 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 /* If we want to create a linked clone just attach the medium
828 * associated with the snapshot. The rest is taken care of by
829 * attach already, so no need to duplicate this. */
830
831 /* We have different approaches for getting the medias which needs to
832 * be replicated based on the clone mode the user requested (this is
833 * mostly about the full clone mode).
834 * MachineState:
835 * - Only the images which are directly attached to an source VM will
836 * be cloned. Any parent disks in the original chain will be merged
837 * into the final cloned disk.
838 * MachineAndChildStates:
839 * - In this case we search for images which have more than one
840 * children in the cloned VM or are directly attached to the new VM.
841 * All others will be merged into the remaining images which are
842 * cloned.
843 * This case is the most complicated one and needs several iterations
844 * to make sure we are only cloning images which are really
845 * necessary.
846 * AllStates:
847 * - All disks which are directly or indirectly attached to the
848 * original VM are cloned.
849 *
850 * Note: If you change something generic on one if the methods its
851 * likely that it need changed in the others as well! */
852 ULONG uCount = 2; /* One init task and the machine creation. */
853 ULONG uTotalWeight = 2; /* The init task and the machine creation is worth one. */
854 bool fAttachLinked = d->options.contains(CloneOptions_Link); /* Linked clones requested? */
855 switch (d->mode)
856 {
857 case CloneMode_MachineState: d->queryMediasForMachineState(machineList, fAttachLinked, uCount, uTotalWeight); break;
858 case CloneMode_MachineAndChildStates: d->queryMediasForMachineAndChildStates(machineList, fAttachLinked, uCount, uTotalWeight); break;
859 case CloneMode_AllStates: d->queryMediasForAllStates(machineList, fAttachLinked, uCount, uTotalWeight); break;
860 }
861
862 /* Now create the progress project, so the user knows whats going on. */
863 rc = d->pProgress.createObject();
864 if (FAILED(rc)) throw rc;
865 rc = d->pProgress->init(p->getVirtualBox(),
866 static_cast<IMachine*>(d->pSrcMachine) /* aInitiator */,
867 Bstr(p->tr("Cloning Machine")).raw(),
868 true /* fCancellable */,
869 uCount,
870 uTotalWeight,
871 Bstr(p->tr("Initialize Cloning")).raw(),
872 1);
873 if (FAILED(rc)) throw rc;
874
875 int vrc = d->startWorker();
876
877 if (RT_FAILURE(vrc))
878 p->setError(VBOX_E_IPRT_ERROR, "Could not create machine clone thread (%Rrc)", vrc);
879 }
880 catch (HRESULT rc2)
881 {
882 rc = rc2;
883 }
884
885 if (SUCCEEDED(rc))
886 d->pProgress.queryInterfaceTo(pProgress);
887
888 return rc;
889}
890
891HRESULT MachineCloneVM::run()
892{
893 DPTR(MachineCloneVM);
894 ComObjPtr<Machine> &p = d->p;
895
896 AutoCaller autoCaller(p);
897 if (FAILED(autoCaller.rc())) return autoCaller.rc();
898
899 AutoReadLock srcLock(p COMMA_LOCKVAL_SRC_POS);
900 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
901
902 HRESULT rc = S_OK;
903
904 /*
905 * Todo:
906 * - What about log files?
907 */
908
909 /* Where should all the media go? */
910 Utf8Str strTrgSnapshotFolder;
911 Utf8Str strTrgMachineFolder = d->pTrgMachine->getSettingsFileFull();
912 strTrgMachineFolder.stripFilename();
913
914 RTCList<ComObjPtr<Medium> > newMedia; /* All created images */
915 RTCList<Utf8Str> newFiles; /* All extra created files (save states, ...) */
916 try
917 {
918 /* Copy all the configuration from this machine to an empty
919 * configuration dataset. */
920 settings::MachineConfigFile trgMCF = *d->pSrcMachine->mData->pMachineConfigFile;
921
922 /* Reset media registry. */
923 trgMCF.mediaRegistry.llHardDisks.clear();
924 /* If we got a valid snapshot id, replace the hardware/storage section
925 * with the stuff from the snapshot. */
926 settings::Snapshot sn;
927 if (!d->snapshotId.isEmpty())
928 sn = d->findSnapshot(&trgMCF, trgMCF.llFirstSnapshot, d->snapshotId);
929
930 if (d->mode == CloneMode_MachineState)
931 {
932 if (!sn.uuid.isEmpty())
933 {
934 trgMCF.hardwareMachine = sn.hardware;
935 trgMCF.storageMachine = sn.storage;
936 }
937
938 /* Remove any hint on snapshots. */
939 trgMCF.llFirstSnapshot.clear();
940 trgMCF.uuidCurrentSnapshot.clear();
941 }
942 else if ( d->mode == CloneMode_MachineAndChildStates
943 && !sn.uuid.isEmpty())
944 {
945 /* Copy the snapshot data to the current machine. */
946 trgMCF.hardwareMachine = sn.hardware;
947 trgMCF.storageMachine = sn.storage;
948
949 /* The snapshot will be the root one. */
950 trgMCF.uuidCurrentSnapshot = sn.uuid;
951 trgMCF.llFirstSnapshot.clear();
952 trgMCF.llFirstSnapshot.push_back(sn);
953 }
954
955 /* Generate new MAC addresses for all machines when not forbidden. */
956 if (!d->options.contains(CloneOptions_KeepAllMACs))
957 {
958 d->updateMACAddresses(trgMCF.hardwareMachine.llNetworkAdapters);
959 d->updateMACAddresses(trgMCF.llFirstSnapshot);
960 }
961
962 /* When the current snapshot folder is absolute we reset it to the
963 * default relative folder. */
964 if (RTPathStartsWithRoot(trgMCF.machineUserData.strSnapshotFolder.c_str()))
965 trgMCF.machineUserData.strSnapshotFolder = "Snapshots";
966 trgMCF.strStateFile = "";
967 /* Force writing of setting file. */
968 trgMCF.fCurrentStateModified = true;
969 /* Set the new name. */
970 const Utf8Str strOldVMName = trgMCF.machineUserData.strName;
971 trgMCF.machineUserData.strName = d->pTrgMachine->mUserData->s.strName;
972 trgMCF.uuid = d->pTrgMachine->mData->mUuid;
973
974 Bstr bstrSrcSnapshotFolder;
975 rc = d->pSrcMachine->COMGETTER(SnapshotFolder)(bstrSrcSnapshotFolder.asOutParam());
976 if (FAILED(rc)) throw rc;
977 /* The absolute name of the snapshot folder. */
978 strTrgSnapshotFolder = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, trgMCF.machineUserData.strSnapshotFolder.c_str());
979
980 /* Should we rename the disk names. */
981 bool fKeepDiskNames = d->options.contains(CloneOptions_KeepDiskNames);
982
983 /* We need to create a map with the already created medias. This is
984 * necessary, cause different snapshots could have the same
985 * parents/parent chain. If a medium is in this map already, it isn't
986 * cloned a second time, but simply used. */
987 typedef std::map<Utf8Str, ComObjPtr<Medium> > TStrMediumMap;
988 typedef std::pair<Utf8Str, ComObjPtr<Medium> > TStrMediumPair;
989 TStrMediumMap map;
990 GuidList llRegistriesThatNeedSaving;
991 size_t cDisks = 0;
992 for (size_t i = 0; i < d->llMedias.size(); ++i)
993 {
994 const MEDIUMTASKCHAIN &mtc = d->llMedias.at(i);
995 ComObjPtr<Medium> pNewParent;
996 for (size_t a = mtc.chain.size(); a > 0; --a)
997 {
998 const MEDIUMTASK &mt = mtc.chain.at(a - 1);
999 ComPtr<IMedium> pMedium = mt.pMedium;
1000
1001 Bstr bstrSrcName;
1002 rc = pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
1003 if (FAILED(rc)) throw rc;
1004
1005 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Cloning Disk '%ls' ..."), bstrSrcName.raw()).raw(), mt.uWeight);
1006 if (FAILED(rc)) throw rc;
1007
1008 Bstr bstrSrcId;
1009 rc = pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
1010 if (FAILED(rc)) throw rc;
1011
1012 if (mtc.fAttachLinked)
1013 {
1014 IMedium *pTmp = pMedium;
1015 ComObjPtr<Medium> pLMedium = static_cast<Medium*>(pTmp);
1016 if (pLMedium.isNull())
1017 throw E_POINTER;
1018 ComObjPtr<Medium> pBase = pLMedium->getBase();
1019 if (pBase->isReadOnly())
1020 {
1021 ComObjPtr<Medium> pDiff;
1022 /* create the diff under the snapshot medium */
1023 rc = d->createDifferencingMedium(pLMedium, strTrgSnapshotFolder,
1024 newMedia, &pDiff);
1025 if (FAILED(rc)) throw rc;
1026 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pDiff));
1027 /* diff image has to be used... */
1028 pNewParent = pDiff;
1029 }
1030 else
1031 {
1032 /* Attach the medium directly, as its type is not
1033 * subject to diff creation. */
1034 newMedia.append(pLMedium);
1035 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pLMedium));
1036 pNewParent = pLMedium;
1037 }
1038 }
1039 else
1040 {
1041 /* Is a clone already there? */
1042 TStrMediumMap::iterator it = map.find(Utf8Str(bstrSrcId));
1043 if (it != map.end())
1044 pNewParent = it->second;
1045 else
1046 {
1047 ComPtr<IMediumFormat> pSrcFormat;
1048 rc = pMedium->COMGETTER(MediumFormat)(pSrcFormat.asOutParam());
1049 ULONG uSrcCaps = 0;
1050 rc = pSrcFormat->COMGETTER(Capabilities)(&uSrcCaps);
1051 if (FAILED(rc)) throw rc;
1052
1053 /* Default format? */
1054 Utf8Str strDefaultFormat;
1055 p->mParent->getDefaultHardDiskFormat(strDefaultFormat);
1056 Bstr bstrSrcFormat(strDefaultFormat);
1057 ULONG srcVar = MediumVariant_Standard;
1058 /* Is the source file based? */
1059 if ((uSrcCaps & MediumFormatCapabilities_File) == MediumFormatCapabilities_File)
1060 {
1061 /* Yes, just use the source format. Otherwise the defaults
1062 * will be used. */
1063 rc = pMedium->COMGETTER(Format)(bstrSrcFormat.asOutParam());
1064 if (FAILED(rc)) throw rc;
1065 rc = pMedium->COMGETTER(Variant)(&srcVar);
1066 if (FAILED(rc)) throw rc;
1067 }
1068
1069 Guid newId;
1070 newId.create();
1071 Utf8Str strNewName(bstrSrcName);
1072 if (!fKeepDiskNames)
1073 {
1074 Utf8Str strSrcTest = bstrSrcName;
1075 /* Check if we have to use another name. */
1076 if (!mt.strBaseName.isEmpty())
1077 strSrcTest = mt.strBaseName;
1078 strSrcTest.stripExt();
1079 /* If the old disk name was in {uuid} format we also
1080 * want the new name in this format, but with the
1081 * updated id of course. If the old disk was called
1082 * like the VM name, we change it to the new VM name.
1083 * For all other disks we rename them with this
1084 * template: "new name-disk1.vdi". */
1085 if (strSrcTest == strOldVMName)
1086 strNewName = Utf8StrFmt("%s%s", trgMCF.machineUserData.strName.c_str(), RTPathExt(Utf8Str(bstrSrcName).c_str()));
1087 else if ( strSrcTest.startsWith("{")
1088 && strSrcTest.endsWith("}"))
1089 {
1090 strSrcTest = strSrcTest.substr(1, strSrcTest.length() - 2);
1091 if (isValidGuid(strSrcTest))
1092 strNewName = Utf8StrFmt("%s%s", newId.toStringCurly().c_str(), RTPathExt(strNewName.c_str()));
1093 }
1094 else
1095 strNewName = Utf8StrFmt("%s-disk%d%s", trgMCF.machineUserData.strName.c_str(), ++cDisks, RTPathExt(Utf8Str(bstrSrcName).c_str()));
1096 }
1097
1098 /* Check if this medium comes from the snapshot folder, if
1099 * so, put it there in the cloned machine as well.
1100 * Otherwise it goes to the machine folder. */
1101 Bstr bstrSrcPath;
1102 Utf8Str strFile = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
1103 rc = pMedium->COMGETTER(Location)(bstrSrcPath.asOutParam());
1104 if (FAILED(rc)) throw rc;
1105 if ( !bstrSrcPath.isEmpty()
1106 && RTPathStartsWith(Utf8Str(bstrSrcPath).c_str(), Utf8Str(bstrSrcSnapshotFolder).c_str())
1107 && (fKeepDiskNames || mt.strBaseName.isEmpty()))
1108 strFile = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
1109
1110 /* Start creating the clone. */
1111 ComObjPtr<Medium> pTarget;
1112 rc = pTarget.createObject();
1113 if (FAILED(rc)) throw rc;
1114
1115 rc = pTarget->init(p->mParent,
1116 Utf8Str(bstrSrcFormat),
1117 strFile,
1118 Guid::Empty, /* empty media registry */
1119 NULL /* llRegistriesThatNeedSaving */);
1120 if (FAILED(rc)) throw rc;
1121
1122 /* Update the new uuid. */
1123 pTarget->updateId(newId);
1124
1125 srcLock.release();
1126 /* Do the disk cloning. */
1127 ComPtr<IProgress> progress2;
1128 rc = pMedium->CloneTo(pTarget,
1129 srcVar,
1130 pNewParent,
1131 progress2.asOutParam());
1132 if (FAILED(rc)) throw rc;
1133
1134 /* Wait until the async process has finished. */
1135 rc = d->pProgress->WaitForAsyncProgressCompletion(progress2);
1136 srcLock.acquire();
1137 if (FAILED(rc)) throw rc;
1138
1139 /* Check the result of the async process. */
1140 LONG iRc;
1141 rc = progress2->COMGETTER(ResultCode)(&iRc);
1142 if (FAILED(rc)) throw rc;
1143 if (FAILED(iRc))
1144 {
1145 /* If the thread of the progress object has an error, then
1146 * retrieve the error info from there, or it'll be lost. */
1147 ProgressErrorInfo info(progress2);
1148 throw p->setError(iRc, Utf8Str(info.getText()).c_str());
1149 }
1150 /* Remember created medium. */
1151 newMedia.append(pTarget);
1152 /* Get the medium type from the source and set it to the
1153 * new medium. */
1154 MediumType_T type;
1155 rc = pMedium->COMGETTER(Type)(&type);
1156 if (FAILED(rc)) throw rc;
1157 rc = pTarget->COMSETTER(Type)(type);
1158 if (FAILED(rc)) throw rc;
1159 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pTarget));
1160 /* register the new harddisk */
1161 {
1162 AutoWriteLock tlock(p->mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1163 rc = p->mParent->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
1164 if (FAILED(rc)) throw rc;
1165 }
1166 /* This medium becomes the parent of the next medium in the
1167 * chain. */
1168 pNewParent = pTarget;
1169 }
1170 }
1171 }
1172
1173 Bstr bstrSrcId;
1174 rc = mtc.chain.first().pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
1175 if (FAILED(rc)) throw rc;
1176 Bstr bstrTrgId;
1177 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
1178 if (FAILED(rc)) throw rc;
1179 /* update snapshot configuration */
1180 d->updateSnapshotStorageLists(trgMCF.llFirstSnapshot, bstrSrcId, bstrTrgId);
1181
1182 /* create new 'Current State' diff for caller defined place */
1183 if (mtc.fCreateDiffs)
1184 {
1185 const MEDIUMTASK &mt = mtc.chain.first();
1186 ComObjPtr<Medium> pLMedium = static_cast<Medium*>((IMedium*)mt.pMedium);
1187 if (pLMedium.isNull())
1188 throw E_POINTER;
1189 ComObjPtr<Medium> pBase = pLMedium->getBase();
1190 if (pBase->isReadOnly())
1191 {
1192 ComObjPtr<Medium> pDiff;
1193 rc = d->createDifferencingMedium(pNewParent, strTrgSnapshotFolder,
1194 newMedia, &pDiff);
1195 if (FAILED(rc)) throw rc;
1196 /* diff image has to be used... */
1197 pNewParent = pDiff;
1198 }
1199 else
1200 {
1201 /* Attach the medium directly, as its type is not
1202 * subject to diff creation. */
1203 newMedia.append(pNewParent);
1204 }
1205
1206 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
1207 if (FAILED(rc)) throw rc;
1208 }
1209 /* update 'Current State' configuration */
1210 d->updateStorageLists(trgMCF.storageMachine.llStorageControllers, bstrSrcId, bstrTrgId);
1211 }
1212 /* Make sure all disks know of the new machine uuid. We do this last to
1213 * be able to change the medium type above. */
1214 for (size_t i = newMedia.size(); i > 0; --i)
1215 {
1216 const ComObjPtr<Medium> &pMedium = newMedia.at(i - 1);
1217 AutoCaller mac(pMedium);
1218 if (FAILED(mac.rc())) throw mac.rc();
1219 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
1220 Guid uuid = d->pTrgMachine->mData->mUuid;
1221 if (d->options.contains(CloneOptions_Link))
1222 {
1223 ComObjPtr<Medium> pParent = pMedium->getParent();
1224 mlock.release();
1225 if (!pParent.isNull())
1226 {
1227 AutoCaller mac2(pParent);
1228 if (FAILED(mac2.rc())) throw mac2.rc();
1229 AutoReadLock mlock2(pParent COMMA_LOCKVAL_SRC_POS);
1230 if (pParent->getFirstRegistryMachineId(uuid))
1231 VirtualBox::addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
1232 }
1233 mlock.acquire();
1234 }
1235 pMedium->addRegistry(uuid, false /* fRecurse */);
1236 }
1237 /* Check if a snapshot folder is necessary and if so doesn't already
1238 * exists. */
1239 if ( !d->llSaveStateFiles.isEmpty()
1240 && !RTDirExists(strTrgSnapshotFolder.c_str()))
1241 {
1242 int vrc = RTDirCreateFullPath(strTrgSnapshotFolder.c_str(), 0777);
1243 if (RT_FAILURE(vrc))
1244 throw p->setError(VBOX_E_IPRT_ERROR,
1245 p->tr("Could not create snapshots folder '%s' (%Rrc)"), strTrgSnapshotFolder.c_str(), vrc);
1246 }
1247 /* Clone all save state files. */
1248 for (size_t i = 0; i < d->llSaveStateFiles.size(); ++i)
1249 {
1250 SAVESTATETASK sst = d->llSaveStateFiles.at(i);
1251 const Utf8Str &strTrgSaveState = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, RTPathFilename(sst.strSaveStateFile.c_str()));
1252
1253 /* Move to next sub-operation. */
1254 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Copy save state file '%s' ..."), RTPathFilename(sst.strSaveStateFile.c_str())).raw(), sst.uWeight);
1255 if (FAILED(rc)) throw rc;
1256 /* Copy the file only if it was not copied already. */
1257 if (!newFiles.contains(strTrgSaveState.c_str()))
1258 {
1259 int vrc = RTFileCopyEx(sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), 0, MachineCloneVMPrivate::copyStateFileProgress, &d->pProgress);
1260 if (RT_FAILURE(vrc))
1261 throw p->setError(VBOX_E_IPRT_ERROR,
1262 p->tr("Could not copy state file '%s' to '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), vrc);
1263 newFiles.append(strTrgSaveState);
1264 }
1265 /* Update the path in the configuration either for the current
1266 * machine state or the snapshots. */
1267 if (sst.snapshotUuid.isEmpty())
1268 trgMCF.strStateFile = strTrgSaveState;
1269 else
1270 d->updateStateFile(trgMCF.llFirstSnapshot, sst.snapshotUuid, strTrgSaveState);
1271 }
1272
1273 {
1274 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Create Machine Clone '%s' ..."), trgMCF.machineUserData.strName.c_str()).raw(), 1);
1275 if (FAILED(rc)) throw rc;
1276 /* After modifying the new machine config, we can copy the stuff
1277 * over to the new machine. The machine have to be mutable for
1278 * this. */
1279 rc = d->pTrgMachine->checkStateDependency(p->MutableStateDep);
1280 if (FAILED(rc)) throw rc;
1281 rc = d->pTrgMachine->loadMachineDataFromSettings(trgMCF,
1282 &d->pTrgMachine->mData->mUuid);
1283 if (FAILED(rc)) throw rc;
1284 }
1285
1286 /* Now save the new configuration to disk. */
1287 rc = d->pTrgMachine->SaveSettings();
1288 if (FAILED(rc)) throw rc;
1289 trgLock.release();
1290 if (!llRegistriesThatNeedSaving.empty())
1291 {
1292 srcLock.release();
1293 rc = p->mParent->saveRegistries(llRegistriesThatNeedSaving);
1294 if (FAILED(rc)) throw rc;
1295 }
1296 }
1297 catch (HRESULT rc2)
1298 {
1299 rc = rc2;
1300 }
1301 catch (...)
1302 {
1303 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
1304 }
1305
1306 MultiResult mrc(rc);
1307 /* Cleanup on failure (CANCEL also) */
1308 if (FAILED(rc))
1309 {
1310 int vrc = VINF_SUCCESS;
1311 /* Delete all created files. */
1312 for (size_t i = 0; i < newFiles.size(); ++i)
1313 {
1314 vrc = RTFileDelete(newFiles.at(i).c_str());
1315 if (RT_FAILURE(vrc))
1316 mrc = p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not delete file '%s' (%Rrc)"), newFiles.at(i).c_str(), vrc);
1317 }
1318 /* Delete all already created medias. (Reverse, cause there could be
1319 * parent->child relations.) */
1320 for (size_t i = newMedia.size(); i > 0; --i)
1321 {
1322 const ComObjPtr<Medium> &pMedium = newMedia.at(i - 1);
1323 mrc = pMedium->deleteStorage(NULL /* aProgress */,
1324 true /* aWait */,
1325 NULL /* llRegistriesThatNeedSaving */);
1326 pMedium->Close();
1327 }
1328 /* Delete the snapshot folder when not empty. */
1329 if (!strTrgSnapshotFolder.isEmpty())
1330 RTDirRemove(strTrgSnapshotFolder.c_str());
1331 /* Delete the machine folder when not empty. */
1332 RTDirRemove(strTrgMachineFolder.c_str());
1333 }
1334
1335 return mrc;
1336}
1337
1338void MachineCloneVM::destroy()
1339{
1340 delete this;
1341}
1342
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