VirtualBox

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

Last change on this file since 38145 was 38145, checked in by vboxsync, 13 years ago

Main-CloneVM: make this error fatal

  • 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 38145 2011-07-25 11:02:02Z 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 bool findSnapshot(const settings::SnapshotsList &snl, const Guid &id, settings::Snapshot &sn) 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
532bool MachineCloneVMPrivate::findSnapshot(const settings::SnapshotsList &snl, const Guid &id, settings::Snapshot &sn) const
533{
534 settings::SnapshotsList::const_iterator it;
535 for (it = snl.begin(); it != snl.end(); ++it)
536 {
537 if (it->uuid == id)
538 {
539 sn = (*it);
540 return true;
541 }
542 else if (!it->llChildSnapshots.empty())
543 {
544 if (findSnapshot(it->llChildSnapshots, id, sn))
545 return true;
546 }
547 }
548 return false;
549}
550
551void MachineCloneVMPrivate::updateMACAddresses(settings::NetworkAdaptersList &nwl) const
552{
553 const bool fNotNAT = options.contains(CloneOptions_KeepNATMACs);
554 settings::NetworkAdaptersList::iterator it;
555 for (it = nwl.begin(); it != nwl.end(); ++it)
556 {
557 if ( fNotNAT
558 && it->mode == NetworkAttachmentType_NAT)
559 continue;
560 Host::generateMACAddress(it->strMACAddress);
561 }
562}
563
564void MachineCloneVMPrivate::updateMACAddresses(settings::SnapshotsList &sl) const
565{
566 settings::SnapshotsList::iterator it;
567 for (it = sl.begin(); it != sl.end(); ++it)
568 {
569 updateMACAddresses(it->hardware.llNetworkAdapters);
570 if (!it->llChildSnapshots.empty())
571 updateMACAddresses(it->llChildSnapshots);
572 }
573}
574
575void MachineCloneVMPrivate::updateStorageLists(settings::StorageControllersList &sc, const Bstr &bstrOldId, const Bstr &bstrNewId) const
576{
577 settings::StorageControllersList::iterator it3;
578 for (it3 = sc.begin();
579 it3 != sc.end();
580 ++it3)
581 {
582 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
583 settings::AttachedDevicesList::iterator it4;
584 for (it4 = llAttachments.begin();
585 it4 != llAttachments.end();
586 ++it4)
587 {
588 if ( it4->deviceType == DeviceType_HardDisk
589 && it4->uuid == bstrOldId)
590 {
591 it4->uuid = bstrNewId;
592 }
593 }
594 }
595}
596
597void MachineCloneVMPrivate::updateSnapshotStorageLists(settings::SnapshotsList &sl, const Bstr &bstrOldId, const Bstr &bstrNewId) const
598{
599 settings::SnapshotsList::iterator it;
600 for ( it = sl.begin();
601 it != sl.end();
602 ++it)
603 {
604 updateStorageLists(it->storage.llStorageControllers, bstrOldId, bstrNewId);
605 if (!it->llChildSnapshots.empty())
606 updateSnapshotStorageLists(it->llChildSnapshots, bstrOldId, bstrNewId);
607 }
608}
609
610void MachineCloneVMPrivate::updateStateFile(settings::SnapshotsList &snl, const Guid &id, const Utf8Str &strFile) const
611{
612 settings::SnapshotsList::iterator it;
613 for (it = snl.begin(); it != snl.end(); ++it)
614 {
615 if (it->uuid == id)
616 it->strStateFile = strFile;
617 else if (!it->llChildSnapshots.empty())
618 updateStateFile(it->llChildSnapshots, id, strFile);
619 }
620}
621
622HRESULT MachineCloneVMPrivate::createDifferencingMedium(const ComObjPtr<Medium> &pParent, const Utf8Str &strSnapshotFolder, RTCList<ComObjPtr<Medium> > &newMedia, ComObjPtr<Medium> *ppDiff) const
623{
624 HRESULT rc = S_OK;
625 try
626 {
627 Bstr bstrSrcId;
628 rc = pParent->COMGETTER(Id)(bstrSrcId.asOutParam());
629 if (FAILED(rc)) throw rc;
630 ComObjPtr<Medium> diff;
631 diff.createObject();
632 rc = diff->init(p->getVirtualBox(),
633 pParent->getPreferredDiffFormat(),
634 Utf8StrFmt("%s%c", strSnapshotFolder.c_str(), RTPATH_DELIMITER),
635 Guid::Empty, /* empty media registry */
636 NULL); /* pllRegistriesThatNeedSaving */
637 if (FAILED(rc)) throw rc;
638 MediumLockList *pMediumLockList(new MediumLockList());
639 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
640 true /* fMediumLockWrite */,
641 pParent,
642 *pMediumLockList);
643 if (FAILED(rc)) throw rc;
644 rc = pMediumLockList->Lock();
645 if (FAILED(rc)) throw rc;
646 /* this already registers the new diff image */
647 rc = pParent->createDiffStorage(diff, MediumVariant_Standard,
648 pMediumLockList,
649 NULL /* aProgress */,
650 true /* aWait */,
651 NULL); // pllRegistriesThatNeedSaving
652 delete pMediumLockList;
653 if (FAILED(rc)) throw rc;
654 /* Remember created medium. */
655 newMedia.append(diff);
656 *ppDiff = diff;
657 }
658 catch (HRESULT rc2)
659 {
660 rc = rc2;
661 }
662 catch (...)
663 {
664 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
665 }
666
667 return rc;
668}
669
670/* static */
671int MachineCloneVMPrivate::copyStateFileProgress(unsigned uPercentage, void *pvUser)
672{
673 ComObjPtr<Progress> pProgress = *static_cast< ComObjPtr<Progress>* >(pvUser);
674
675 BOOL fCanceled = false;
676 HRESULT rc = pProgress->COMGETTER(Canceled)(&fCanceled);
677 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
678 /* If canceled by the user tell it to the copy operation. */
679 if (fCanceled) return VERR_CANCELLED;
680 /* Set the new process. */
681 rc = pProgress->SetCurrentOperationProgress(uPercentage);
682 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
683
684 return VINF_SUCCESS;
685}
686
687// The public class
688/////////////////////////////////////////////////////////////////////////////
689
690MachineCloneVM::MachineCloneVM(ComObjPtr<Machine> pSrcMachine, ComObjPtr<Machine> pTrgMachine, CloneMode_T mode, const RTCList<CloneOptions_T> &opts)
691 : d_ptr(new MachineCloneVMPrivate(this, pSrcMachine, pTrgMachine, mode, opts))
692{
693}
694
695MachineCloneVM::~MachineCloneVM()
696{
697 delete d_ptr;
698}
699
700HRESULT MachineCloneVM::start(IProgress **pProgress)
701{
702 DPTR(MachineCloneVM);
703 ComObjPtr<Machine> &p = d->p;
704
705 HRESULT rc;
706 try
707 {
708 /** @todo r=klaus this code cannot deal with someone crazy specifying
709 * IMachine corresponding to a mutable machine as d->pSrcMachine */
710 if (d->pSrcMachine->isSessionMachine())
711 throw E_FAIL;
712
713 /* Handle the special case that someone is requesting a _full_ clone
714 * with all snapshots (and the current state), but uses a snapshot
715 * machine (and not the current one) as source machine. In this case we
716 * just replace the source (snapshot) machine with the current machine. */
717 if ( d->mode == CloneMode_AllStates
718 && d->pSrcMachine->isSnapshotMachine())
719 {
720 Bstr bstrSrcMachineId;
721 rc = d->pSrcMachine->COMGETTER(Id)(bstrSrcMachineId.asOutParam());
722 if (FAILED(rc)) throw rc;
723 ComPtr<IMachine> newSrcMachine;
724 rc = d->pSrcMachine->getVirtualBox()->FindMachine(bstrSrcMachineId.raw(), newSrcMachine.asOutParam());
725 if (FAILED(rc)) throw rc;
726 d->pSrcMachine = (Machine*)(IMachine*)newSrcMachine;
727 }
728
729 bool fSubtreeIncludesCurrent = false;
730 ComObjPtr<Machine> pCurrState;
731 if (d->mode == CloneMode_MachineAndChildStates)
732 {
733 if (d->pSrcMachine->isSnapshotMachine())
734 {
735 /* find machine object for current snapshot of current state */
736 Bstr bstrSrcMachineId;
737 rc = d->pSrcMachine->COMGETTER(Id)(bstrSrcMachineId.asOutParam());
738 if (FAILED(rc)) throw rc;
739 ComPtr<IMachine> pCurr;
740 rc = d->pSrcMachine->getVirtualBox()->FindMachine(bstrSrcMachineId.raw(), pCurr.asOutParam());
741 if (FAILED(rc)) throw rc;
742 if (pCurr.isNull())
743 throw E_FAIL;
744 pCurrState = (Machine *)(IMachine *)pCurr;
745 ComPtr<ISnapshot> pSnapshot;
746 rc = pCurrState->COMGETTER(CurrentSnapshot)(pSnapshot.asOutParam());
747 if (FAILED(rc)) throw rc;
748 if (pSnapshot.isNull())
749 throw E_FAIL;
750 ComPtr<IMachine> pCurrSnapMachine;
751 rc = pSnapshot->COMGETTER(Machine)(pCurrSnapMachine.asOutParam());
752 if (FAILED(rc)) throw rc;
753 if (pCurrSnapMachine.isNull())
754 throw E_FAIL;
755
756 /* now check if there is a parent chain which leads to the
757 * snapshot machine defining the subtree. */
758 while (!pSnapshot.isNull())
759 {
760 ComPtr<IMachine> pSnapMachine;
761 rc = pSnapshot->COMGETTER(Machine)(pSnapMachine.asOutParam());
762 if (FAILED(rc)) throw rc;
763 if (pSnapMachine.isNull())
764 throw E_FAIL;
765 if (pSnapMachine == d->pSrcMachine)
766 {
767 fSubtreeIncludesCurrent = true;
768 break;
769 }
770 rc = pSnapshot->COMGETTER(Parent)(pSnapshot.asOutParam());
771 if (FAILED(rc)) throw rc;
772 }
773 }
774 else
775 {
776 /* If the subtree is only the Current State simply use the
777 * 'machine' case for cloning. It is easier to understand. */
778 d->mode = CloneMode_MachineState;
779 }
780 }
781
782 /* Lock the target machine early (so nobody mess around with it in the meantime). */
783 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
784
785 if (d->pSrcMachine->isSnapshotMachine())
786 d->snapshotId = d->pSrcMachine->getSnapshotId();
787
788 /* Add the current machine and all snapshot machines below this machine
789 * in a list for further processing. */
790 RTCList< ComObjPtr<Machine> > machineList;
791
792 /* Include current state? */
793 if ( d->mode == CloneMode_MachineState
794 || d->mode == CloneMode_AllStates)
795 machineList.append(d->pSrcMachine);
796 /* Should be done a depth copy with all child snapshots? */
797 if ( d->mode == CloneMode_MachineAndChildStates
798 || d->mode == CloneMode_AllStates)
799 {
800 ULONG cSnapshots = 0;
801 rc = d->pSrcMachine->COMGETTER(SnapshotCount)(&cSnapshots);
802 if (FAILED(rc)) throw rc;
803 if (cSnapshots > 0)
804 {
805 Utf8Str id;
806 if (d->mode == CloneMode_MachineAndChildStates)
807 id = d->snapshotId.toString();
808 ComPtr<ISnapshot> pSnapshot;
809 rc = d->pSrcMachine->FindSnapshot(Bstr(id).raw(), pSnapshot.asOutParam());
810 if (FAILED(rc)) throw rc;
811 rc = d->createMachineList(pSnapshot, machineList);
812 if (FAILED(rc)) throw rc;
813 if (d->mode == CloneMode_MachineAndChildStates)
814 {
815 if (fSubtreeIncludesCurrent)
816 {
817 /* zap d->snapshotId because there is no need to
818 * create a new current state. */
819 d->snapshotId.clear();
820 if (pCurrState.isNull())
821 throw E_FAIL;
822 machineList.append(pCurrState);
823 }
824 else
825 {
826 rc = pSnapshot->COMGETTER(Machine)(d->pOldMachineState.asOutParam());
827 if (FAILED(rc)) throw rc;
828 }
829 }
830 }
831 }
832
833 /* We have different approaches for getting the medias which needs to
834 * be replicated based on the clone mode the user requested (this is
835 * mostly about the full clone mode).
836 * MachineState:
837 * - Only the images which are directly attached to an source VM will
838 * be cloned. Any parent disks in the original chain will be merged
839 * into the final cloned disk.
840 * MachineAndChildStates:
841 * - In this case we search for images which have more than one
842 * children in the cloned VM or are directly attached to the new VM.
843 * All others will be merged into the remaining images which are
844 * cloned.
845 * This case is the most complicated one and needs several iterations
846 * to make sure we are only cloning images which are really
847 * necessary.
848 * AllStates:
849 * - All disks which are directly or indirectly attached to the
850 * original VM are cloned.
851 *
852 * Note: If you change something generic in one of the methods its
853 * likely that it need to be changed in the others as well! */
854 ULONG uCount = 2; /* One init task and the machine creation. */
855 ULONG uTotalWeight = 2; /* The init task and the machine creation is worth one. */
856 bool fAttachLinked = d->options.contains(CloneOptions_Link); /* Linked clones requested? */
857 switch (d->mode)
858 {
859 case CloneMode_MachineState: d->queryMediasForMachineState(machineList, fAttachLinked, uCount, uTotalWeight); break;
860 case CloneMode_MachineAndChildStates: d->queryMediasForMachineAndChildStates(machineList, fAttachLinked, uCount, uTotalWeight); break;
861 case CloneMode_AllStates: d->queryMediasForAllStates(machineList, fAttachLinked, uCount, uTotalWeight); break;
862 }
863
864 /* Now create the progress project, so the user knows whats going on. */
865 rc = d->pProgress.createObject();
866 if (FAILED(rc)) throw rc;
867 rc = d->pProgress->init(p->getVirtualBox(),
868 static_cast<IMachine*>(d->pSrcMachine) /* aInitiator */,
869 Bstr(p->tr("Cloning Machine")).raw(),
870 true /* fCancellable */,
871 uCount,
872 uTotalWeight,
873 Bstr(p->tr("Initialize Cloning")).raw(),
874 1);
875 if (FAILED(rc)) throw rc;
876
877 int vrc = d->startWorker();
878
879 if (RT_FAILURE(vrc))
880 p->setError(VBOX_E_IPRT_ERROR, "Could not create machine clone thread (%Rrc)", vrc);
881 }
882 catch (HRESULT rc2)
883 {
884 rc = rc2;
885 }
886
887 if (SUCCEEDED(rc))
888 d->pProgress.queryInterfaceTo(pProgress);
889
890 return rc;
891}
892
893HRESULT MachineCloneVM::run()
894{
895 DPTR(MachineCloneVM);
896 ComObjPtr<Machine> &p = d->p;
897
898 AutoCaller autoCaller(p);
899 if (FAILED(autoCaller.rc())) return autoCaller.rc();
900
901 AutoReadLock srcLock(p COMMA_LOCKVAL_SRC_POS);
902 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
903
904 HRESULT rc = S_OK;
905
906 /*
907 * Todo:
908 * - What about log files?
909 */
910
911 /* Where should all the media go? */
912 Utf8Str strTrgSnapshotFolder;
913 Utf8Str strTrgMachineFolder = d->pTrgMachine->getSettingsFileFull();
914 strTrgMachineFolder.stripFilename();
915
916 RTCList<ComObjPtr<Medium> > newMedia; /* All created images */
917 RTCList<Utf8Str> newFiles; /* All extra created files (save states, ...) */
918 try
919 {
920 /* Copy all the configuration from this machine to an empty
921 * configuration dataset. */
922 settings::MachineConfigFile trgMCF = *d->pSrcMachine->mData->pMachineConfigFile;
923
924 /* Reset media registry. */
925 trgMCF.mediaRegistry.llHardDisks.clear();
926 /* If we got a valid snapshot id, replace the hardware/storage section
927 * with the stuff from the snapshot. */
928 settings::Snapshot sn;
929 if (!d->snapshotId.isEmpty())
930 if (!d->findSnapshot(trgMCF.llFirstSnapshot, d->snapshotId, sn))
931 throw p->setError(E_FAIL,
932 p->tr("Could not find data to snapshots '%s'"), d->snapshotId.toString().c_str());
933
934
935
936 if (d->mode == CloneMode_MachineState)
937 {
938 if (!sn.uuid.isEmpty())
939 {
940 trgMCF.hardwareMachine = sn.hardware;
941 trgMCF.storageMachine = sn.storage;
942 }
943
944 /* Remove any hint on snapshots. */
945 trgMCF.llFirstSnapshot.clear();
946 trgMCF.uuidCurrentSnapshot.clear();
947 }
948 else if ( d->mode == CloneMode_MachineAndChildStates
949 && !sn.uuid.isEmpty())
950 {
951 /* Copy the snapshot data to the current machine. */
952 trgMCF.hardwareMachine = sn.hardware;
953 trgMCF.storageMachine = sn.storage;
954
955 /* The snapshot will be the root one. */
956 trgMCF.uuidCurrentSnapshot = sn.uuid;
957 trgMCF.llFirstSnapshot.clear();
958 trgMCF.llFirstSnapshot.push_back(sn);
959 }
960
961 /* Generate new MAC addresses for all machines when not forbidden. */
962 if (!d->options.contains(CloneOptions_KeepAllMACs))
963 {
964 d->updateMACAddresses(trgMCF.hardwareMachine.llNetworkAdapters);
965 d->updateMACAddresses(trgMCF.llFirstSnapshot);
966 }
967
968 /* When the current snapshot folder is absolute we reset it to the
969 * default relative folder. */
970 if (RTPathStartsWithRoot(trgMCF.machineUserData.strSnapshotFolder.c_str()))
971 trgMCF.machineUserData.strSnapshotFolder = "Snapshots";
972 trgMCF.strStateFile = "";
973 /* Force writing of setting file. */
974 trgMCF.fCurrentStateModified = true;
975 /* Set the new name. */
976 const Utf8Str strOldVMName = trgMCF.machineUserData.strName;
977 trgMCF.machineUserData.strName = d->pTrgMachine->mUserData->s.strName;
978 trgMCF.uuid = d->pTrgMachine->mData->mUuid;
979
980 Bstr bstrSrcSnapshotFolder;
981 rc = d->pSrcMachine->COMGETTER(SnapshotFolder)(bstrSrcSnapshotFolder.asOutParam());
982 if (FAILED(rc)) throw rc;
983 /* The absolute name of the snapshot folder. */
984 strTrgSnapshotFolder = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, trgMCF.machineUserData.strSnapshotFolder.c_str());
985
986 /* Should we rename the disk names. */
987 bool fKeepDiskNames = d->options.contains(CloneOptions_KeepDiskNames);
988
989 /* We need to create a map with the already created medias. This is
990 * necessary, cause different snapshots could have the same
991 * parents/parent chain. If a medium is in this map already, it isn't
992 * cloned a second time, but simply used. */
993 typedef std::map<Utf8Str, ComObjPtr<Medium> > TStrMediumMap;
994 typedef std::pair<Utf8Str, ComObjPtr<Medium> > TStrMediumPair;
995 TStrMediumMap map;
996 GuidList llRegistriesThatNeedSaving;
997 size_t cDisks = 0;
998 for (size_t i = 0; i < d->llMedias.size(); ++i)
999 {
1000 const MEDIUMTASKCHAIN &mtc = d->llMedias.at(i);
1001 ComObjPtr<Medium> pNewParent;
1002 for (size_t a = mtc.chain.size(); a > 0; --a)
1003 {
1004 const MEDIUMTASK &mt = mtc.chain.at(a - 1);
1005 ComPtr<IMedium> pMedium = mt.pMedium;
1006
1007 Bstr bstrSrcName;
1008 rc = pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
1009 if (FAILED(rc)) throw rc;
1010
1011 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Cloning Disk '%ls' ..."), bstrSrcName.raw()).raw(), mt.uWeight);
1012 if (FAILED(rc)) throw rc;
1013
1014 Bstr bstrSrcId;
1015 rc = pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
1016 if (FAILED(rc)) throw rc;
1017
1018 if (mtc.fAttachLinked)
1019 {
1020 IMedium *pTmp = pMedium;
1021 ComObjPtr<Medium> pLMedium = static_cast<Medium*>(pTmp);
1022 if (pLMedium.isNull())
1023 throw E_POINTER;
1024 ComObjPtr<Medium> pBase = pLMedium->getBase();
1025 if (pBase->isReadOnly())
1026 {
1027 ComObjPtr<Medium> pDiff;
1028 /* create the diff under the snapshot medium */
1029 rc = d->createDifferencingMedium(pLMedium, strTrgSnapshotFolder,
1030 newMedia, &pDiff);
1031 if (FAILED(rc)) throw rc;
1032 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pDiff));
1033 /* diff image has to be used... */
1034 pNewParent = pDiff;
1035 }
1036 else
1037 {
1038 /* Attach the medium directly, as its type is not
1039 * subject to diff creation. */
1040 newMedia.append(pLMedium);
1041 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pLMedium));
1042 pNewParent = pLMedium;
1043 }
1044 }
1045 else
1046 {
1047 /* Is a clone already there? */
1048 TStrMediumMap::iterator it = map.find(Utf8Str(bstrSrcId));
1049 if (it != map.end())
1050 pNewParent = it->second;
1051 else
1052 {
1053 ComPtr<IMediumFormat> pSrcFormat;
1054 rc = pMedium->COMGETTER(MediumFormat)(pSrcFormat.asOutParam());
1055 ULONG uSrcCaps = 0;
1056 rc = pSrcFormat->COMGETTER(Capabilities)(&uSrcCaps);
1057 if (FAILED(rc)) throw rc;
1058
1059 /* Default format? */
1060 Utf8Str strDefaultFormat;
1061 p->mParent->getDefaultHardDiskFormat(strDefaultFormat);
1062 Bstr bstrSrcFormat(strDefaultFormat);
1063 ULONG srcVar = MediumVariant_Standard;
1064 /* Is the source file based? */
1065 if ((uSrcCaps & MediumFormatCapabilities_File) == MediumFormatCapabilities_File)
1066 {
1067 /* Yes, just use the source format. Otherwise the defaults
1068 * will be used. */
1069 rc = pMedium->COMGETTER(Format)(bstrSrcFormat.asOutParam());
1070 if (FAILED(rc)) throw rc;
1071 rc = pMedium->COMGETTER(Variant)(&srcVar);
1072 if (FAILED(rc)) throw rc;
1073 }
1074
1075 Guid newId;
1076 newId.create();
1077 Utf8Str strNewName(bstrSrcName);
1078 if (!fKeepDiskNames)
1079 {
1080 Utf8Str strSrcTest = bstrSrcName;
1081 /* Check if we have to use another name. */
1082 if (!mt.strBaseName.isEmpty())
1083 strSrcTest = mt.strBaseName;
1084 strSrcTest.stripExt();
1085 /* If the old disk name was in {uuid} format we also
1086 * want the new name in this format, but with the
1087 * updated id of course. If the old disk was called
1088 * like the VM name, we change it to the new VM name.
1089 * For all other disks we rename them with this
1090 * template: "new name-disk1.vdi". */
1091 if (strSrcTest == strOldVMName)
1092 strNewName = Utf8StrFmt("%s%s", trgMCF.machineUserData.strName.c_str(), RTPathExt(Utf8Str(bstrSrcName).c_str()));
1093 else if ( strSrcTest.startsWith("{")
1094 && strSrcTest.endsWith("}"))
1095 {
1096 strSrcTest = strSrcTest.substr(1, strSrcTest.length() - 2);
1097 if (isValidGuid(strSrcTest))
1098 strNewName = Utf8StrFmt("%s%s", newId.toStringCurly().c_str(), RTPathExt(strNewName.c_str()));
1099 }
1100 else
1101 strNewName = Utf8StrFmt("%s-disk%d%s", trgMCF.machineUserData.strName.c_str(), ++cDisks, RTPathExt(Utf8Str(bstrSrcName).c_str()));
1102 }
1103
1104 /* Check if this medium comes from the snapshot folder, if
1105 * so, put it there in the cloned machine as well.
1106 * Otherwise it goes to the machine folder. */
1107 Bstr bstrSrcPath;
1108 Utf8Str strFile = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
1109 rc = pMedium->COMGETTER(Location)(bstrSrcPath.asOutParam());
1110 if (FAILED(rc)) throw rc;
1111 if ( !bstrSrcPath.isEmpty()
1112 && RTPathStartsWith(Utf8Str(bstrSrcPath).c_str(), Utf8Str(bstrSrcSnapshotFolder).c_str())
1113 && (fKeepDiskNames || mt.strBaseName.isEmpty()))
1114 strFile = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
1115
1116 /* Start creating the clone. */
1117 ComObjPtr<Medium> pTarget;
1118 rc = pTarget.createObject();
1119 if (FAILED(rc)) throw rc;
1120
1121 rc = pTarget->init(p->mParent,
1122 Utf8Str(bstrSrcFormat),
1123 strFile,
1124 Guid::Empty, /* empty media registry */
1125 NULL /* llRegistriesThatNeedSaving */);
1126 if (FAILED(rc)) throw rc;
1127
1128 /* Update the new uuid. */
1129 pTarget->updateId(newId);
1130
1131 srcLock.release();
1132 /* Do the disk cloning. */
1133 ComPtr<IProgress> progress2;
1134 rc = pMedium->CloneTo(pTarget,
1135 srcVar,
1136 pNewParent,
1137 progress2.asOutParam());
1138 if (FAILED(rc)) throw rc;
1139
1140 /* Wait until the async process has finished. */
1141 rc = d->pProgress->WaitForAsyncProgressCompletion(progress2);
1142 srcLock.acquire();
1143 if (FAILED(rc)) throw rc;
1144
1145 /* Check the result of the async process. */
1146 LONG iRc;
1147 rc = progress2->COMGETTER(ResultCode)(&iRc);
1148 if (FAILED(rc)) throw rc;
1149 if (FAILED(iRc))
1150 {
1151 /* If the thread of the progress object has an error, then
1152 * retrieve the error info from there, or it'll be lost. */
1153 ProgressErrorInfo info(progress2);
1154 throw p->setError(iRc, Utf8Str(info.getText()).c_str());
1155 }
1156 /* Remember created medium. */
1157 newMedia.append(pTarget);
1158 /* Get the medium type from the source and set it to the
1159 * new medium. */
1160 MediumType_T type;
1161 rc = pMedium->COMGETTER(Type)(&type);
1162 if (FAILED(rc)) throw rc;
1163 rc = pTarget->COMSETTER(Type)(type);
1164 if (FAILED(rc)) throw rc;
1165 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pTarget));
1166 /* register the new harddisk */
1167 {
1168 AutoWriteLock tlock(p->mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1169 rc = p->mParent->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
1170 if (FAILED(rc)) throw rc;
1171 }
1172 /* This medium becomes the parent of the next medium in the
1173 * chain. */
1174 pNewParent = pTarget;
1175 }
1176 }
1177 }
1178
1179 Bstr bstrSrcId;
1180 rc = mtc.chain.first().pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
1181 if (FAILED(rc)) throw rc;
1182 Bstr bstrTrgId;
1183 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
1184 if (FAILED(rc)) throw rc;
1185 /* update snapshot configuration */
1186 d->updateSnapshotStorageLists(trgMCF.llFirstSnapshot, bstrSrcId, bstrTrgId);
1187
1188 /* create new 'Current State' diff for caller defined place */
1189 if (mtc.fCreateDiffs)
1190 {
1191 const MEDIUMTASK &mt = mtc.chain.first();
1192 ComObjPtr<Medium> pLMedium = static_cast<Medium*>((IMedium*)mt.pMedium);
1193 if (pLMedium.isNull())
1194 throw E_POINTER;
1195 ComObjPtr<Medium> pBase = pLMedium->getBase();
1196 if (pBase->isReadOnly())
1197 {
1198 ComObjPtr<Medium> pDiff;
1199 rc = d->createDifferencingMedium(pNewParent, strTrgSnapshotFolder,
1200 newMedia, &pDiff);
1201 if (FAILED(rc)) throw rc;
1202 /* diff image has to be used... */
1203 pNewParent = pDiff;
1204 }
1205 else
1206 {
1207 /* Attach the medium directly, as its type is not
1208 * subject to diff creation. */
1209 newMedia.append(pNewParent);
1210 }
1211
1212 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
1213 if (FAILED(rc)) throw rc;
1214 }
1215 /* update 'Current State' configuration */
1216 d->updateStorageLists(trgMCF.storageMachine.llStorageControllers, bstrSrcId, bstrTrgId);
1217 }
1218 /* Make sure all disks know of the new machine uuid. We do this last to
1219 * be able to change the medium type above. */
1220 for (size_t i = newMedia.size(); i > 0; --i)
1221 {
1222 const ComObjPtr<Medium> &pMedium = newMedia.at(i - 1);
1223 AutoCaller mac(pMedium);
1224 if (FAILED(mac.rc())) throw mac.rc();
1225 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
1226 Guid uuid = d->pTrgMachine->mData->mUuid;
1227 if (d->options.contains(CloneOptions_Link))
1228 {
1229 ComObjPtr<Medium> pParent = pMedium->getParent();
1230 mlock.release();
1231 if (!pParent.isNull())
1232 {
1233 AutoCaller mac2(pParent);
1234 if (FAILED(mac2.rc())) throw mac2.rc();
1235 AutoReadLock mlock2(pParent COMMA_LOCKVAL_SRC_POS);
1236 if (pParent->getFirstRegistryMachineId(uuid))
1237 VirtualBox::addGuidToListUniquely(llRegistriesThatNeedSaving, uuid);
1238 }
1239 mlock.acquire();
1240 }
1241 pMedium->addRegistry(uuid, false /* fRecurse */);
1242 }
1243 /* Check if a snapshot folder is necessary and if so doesn't already
1244 * exists. */
1245 if ( !d->llSaveStateFiles.isEmpty()
1246 && !RTDirExists(strTrgSnapshotFolder.c_str()))
1247 {
1248 int vrc = RTDirCreateFullPath(strTrgSnapshotFolder.c_str(), 0777);
1249 if (RT_FAILURE(vrc))
1250 throw p->setError(VBOX_E_IPRT_ERROR,
1251 p->tr("Could not create snapshots folder '%s' (%Rrc)"), strTrgSnapshotFolder.c_str(), vrc);
1252 }
1253 /* Clone all save state files. */
1254 for (size_t i = 0; i < d->llSaveStateFiles.size(); ++i)
1255 {
1256 SAVESTATETASK sst = d->llSaveStateFiles.at(i);
1257 const Utf8Str &strTrgSaveState = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, RTPathFilename(sst.strSaveStateFile.c_str()));
1258
1259 /* Move to next sub-operation. */
1260 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Copy save state file '%s' ..."), RTPathFilename(sst.strSaveStateFile.c_str())).raw(), sst.uWeight);
1261 if (FAILED(rc)) throw rc;
1262 /* Copy the file only if it was not copied already. */
1263 if (!newFiles.contains(strTrgSaveState.c_str()))
1264 {
1265 int vrc = RTFileCopyEx(sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), 0, MachineCloneVMPrivate::copyStateFileProgress, &d->pProgress);
1266 if (RT_FAILURE(vrc))
1267 throw p->setError(VBOX_E_IPRT_ERROR,
1268 p->tr("Could not copy state file '%s' to '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), vrc);
1269 newFiles.append(strTrgSaveState);
1270 }
1271 /* Update the path in the configuration either for the current
1272 * machine state or the snapshots. */
1273 if (sst.snapshotUuid.isEmpty())
1274 trgMCF.strStateFile = strTrgSaveState;
1275 else
1276 d->updateStateFile(trgMCF.llFirstSnapshot, sst.snapshotUuid, strTrgSaveState);
1277 }
1278
1279 {
1280 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Create Machine Clone '%s' ..."), trgMCF.machineUserData.strName.c_str()).raw(), 1);
1281 if (FAILED(rc)) throw rc;
1282 /* After modifying the new machine config, we can copy the stuff
1283 * over to the new machine. The machine have to be mutable for
1284 * this. */
1285 rc = d->pTrgMachine->checkStateDependency(p->MutableStateDep);
1286 if (FAILED(rc)) throw rc;
1287 rc = d->pTrgMachine->loadMachineDataFromSettings(trgMCF,
1288 &d->pTrgMachine->mData->mUuid);
1289 if (FAILED(rc)) throw rc;
1290 }
1291
1292 /* Now save the new configuration to disk. */
1293 rc = d->pTrgMachine->SaveSettings();
1294 if (FAILED(rc)) throw rc;
1295 trgLock.release();
1296 if (!llRegistriesThatNeedSaving.empty())
1297 {
1298 srcLock.release();
1299 rc = p->mParent->saveRegistries(llRegistriesThatNeedSaving);
1300 if (FAILED(rc)) throw rc;
1301 }
1302 }
1303 catch (HRESULT rc2)
1304 {
1305 rc = rc2;
1306 }
1307 catch (...)
1308 {
1309 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
1310 }
1311
1312 MultiResult mrc(rc);
1313 /* Cleanup on failure (CANCEL also) */
1314 if (FAILED(rc))
1315 {
1316 int vrc = VINF_SUCCESS;
1317 /* Delete all created files. */
1318 for (size_t i = 0; i < newFiles.size(); ++i)
1319 {
1320 vrc = RTFileDelete(newFiles.at(i).c_str());
1321 if (RT_FAILURE(vrc))
1322 mrc = p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not delete file '%s' (%Rrc)"), newFiles.at(i).c_str(), vrc);
1323 }
1324 /* Delete all already created medias. (Reverse, cause there could be
1325 * parent->child relations.) */
1326 for (size_t i = newMedia.size(); i > 0; --i)
1327 {
1328 const ComObjPtr<Medium> &pMedium = newMedia.at(i - 1);
1329 mrc = pMedium->deleteStorage(NULL /* aProgress */,
1330 true /* aWait */,
1331 NULL /* llRegistriesThatNeedSaving */);
1332 pMedium->Close();
1333 }
1334 /* Delete the snapshot folder when not empty. */
1335 if (!strTrgSnapshotFolder.isEmpty())
1336 RTDirRemove(strTrgSnapshotFolder.c_str());
1337 /* Delete the machine folder when not empty. */
1338 RTDirRemove(strTrgMachineFolder.c_str());
1339 }
1340
1341 return mrc;
1342}
1343
1344void MachineCloneVM::destroy()
1345{
1346 delete this;
1347}
1348
Note: See TracBrowser for help on using the repository browser.

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