VirtualBox

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

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

Main-CloneVM: change the name of a cloned disk to the new VM name, if the old was the old VM name

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 36.1 KB
Line 
1/* $Id: MachineImplCloneVM.cpp 37905 2011-07-12 15:37:33Z 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
28#include <VBox/com/list.h>
29#include <VBox/com/MultiResult.h>
30
31// typedefs
32/////////////////////////////////////////////////////////////////////////////
33
34typedef struct
35{
36 ComPtr<IMedium> pMedium;
37 ULONG uWeight;
38}MEDIUMTASK;
39
40typedef struct
41{
42 RTCList<MEDIUMTASK> chain;
43 bool fCreateDiffs;
44}MEDIUMTASKCHAIN;
45
46typedef struct
47{
48 Guid snapshotUuid;
49 Utf8Str strSaveStateFile;
50 ULONG uWeight;
51}SAVESTATETASK;
52
53// The private class
54/////////////////////////////////////////////////////////////////////////////
55
56struct MachineCloneVMPrivate
57{
58 MachineCloneVMPrivate(MachineCloneVM *a_q, ComObjPtr<Machine> &a_pSrcMachine, ComObjPtr<Machine> &a_pTrgMachine, CloneMode_T a_mode, const RTCList<CloneOptions_T> &opts)
59 : q_ptr(a_q)
60 , p(a_pSrcMachine)
61 , pSrcMachine(a_pSrcMachine)
62 , pTrgMachine(a_pTrgMachine)
63 , mode(a_mode)
64 , options(opts)
65 {}
66
67 /* Thread management */
68 int startWorker()
69 {
70 return RTThreadCreate(NULL,
71 MachineCloneVMPrivate::workerThread,
72 static_cast<void*>(this),
73 0,
74 RTTHREADTYPE_MAIN_WORKER,
75 0,
76 "MachineClone");
77 }
78
79 static int workerThread(RTTHREAD /* Thread */, void *pvUser)
80 {
81 MachineCloneVMPrivate *pTask = static_cast<MachineCloneVMPrivate*>(pvUser);
82 AssertReturn(pTask, VERR_INVALID_POINTER);
83
84 HRESULT rc = pTask->q_ptr->run();
85
86 pTask->pProgress->notifyComplete(rc);
87
88 pTask->q_ptr->destroy();
89
90 return VINF_SUCCESS;
91 }
92
93 /* Private helper methods */
94 HRESULT createMachineList(const ComPtr<ISnapshot> &pSnapshot, RTCList< ComObjPtr<Machine> > &machineList) const;
95 settings::Snapshot findSnapshot(settings::MachineConfigFile *pMCF, const settings::SnapshotsList &snl, const Guid &id) const;
96 void updateMACAddresses(settings::NetworkAdaptersList &nwl) const;
97 void updateMACAddresses(settings::SnapshotsList &sl) const;
98 void updateStorageLists(settings::StorageControllersList &sc, const Bstr &bstrOldId, const Bstr &bstrNewId) const;
99 void updateSnapshotStorageLists(settings::SnapshotsList &sl, const Bstr &bstrOldId, const Bstr &bstrNewId) const;
100 void updateStateFile(settings::SnapshotsList &snl, const Guid &id, const Utf8Str &strFile) const;
101 static int copyStateFileProgress(unsigned uPercentage, void *pvUser);
102
103 /* Private q and parent pointer */
104 MachineCloneVM *q_ptr;
105 ComObjPtr<Machine> p;
106
107 /* Private helper members */
108 ComObjPtr<Machine> pSrcMachine;
109 ComObjPtr<Machine> pTrgMachine;
110 ComPtr<IMachine> pOldMachineState;
111 ComObjPtr<Progress> pProgress;
112 Guid snapshotId;
113 CloneMode_T mode;
114 RTCList<CloneOptions_T> options;
115 RTCList<MEDIUMTASKCHAIN> llMedias;
116 RTCList<SAVESTATETASK> llSaveStateFiles; /* Snapshot UUID -> File path */
117};
118
119HRESULT MachineCloneVMPrivate::createMachineList(const ComPtr<ISnapshot> &pSnapshot, RTCList< ComObjPtr<Machine> > &machineList) const
120{
121 HRESULT rc = S_OK;
122 Bstr name;
123 rc = pSnapshot->COMGETTER(Name)(name.asOutParam());
124 if (FAILED(rc)) return rc;
125
126 ComPtr<IMachine> pMachine;
127 rc = pSnapshot->COMGETTER(Machine)(pMachine.asOutParam());
128 if (FAILED(rc)) return rc;
129 machineList.append((Machine*)(IMachine*)pMachine);
130
131 SafeIfaceArray<ISnapshot> sfaChilds;
132 rc = pSnapshot->COMGETTER(Children)(ComSafeArrayAsOutParam(sfaChilds));
133 if (FAILED(rc)) return rc;
134 for (size_t i = 0; i < sfaChilds.size(); ++i)
135 {
136 rc = createMachineList(sfaChilds[i], machineList);
137 if (FAILED(rc)) return rc;
138 }
139
140 return rc;
141}
142
143settings::Snapshot MachineCloneVMPrivate::findSnapshot(settings::MachineConfigFile *pMCF, const settings::SnapshotsList &snl, const Guid &id) const
144{
145 settings::SnapshotsList::const_iterator it;
146 for (it = snl.begin(); it != snl.end(); ++it)
147 {
148 if (it->uuid == id)
149 return *it;
150 else if (!it->llChildSnapshots.empty())
151 return findSnapshot(pMCF, it->llChildSnapshots, id);
152 }
153 return settings::Snapshot();
154}
155
156void MachineCloneVMPrivate::updateMACAddresses(settings::NetworkAdaptersList &nwl) const
157{
158 const bool fNotNAT = options.contains(CloneOptions_KeepNATMACs);
159 settings::NetworkAdaptersList::iterator it;
160 for (it = nwl.begin(); it != nwl.end(); ++it)
161 {
162 if ( fNotNAT
163 && it->mode == NetworkAttachmentType_NAT)
164 continue;
165 Host::generateMACAddress(it->strMACAddress);
166 }
167}
168
169void MachineCloneVMPrivate::updateMACAddresses(settings::SnapshotsList &sl) const
170{
171 settings::SnapshotsList::iterator it;
172 for (it = sl.begin(); it != sl.end(); ++it)
173 {
174 updateMACAddresses(it->hardware.llNetworkAdapters);
175 if (!it->llChildSnapshots.empty())
176 updateMACAddresses(it->llChildSnapshots);
177 }
178}
179
180void MachineCloneVMPrivate::updateStorageLists(settings::StorageControllersList &sc, const Bstr &bstrOldId, const Bstr &bstrNewId) const
181{
182 settings::StorageControllersList::iterator it3;
183 for (it3 = sc.begin();
184 it3 != sc.end();
185 ++it3)
186 {
187 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
188 settings::AttachedDevicesList::iterator it4;
189 for (it4 = llAttachments.begin();
190 it4 != llAttachments.end();
191 ++it4)
192 {
193 if ( it4->deviceType == DeviceType_HardDisk
194 && it4->uuid == bstrOldId)
195 {
196 it4->uuid = bstrNewId;
197 }
198 }
199 }
200}
201
202void MachineCloneVMPrivate::updateSnapshotStorageLists(settings::SnapshotsList &sl, const Bstr &bstrOldId, const Bstr &bstrNewId) const
203{
204 settings::SnapshotsList::iterator it;
205 for ( it = sl.begin();
206 it != sl.end();
207 ++it)
208 {
209 updateStorageLists(it->storage.llStorageControllers, bstrOldId, bstrNewId);
210 if (!it->llChildSnapshots.empty())
211 updateSnapshotStorageLists(it->llChildSnapshots, bstrOldId, bstrNewId);
212 }
213}
214
215void MachineCloneVMPrivate::updateStateFile(settings::SnapshotsList &snl, const Guid &id, const Utf8Str &strFile) const
216{
217 settings::SnapshotsList::iterator it;
218 for (it = snl.begin(); it != snl.end(); ++it)
219 {
220 if (it->uuid == id)
221 it->strStateFile = strFile;
222 else if (!it->llChildSnapshots.empty())
223 updateStateFile(it->llChildSnapshots, id, strFile);
224 }
225}
226
227/* static */
228int MachineCloneVMPrivate::copyStateFileProgress(unsigned uPercentage, void *pvUser)
229{
230 ComObjPtr<Progress> pProgress = *static_cast< ComObjPtr<Progress>* >(pvUser);
231
232 BOOL fCanceled = false;
233 HRESULT rc = pProgress->COMGETTER(Canceled)(&fCanceled);
234 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
235 /* If canceled by the user tell it to the copy operation. */
236 if (fCanceled) return VERR_CANCELLED;
237 /* Set the new process. */
238 rc = pProgress->SetCurrentOperationProgress(uPercentage);
239 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
240
241 return VINF_SUCCESS;
242}
243
244// The public class
245/////////////////////////////////////////////////////////////////////////////
246
247MachineCloneVM::MachineCloneVM(ComObjPtr<Machine> pSrcMachine, ComObjPtr<Machine> pTrgMachine, CloneMode_T mode, const RTCList<CloneOptions_T> &opts)
248 : d_ptr(new MachineCloneVMPrivate(this, pSrcMachine, pTrgMachine, mode, opts))
249{
250}
251
252MachineCloneVM::~MachineCloneVM()
253{
254 delete d_ptr;
255}
256
257HRESULT MachineCloneVM::start(IProgress **pProgress)
258{
259 DPTR(MachineCloneVM);
260 ComObjPtr<Machine> &p = d->p;
261
262 HRESULT rc;
263 try
264 {
265 /* Handle the special case that someone is requesting a _full_ clone
266 * with all snapshots (and the current state), but uses a snapshot
267 * machine (and not the current one) as source machine. In this case we
268 * just replace the source (snapshot) machine with the current machine. */
269 if ( d->mode == CloneMode_AllStates
270 && d->pSrcMachine->isSnapshotMachine())
271 {
272 Bstr bstrSrcMachineId;
273 rc = d->pSrcMachine->COMGETTER(Id)(bstrSrcMachineId.asOutParam());
274 if (FAILED(rc)) throw rc;
275 ComPtr<IMachine> newSrcMachine;
276 rc = d->pSrcMachine->getVirtualBox()->FindMachine(bstrSrcMachineId.raw(), newSrcMachine.asOutParam());
277 if (FAILED(rc)) throw rc;
278 d->pSrcMachine = (Machine*)(IMachine*)newSrcMachine;
279 }
280
281 /* Lock the target machine early (so nobody mess around with it in the meantime). */
282 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
283
284 if (d->pSrcMachine->isSnapshotMachine())
285 d->snapshotId = d->pSrcMachine->getSnapshotId();
286
287 /* Add the current machine and all snapshot machines below this machine
288 * in a list for further processing. */
289 RTCList< ComObjPtr<Machine> > machineList;
290
291 /* Include current state? */
292 if ( d->mode == CloneMode_MachineState
293 || d->mode == CloneMode_AllStates)
294 machineList.append(d->pSrcMachine);
295 /* Should be done a depth copy with all child snapshots? */
296 if ( d->mode == CloneMode_MachineAndChildStates
297 || d->mode == CloneMode_AllStates)
298 {
299 ULONG cSnapshots = 0;
300 rc = d->pSrcMachine->COMGETTER(SnapshotCount)(&cSnapshots);
301 if (FAILED(rc)) throw rc;
302 if (cSnapshots > 0)
303 {
304 Utf8Str id;
305 if ( d->mode == CloneMode_MachineAndChildStates
306 && !d->snapshotId.isEmpty())
307 id = d->snapshotId.toString();
308 ComPtr<ISnapshot> pSnapshot;
309 rc = d->pSrcMachine->FindSnapshot(Bstr(id).raw(), pSnapshot.asOutParam());
310 if (FAILED(rc)) throw rc;
311 rc = d->createMachineList(pSnapshot, machineList);
312 if (FAILED(rc)) throw rc;
313 if (d->mode == CloneMode_MachineAndChildStates)
314 {
315 rc = pSnapshot->COMGETTER(Machine)(d->pOldMachineState.asOutParam());
316 if (FAILED(rc)) throw rc;
317 }
318 }
319 }
320
321 /* Go over every machine and walk over every attachment this machine has. */
322 ULONG uCount = 2; /* One init task and the machine creation. */
323 ULONG uTotalWeight = 2; /* The init task and the machine creation is worth one. */
324 for (size_t i = 0; i < machineList.size(); ++i)
325 {
326 ComObjPtr<Machine> machine = machineList.at(i);
327 /* If this is the Snapshot Machine we want to clone, we need to
328 * create a new diff file for the new "current state". */
329 bool fCreateDiffs = false;
330 if (machine == d->pOldMachineState)
331 fCreateDiffs = true;
332 SafeIfaceArray<IMediumAttachment> sfaAttachments;
333 rc = machine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
334 if (FAILED(rc)) throw rc;
335 /* Add all attachments (and their parents) of the different
336 * machines to a worker list. */
337 for (size_t a = 0; a < sfaAttachments.size(); ++a)
338 {
339 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
340 DeviceType_T type;
341 rc = pAtt->COMGETTER(Type)(&type);
342 if (FAILED(rc)) throw rc;
343
344 /* Only harddisk's are of interest. */
345 if (type != DeviceType_HardDisk)
346 continue;
347
348 /* Valid medium attached? */
349 ComPtr<IMedium> pSrcMedium;
350 rc = pAtt->COMGETTER(Medium)(pSrcMedium.asOutParam());
351 if (FAILED(rc)) throw rc;
352 if (pSrcMedium.isNull())
353 continue;
354
355 /* Build up a child->parent list of this attachment. (Note: we are
356 * not interested of any child's not attached to this VM. So this
357 * will not create a full copy of the base/child relationship.) */
358 MEDIUMTASKCHAIN mtc;
359 mtc.fCreateDiffs = fCreateDiffs;
360 while(!pSrcMedium.isNull())
361 {
362 /* Refresh the state so that the file size get read. */
363 MediumState_T e;
364 rc = pSrcMedium->RefreshState(&e);
365 if (FAILED(rc)) throw rc;
366 LONG64 lSize;
367 rc = pSrcMedium->COMGETTER(Size)(&lSize);
368 if (FAILED(rc)) throw rc;
369
370 /* Save the current medium, for later cloning. */
371 MEDIUMTASK mt;
372 mt.pMedium = pSrcMedium;
373 mt.uWeight = (lSize + _1M - 1) / _1M;
374 mtc.chain.append(mt);
375
376 /* Query next parent. */
377 rc = pSrcMedium->COMGETTER(Parent)(pSrcMedium.asOutParam());
378 if (FAILED(rc)) throw rc;
379 };
380 /* Currently the creation of diff images involves reading at least
381 * the biggest parent in the previous chain. So even if the new
382 * diff image is small in size, it could need some time to create
383 * it. Adding the biggest size in the chain should balance this a
384 * little bit more, i.e. the weight is the sum of the data which
385 * needs to be read and written. */
386 uint64_t uMaxSize = 0;
387 for (size_t e = mtc.chain.size(); e > 0; --e)
388 {
389 MEDIUMTASK &mt = mtc.chain.at(e - 1);
390 mt.uWeight += uMaxSize;
391
392 /* Calculate progress data */
393 ++uCount;
394 uTotalWeight += mt.uWeight;
395
396 /* Save the max size for better weighting of diff image
397 * creation. */
398 uMaxSize = RT_MAX(uMaxSize, mt.uWeight);
399 }
400 d->llMedias.append(mtc);
401 }
402 Bstr bstrSrcSaveStatePath;
403 rc = machine->COMGETTER(StateFilePath)(bstrSrcSaveStatePath.asOutParam());
404 if (FAILED(rc)) throw rc;
405 if (!bstrSrcSaveStatePath.isEmpty())
406 {
407 SAVESTATETASK sst;
408 sst.snapshotUuid = machine->getSnapshotId();
409 sst.strSaveStateFile = bstrSrcSaveStatePath;
410 uint64_t cbSize;
411 int vrc = RTFileQuerySize(sst.strSaveStateFile.c_str(), &cbSize);
412 if (RT_FAILURE(vrc))
413 throw p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not query file size of '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), vrc);
414 /* same rule as above: count both the data which needs to
415 * be read and written */
416 sst.uWeight = 2 * (cbSize + _1M - 1) / _1M;
417 d->llSaveStateFiles.append(sst);
418 ++uCount;
419 uTotalWeight += sst.uWeight;
420 }
421 }
422
423 rc = d->pProgress.createObject();
424 if (FAILED(rc)) throw rc;
425 rc = d->pProgress->init(p->getVirtualBox(),
426 static_cast<IMachine*>(d->pSrcMachine) /* aInitiator */,
427 Bstr(p->tr("Cloning Machine")).raw(),
428 true /* fCancellable */,
429 uCount,
430 uTotalWeight,
431 Bstr(p->tr("Initialize Cloning")).raw(),
432 1);
433 if (FAILED(rc)) throw rc;
434
435 int vrc = d->startWorker();
436
437 if (RT_FAILURE(vrc))
438 p->setError(VBOX_E_IPRT_ERROR, "Could not create machine clone thread (%Rrc)", vrc);
439 }
440 catch (HRESULT rc2)
441 {
442 rc = rc2;
443 }
444
445 if (SUCCEEDED(rc))
446 d->pProgress.queryInterfaceTo(pProgress);
447
448 return rc;
449}
450
451HRESULT MachineCloneVM::run()
452{
453 DPTR(MachineCloneVM);
454 ComObjPtr<Machine> &p = d->p;
455
456 AutoCaller autoCaller(p);
457 if (FAILED(autoCaller.rc())) return autoCaller.rc();
458
459 AutoReadLock srcLock(p COMMA_LOCKVAL_SRC_POS);
460 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
461
462 HRESULT rc = S_OK;
463
464 /*
465 * Todo:
466 * - What about log files?
467 */
468
469 /* Where should all the media go? */
470 Utf8Str strTrgSnapshotFolder;
471 Utf8Str strTrgMachineFolder = d->pTrgMachine->getSettingsFileFull();
472 strTrgMachineFolder.stripFilename();
473
474 RTCList< ComObjPtr<Medium> > newMedias; /* All created images */
475 RTCList<Utf8Str> newFiles; /* All extra created files (save states, ...) */
476 try
477 {
478 /* Copy all the configuration from this machine to an empty
479 * configuration dataset. */
480 settings::MachineConfigFile trgMCF = *d->pSrcMachine->mData->pMachineConfigFile;
481
482 /* Reset media registry. */
483 trgMCF.mediaRegistry.llHardDisks.clear();
484 /* If we got a valid snapshot id, replace the hardware/storage section
485 * with the stuff from the snapshot. */
486 settings::Snapshot sn;
487 if (!d->snapshotId.isEmpty())
488 sn = d->findSnapshot(&trgMCF, trgMCF.llFirstSnapshot, d->snapshotId);
489
490 if (d->mode == CloneMode_MachineState)
491 {
492 if (!sn.uuid.isEmpty())
493 {
494 trgMCF.hardwareMachine = sn.hardware;
495 trgMCF.storageMachine = sn.storage;
496 }
497
498 /* Remove any hint on snapshots. */
499 trgMCF.llFirstSnapshot.clear();
500 trgMCF.uuidCurrentSnapshot.clear();
501 }else
502 if ( d->mode == CloneMode_MachineAndChildStates
503 && !sn.uuid.isEmpty())
504 {
505 /* Copy the snapshot data to the current machine. */
506 trgMCF.hardwareMachine = sn.hardware;
507 trgMCF.storageMachine = sn.storage;
508
509 /* The snapshot will be the root one. */
510 trgMCF.uuidCurrentSnapshot = sn.uuid;
511 trgMCF.llFirstSnapshot.clear();
512 trgMCF.llFirstSnapshot.push_back(sn);
513 }
514
515 /* Generate new MAC addresses for all machines when not forbidden. */
516 if (!d->options.contains(CloneOptions_KeepAllMACs))
517 {
518 d->updateMACAddresses(trgMCF.hardwareMachine.llNetworkAdapters);
519 d->updateMACAddresses(trgMCF.llFirstSnapshot);
520 }
521
522 /* When the current snapshot folder is absolute we reset it to the
523 * default relative folder. */
524 if (RTPathStartsWithRoot(trgMCF.machineUserData.strSnapshotFolder.c_str()))
525 trgMCF.machineUserData.strSnapshotFolder = "Snapshots";
526 trgMCF.strStateFile = "";
527 /* Force writing of setting file. */
528 trgMCF.fCurrentStateModified = true;
529 /* Set the new name. */
530 const Utf8Str strOldVMName = trgMCF.machineUserData.strName;
531 trgMCF.machineUserData.strName = d->pTrgMachine->mUserData->s.strName;
532 trgMCF.uuid = d->pTrgMachine->mData->mUuid;
533
534 Bstr bstrSrcSnapshotFolder;
535 rc = d->pSrcMachine->COMGETTER(SnapshotFolder)(bstrSrcSnapshotFolder.asOutParam());
536 if (FAILED(rc)) throw rc;
537 /* The absolute name of the snapshot folder. */
538 strTrgSnapshotFolder = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, trgMCF.machineUserData.strSnapshotFolder.c_str());
539
540 /* Should we rename the disk names. */
541 bool fKeepDiskNames = d->options.contains(CloneOptions_KeepDiskNames);
542
543 /* We need to create a map with the already created medias. This is
544 * necessary, cause different snapshots could have the same
545 * parents/parent chain. If a medium is in this map already, it isn't
546 * cloned a second time, but simply used. */
547 typedef std::map<Utf8Str, ComObjPtr<Medium> > TStrMediumMap;
548 typedef std::pair<Utf8Str, ComObjPtr<Medium> > TStrMediumPair;
549 TStrMediumMap map;
550 size_t cDisks = 0;
551 for (size_t i = 0; i < d->llMedias.size(); ++i)
552 {
553 const MEDIUMTASKCHAIN &mtc = d->llMedias.at(i);
554 ComObjPtr<Medium> pNewParent;
555 for (size_t a = mtc.chain.size(); a > 0; --a)
556 {
557 const MEDIUMTASK &mt = mtc.chain.at(a - 1);
558 ComPtr<IMedium> pMedium = mt.pMedium;
559
560 Bstr bstrSrcName;
561 rc = pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
562 if (FAILED(rc)) throw rc;
563
564 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Cloning Disk '%ls' ..."), bstrSrcName.raw()).raw(), mt.uWeight);
565 if (FAILED(rc)) throw rc;
566
567 Bstr bstrSrcId;
568 rc = pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
569 if (FAILED(rc)) throw rc;
570
571 /* Is a clone already there? */
572 TStrMediumMap::iterator it = map.find(Utf8Str(bstrSrcId));
573 if (it != map.end())
574 pNewParent = it->second;
575 else
576 {
577 ComPtr<IMediumFormat> pSrcFormat;
578 rc = pMedium->COMGETTER(MediumFormat)(pSrcFormat.asOutParam());
579 ULONG uSrcCaps = 0;
580 rc = pSrcFormat->COMGETTER(Capabilities)(&uSrcCaps);
581 if (FAILED(rc)) throw rc;
582
583 /* Default format? */
584 Utf8Str strDefaultFormat;
585 p->mParent->getDefaultHardDiskFormat(strDefaultFormat);
586 Bstr bstrSrcFormat(strDefaultFormat);
587 ULONG srcVar = MediumVariant_Standard;
588 /* Is the source file based? */
589 if ((uSrcCaps & MediumFormatCapabilities_File) == MediumFormatCapabilities_File)
590 {
591 /* Yes, just use the source format. Otherwise the defaults
592 * will be used. */
593 rc = pMedium->COMGETTER(Format)(bstrSrcFormat.asOutParam());
594 if (FAILED(rc)) throw rc;
595 rc = pMedium->COMGETTER(Variant)(&srcVar);
596 if (FAILED(rc)) throw rc;
597 }
598
599 Guid newId;
600 newId.create();
601 Utf8Str strNewName(bstrSrcName);
602 if (!fKeepDiskNames)
603 {
604 /* If the old disk name was in {uuid} format we also
605 * want the new name in this format, but with the
606 * updated id of course. If the old disk was called
607 * like the VM name, we change it to the new VM name.
608 * For all other disks we rename them with this
609 * template: "new name-disk1.vdi". */
610 Utf8Str strSrcTest = Utf8Str(bstrSrcName).stripExt();
611 if (strSrcTest == strOldVMName)
612 strNewName = Utf8StrFmt("%s%s", trgMCF.machineUserData.strName.c_str(), RTPathExt(Utf8Str(bstrSrcName).c_str()));
613 else
614 if (strSrcTest.startsWith("{") &&
615 strSrcTest.endsWith("}"))
616 {
617 strSrcTest = strSrcTest.substr(1, strSrcTest.length() - 2);
618 if (isValidGuid(strSrcTest))
619 strNewName = Utf8StrFmt("%s%s", newId.toStringCurly().c_str(), RTPathExt(strNewName.c_str()));
620 }
621 else
622 strNewName = Utf8StrFmt("%s-disk%d%s", trgMCF.machineUserData.strName.c_str(), ++cDisks, RTPathExt(Utf8Str(bstrSrcName).c_str()));
623 }
624
625 /* Check if this medium comes from the snapshot folder, if
626 * so, put it there in the cloned machine as well.
627 * Otherwise it goes to the machine folder. */
628 Bstr bstrSrcPath;
629 Utf8Str strFile = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
630 rc = pMedium->COMGETTER(Location)(bstrSrcPath.asOutParam());
631 if (FAILED(rc)) throw rc;
632 if ( !bstrSrcPath.isEmpty()
633 && RTPathStartsWith(Utf8Str(bstrSrcPath).c_str(), Utf8Str(bstrSrcSnapshotFolder).c_str()))
634 strFile = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
635 else
636 strFile = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, strNewName.c_str());
637
638 /* Start creating the clone. */
639 ComObjPtr<Medium> pTarget;
640 rc = pTarget.createObject();
641 if (FAILED(rc)) throw rc;
642
643 rc = pTarget->init(p->mParent,
644 Utf8Str(bstrSrcFormat),
645 strFile,
646 Guid::Empty, /* empty media registry */
647 NULL /* llRegistriesThatNeedSaving */);
648 if (FAILED(rc)) throw rc;
649
650 /* Update the new uuid. */
651 pTarget->updateId(newId);
652
653 srcLock.release();
654 /* Do the disk cloning. */
655 ComPtr<IProgress> progress2;
656 rc = pMedium->CloneTo(pTarget,
657 srcVar,
658 pNewParent,
659 progress2.asOutParam());
660 if (FAILED(rc)) throw rc;
661
662 /* Wait until the asynchrony process has finished. */
663 rc = d->pProgress->WaitForAsyncProgressCompletion(progress2);
664 srcLock.acquire();
665 if (FAILED(rc)) throw rc;
666
667 /* Check the result of the asynchrony process. */
668 LONG iRc;
669 rc = progress2->COMGETTER(ResultCode)(&iRc);
670 if (FAILED(rc)) throw rc;
671 if (FAILED(iRc))
672 {
673 /* If the thread of the progress object has an error, then
674 * retrieve the error info from there, or it'll be lost. */
675 ProgressErrorInfo info(progress2);
676 throw p->setError(iRc, Utf8Str(info.getText()).c_str());
677 }
678 /* Remember created medias. */
679 newMedias.append(pTarget);
680 /* Get the medium type from the source and set it to the
681 * new medium. */
682 MediumType_T type;
683 rc = pMedium->COMGETTER(Type)(&type);
684 if (FAILED(rc)) throw rc;
685 rc = pTarget->COMSETTER(Type)(type);
686 if (FAILED(rc)) throw rc;
687 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pTarget));
688 /* Global register the new harddisk */
689 {
690 AutoWriteLock tlock(p->mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
691 rc = p->mParent->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
692 if (FAILED(rc)) return rc;
693 }
694 /* This medium becomes the parent of the next medium in the
695 * chain. */
696 pNewParent = pTarget;
697 }
698 }
699
700 /* Create diffs for the last image chain. */
701 if (mtc.fCreateDiffs)
702 {
703 Bstr bstrSrcId;
704 rc = pNewParent->COMGETTER(Id)(bstrSrcId.asOutParam());
705 if (FAILED(rc)) throw rc;
706 ComObjPtr<Medium> diff;
707 diff.createObject();
708 rc = diff->init(p->mParent,
709 pNewParent->getPreferredDiffFormat(),
710 Utf8StrFmt("%s%c", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER),
711 Guid::Empty, /* empty media registry */
712 NULL); /* pllRegistriesThatNeedSaving */
713 if (FAILED(rc)) throw rc;
714 MediumLockList *pMediumLockList(new MediumLockList());
715 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
716 true /* fMediumLockWrite */,
717 pNewParent,
718 *pMediumLockList);
719 if (FAILED(rc)) throw rc;
720 rc = pMediumLockList->Lock();
721 if (FAILED(rc)) throw rc;
722 rc = pNewParent->createDiffStorage(diff, MediumVariant_Standard,
723 pMediumLockList,
724 NULL /* aProgress */,
725 true /* aWait */,
726 NULL); // pllRegistriesThatNeedSaving
727 delete pMediumLockList;
728 if (FAILED(rc)) throw rc;
729 /* Remember created medias. */
730 newMedias.append(diff);
731 /* Global register the new harddisk */
732 {
733 AutoWriteLock tlock(p->mParent->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
734 rc = p->mParent->registerHardDisk(diff, NULL /* pllRegistriesThatNeedSaving */);
735 if (FAILED(rc)) return rc;
736 }
737 /* This medium becomes the parent of the next medium in the
738 * chain. */
739 pNewParent = diff;
740 }
741 Bstr bstrSrcId;
742 rc = mtc.chain.first().pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
743 if (FAILED(rc)) throw rc;
744 Bstr bstrTrgId;
745 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
746 if (FAILED(rc)) throw rc;
747 /* We have to patch the configuration, so it contains the new
748 * medium uuid instead of the old one. */
749 d->updateStorageLists(trgMCF.storageMachine.llStorageControllers, bstrSrcId, bstrTrgId);
750 d->updateSnapshotStorageLists(trgMCF.llFirstSnapshot, bstrSrcId, bstrTrgId);
751 }
752 /* Make sure all disks know of the new machine uuid. We do this last to
753 * be able to change the medium type above. */
754 for (size_t i = newMedias.size(); i > 0; --i)
755 {
756 ComObjPtr<Medium> &pMedium = newMedias.at(i - 1);
757 AutoCaller mac(pMedium);
758 if (FAILED(mac.rc())) throw mac.rc();
759 AutoWriteLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
760 pMedium->addRegistry(d->pTrgMachine->mData->mUuid, false /* fRecursive */);
761 }
762 /* Check if a snapshot folder is necessary and if so doesn't already
763 * exists. */
764 if ( !d->llSaveStateFiles.isEmpty()
765 && !RTDirExists(strTrgSnapshotFolder.c_str()))
766 {
767 int vrc = RTDirCreateFullPath(strTrgSnapshotFolder.c_str(), 0777);
768 if (RT_FAILURE(vrc))
769 throw p->setError(VBOX_E_IPRT_ERROR,
770 p->tr("Could not create snapshots folder '%s' (%Rrc)"), strTrgSnapshotFolder.c_str(), vrc);
771 }
772 /* Clone all save state files. */
773 for (size_t i = 0; i < d->llSaveStateFiles.size(); ++i)
774 {
775 SAVESTATETASK sst = d->llSaveStateFiles.at(i);
776 const Utf8Str &strTrgSaveState = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, RTPathFilename(sst.strSaveStateFile.c_str()));
777
778 /* Move to next sub-operation. */
779 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Copy save state file '%s' ..."), RTPathFilename(sst.strSaveStateFile.c_str())).raw(), sst.uWeight);
780 if (FAILED(rc)) throw rc;
781 /* Copy the file only if it was not copied already. */
782 if (!newFiles.contains(strTrgSaveState.c_str()))
783 {
784 int vrc = RTFileCopyEx(sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), 0, MachineCloneVMPrivate::copyStateFileProgress, &d->pProgress);
785 if (RT_FAILURE(vrc))
786 throw p->setError(VBOX_E_IPRT_ERROR,
787 p->tr("Could not copy state file '%s' to '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), vrc);
788 newFiles.append(strTrgSaveState);
789 }
790 /* Update the path in the configuration either for the current
791 * machine state or the snapshots. */
792 if (sst.snapshotUuid.isEmpty())
793 trgMCF.strStateFile = strTrgSaveState;
794 else
795 d->updateStateFile(trgMCF.llFirstSnapshot, sst.snapshotUuid, strTrgSaveState);
796 }
797
798 {
799 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Create Machine Clone '%s' ..."), trgMCF.machineUserData.strName.c_str()).raw(), 1);
800 if (FAILED(rc)) throw rc;
801 /* After modifying the new machine config, we can copy the stuff
802 * over to the new machine. The machine have to be mutable for
803 * this. */
804 rc = d->pTrgMachine->checkStateDependency(p->MutableStateDep);
805 if (FAILED(rc)) throw rc;
806 rc = d->pTrgMachine->loadMachineDataFromSettings(trgMCF,
807 &d->pTrgMachine->mData->mUuid);
808 if (FAILED(rc)) throw rc;
809 }
810
811 /* Now save the new configuration to disk. */
812 rc = d->pTrgMachine->SaveSettings();
813 if (FAILED(rc)) throw rc;
814 }
815 catch(HRESULT rc2)
816 {
817 rc = rc2;
818 }
819 catch (...)
820 {
821 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
822 }
823
824 MultiResult mrc(rc);
825 /* Cleanup on failure (CANCEL also) */
826 if (FAILED(rc))
827 {
828 int vrc = VINF_SUCCESS;
829 /* Delete all created files. */
830 for (size_t i = 0; i < newFiles.size(); ++i)
831 {
832 vrc = RTFileDelete(newFiles.at(i).c_str());
833 if (RT_FAILURE(vrc))
834 mrc = p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not delete file '%s' (%Rrc)"), newFiles.at(i).c_str(), vrc);
835 }
836 /* Delete all already created medias. (Reverse, cause there could be
837 * parent->child relations.) */
838 for (size_t i = newMedias.size(); i > 0; --i)
839 {
840 bool fFile = false;
841 Utf8Str strLoc;
842 ComObjPtr<Medium> &pMedium = newMedias.at(i - 1);
843 {
844 AutoCaller mac(pMedium);
845 if (FAILED(mac.rc())) { continue; mrc = mac.rc(); }
846 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
847 fFile = pMedium->isMediumFormatFile();
848 strLoc = pMedium->getLocationFull();
849 }
850 if (fFile)
851 {
852 vrc = RTFileDelete(strLoc.c_str());
853 if (RT_FAILURE(vrc))
854 mrc = p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not delete file '%s' (%Rrc)"), strLoc.c_str(), vrc);
855 }
856 }
857 /* Delete the snapshot folder when not empty. */
858 if (!strTrgSnapshotFolder.isEmpty())
859 RTDirRemove(strTrgSnapshotFolder.c_str());
860 /* Delete the machine folder when not empty. */
861 RTDirRemove(strTrgMachineFolder.c_str());
862 }
863
864 return mrc;
865}
866
867void MachineCloneVM::destroy()
868{
869 delete this;
870}
871
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