VirtualBox

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

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

Main;FE;CloneVM: add clone options; regenerate MACs of all network adapters dependent of the user option; docs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.2 KB
Line 
1/* $Id: MachineImplCloneVM.cpp 37531 2011-06-17 12:12:29Z 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 uint64_t uSize;
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 uint64_t cbSize;
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 there 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.uSize = lSize;
374 mtc.chain.append(mt);
375
376 /* Calculate progress data */
377 ++uCount;
378 uTotalWeight += lSize;
379
380 /* Query next parent. */
381 rc = pSrcMedium->COMGETTER(Parent)(pSrcMedium.asOutParam());
382 if (FAILED(rc)) throw rc;
383 };
384 d->llMedias.append(mtc);
385 }
386 Bstr bstrSrcSaveStatePath;
387 rc = machine->COMGETTER(StateFilePath)(bstrSrcSaveStatePath.asOutParam());
388 if (FAILED(rc)) throw rc;
389 if (!bstrSrcSaveStatePath.isEmpty())
390 {
391 SAVESTATETASK sst;
392 sst.snapshotUuid = machine->getSnapshotId();
393 sst.strSaveStateFile = bstrSrcSaveStatePath;
394 int vrc = RTFileQuerySize(sst.strSaveStateFile.c_str(), &sst.cbSize);
395 if (RT_FAILURE(vrc))
396 throw p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not query file size of '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), vrc);
397 d->llSaveStateFiles.append(sst);
398 ++uCount;
399 uTotalWeight += sst.cbSize;
400 }
401 }
402
403 rc = d->pProgress.createObject();
404 if (FAILED(rc)) throw rc;
405 rc = d->pProgress->init(p->getVirtualBox(),
406 static_cast<IMachine*>(d->pSrcMachine) /* aInitiator */,
407 Bstr(p->tr("Cloning Machine")).raw(),
408 true /* fCancellable */,
409 uCount,
410 uTotalWeight,
411 Bstr(p->tr("Initialize Cloning")).raw(),
412 1);
413 if (FAILED(rc)) throw rc;
414
415 int vrc = d->startWorker();
416
417 if (RT_FAILURE(vrc))
418 p->setError(VBOX_E_IPRT_ERROR, "Could not create machine clone thread (%Rrc)", vrc);
419 }
420 catch (HRESULT rc2)
421 {
422 rc = rc2;
423 }
424
425 if (SUCCEEDED(rc))
426 d->pProgress.queryInterfaceTo(pProgress);
427
428 return rc;
429}
430
431HRESULT MachineCloneVM::run()
432{
433 DPTR(MachineCloneVM);
434 ComObjPtr<Machine> &p = d->p;
435
436 AutoCaller autoCaller(p);
437 if (FAILED(autoCaller.rc())) return autoCaller.rc();
438
439 AutoReadLock srcLock(p COMMA_LOCKVAL_SRC_POS);
440 AutoWriteLock trgLock(d->pTrgMachine COMMA_LOCKVAL_SRC_POS);
441
442 MultiResult rc = S_OK;
443
444 /*
445 * Todo:
446 * - Snapshot diffs (can) have the uuid as name. After cloning this isn't
447 * right anymore. Is it worth to change to the new uuid? Or should the
448 * cloned disks called exactly as the original one or should all new disks
449 * get a new name with the new VM name in it.
450 * - What about log files?
451 */
452
453 /* Where should all the media go? */
454 Utf8Str strTrgSnapshotFolder;
455 Utf8Str strTrgMachineFolder = d->pTrgMachine->getSettingsFileFull();
456 strTrgMachineFolder.stripFilename();
457
458 RTCList< ComObjPtr<Medium> > newMedias; /* All created images */
459 RTCList<Utf8Str> newFiles; /* All extra created files (save states, ...) */
460 try
461 {
462 /* Copy all the configuration from this machine to an empty
463 * configuration dataset. */
464 settings::MachineConfigFile trgMCF = *d->pSrcMachine->mData->pMachineConfigFile;
465
466 /* Reset media registry. */
467 trgMCF.mediaRegistry.llHardDisks.clear();
468 /* If we got a valid snapshot id, replace the hardware/storage section
469 * with the stuff from the snapshot. */
470 settings::Snapshot sn;
471 if (!d->snapshotId.isEmpty())
472 sn = d->findSnapshot(&trgMCF, trgMCF.llFirstSnapshot, d->snapshotId);
473
474 if (d->mode == CloneMode_MachineState)
475 {
476 if (!sn.uuid.isEmpty())
477 {
478 trgMCF.hardwareMachine = sn.hardware;
479 trgMCF.storageMachine = sn.storage;
480 }
481
482 /* Remove any hint on snapshots. */
483 trgMCF.llFirstSnapshot.clear();
484 trgMCF.uuidCurrentSnapshot.clear();
485 }else
486 if ( d->mode == CloneMode_MachineAndChildStates
487 && !sn.uuid.isEmpty())
488 {
489 /* Copy the snapshot data to the current machine. */
490 trgMCF.hardwareMachine = sn.hardware;
491 trgMCF.storageMachine = sn.storage;
492
493 /* The snapshot will be the root one. */
494 trgMCF.uuidCurrentSnapshot = sn.uuid;
495 trgMCF.llFirstSnapshot.clear();
496 trgMCF.llFirstSnapshot.push_back(sn);
497 }
498
499 /* Generate new MAC addresses for all machines when not forbidden. */
500 if (!d->options.contains(CloneOptions_KeepAllMACs))
501 {
502 d->updateMACAddresses(trgMCF.hardwareMachine.llNetworkAdapters);
503 d->updateMACAddresses(trgMCF.llFirstSnapshot);
504 }
505
506 /* When the current snapshot folder is absolute we reset it to the
507 * default relative folder. */
508 if (RTPathStartsWithRoot(trgMCF.machineUserData.strSnapshotFolder.c_str()))
509 trgMCF.machineUserData.strSnapshotFolder = "Snapshots";
510 trgMCF.strStateFile = "";
511 /* Force writing of setting file. */
512 trgMCF.fCurrentStateModified = true;
513 /* Set the new name. */
514 trgMCF.machineUserData.strName = d->pTrgMachine->mUserData->s.strName;
515 trgMCF.uuid = d->pTrgMachine->mData->mUuid;
516
517 Bstr bstrSrcSnapshotFolder;
518 rc = d->pSrcMachine->COMGETTER(SnapshotFolder)(bstrSrcSnapshotFolder.asOutParam());
519 if (FAILED(rc)) throw rc;
520 /* The absolute name of the snapshot folder. */
521 strTrgSnapshotFolder = Utf8StrFmt("%s%c%s", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, trgMCF.machineUserData.strSnapshotFolder.c_str());
522
523 /* We need to create a map with the already created medias. This is
524 * necessary, cause different snapshots could have the same
525 * parents/parent chain. If a medium is in this map already, it isn't
526 * cloned a second time, but simply used. */
527 typedef std::map<Utf8Str, ComObjPtr<Medium> > TStrMediumMap;
528 typedef std::pair<Utf8Str, ComObjPtr<Medium> > TStrMediumPair;
529 TStrMediumMap map;
530 for (size_t i = 0; i < d->llMedias.size(); ++i)
531 {
532 const MEDIUMTASKCHAIN &mtc = d->llMedias.at(i);
533 ComObjPtr<Medium> pNewParent;
534 for (size_t a = mtc.chain.size(); a > 0; --a)
535 {
536 const MEDIUMTASK &mt = mtc.chain.at(a - 1);
537 ComPtr<IMedium> pMedium = mt.pMedium;
538
539 Bstr bstrSrcName;
540 rc = pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
541 if (FAILED(rc)) throw rc;
542
543 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Cloning Disk '%ls' ..."), bstrSrcName.raw()).raw(), mt.uSize);
544 if (FAILED(rc)) throw rc;
545
546 Bstr bstrSrcId;
547 rc = pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
548 if (FAILED(rc)) throw rc;
549
550 /* Is a clone already there? */
551 TStrMediumMap::iterator it = map.find(Utf8Str(bstrSrcId));
552 if (it != map.end())
553 pNewParent = it->second;
554 else
555 {
556 ComPtr<IMediumFormat> pSrcFormat;
557 rc = pMedium->COMGETTER(MediumFormat)(pSrcFormat.asOutParam());
558 ULONG uSrcCaps = 0;
559 rc = pSrcFormat->COMGETTER(Capabilities)(&uSrcCaps);
560 if (FAILED(rc)) throw rc;
561
562 Bstr bstrSrcFormat = "VDI";
563 ULONG srcVar = MediumVariant_Standard;
564 /* Is the source file based? */
565 if ((uSrcCaps & MediumFormatCapabilities_File) == MediumFormatCapabilities_File)
566 {
567 /* Yes, just use the source format. Otherwise the defaults
568 * will be used. */
569 rc = pMedium->COMGETTER(Format)(bstrSrcFormat.asOutParam());
570 if (FAILED(rc)) throw rc;
571 rc = pMedium->COMGETTER(Variant)(&srcVar);
572 if (FAILED(rc)) throw rc;
573 }
574
575 /* Start creating the clone. */
576 ComObjPtr<Medium> pTarget;
577 rc = pTarget.createObject();
578 if (FAILED(rc)) throw rc;
579
580 /* Check if this medium comes from the snapshot folder, if
581 * so, put it there in the cloned machine as well.
582 * Otherwise it goes to the machine folder. */
583 Utf8Str strFile = Utf8StrFmt("%s%c%lS", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, bstrSrcName.raw());
584 Bstr bstrSrcPath;
585 rc = pMedium->COMGETTER(Location)(bstrSrcPath.asOutParam());
586 if (FAILED(rc)) throw rc;
587 if ( !bstrSrcPath.isEmpty()
588 && RTPathStartsWith(Utf8Str(bstrSrcPath).c_str(), Utf8Str(bstrSrcSnapshotFolder).c_str()))
589 strFile = Utf8StrFmt("%s%c%lS", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, bstrSrcName.raw());
590 else
591 strFile = Utf8StrFmt("%s%c%lS", strTrgMachineFolder.c_str(), RTPATH_DELIMITER, bstrSrcName.raw());
592
593 rc = pTarget->init(p->mParent,
594 Utf8Str(bstrSrcFormat),
595 strFile,
596 d->pTrgMachine->mData->mUuid, /* media registry */
597 NULL /* llRegistriesThatNeedSaving */);
598 if (FAILED(rc)) throw rc;
599
600 /* Do the disk cloning. */
601 ComPtr<IProgress> progress2;
602 rc = pMedium->CloneTo(pTarget,
603 srcVar,
604 pNewParent,
605 progress2.asOutParam());
606 if (FAILED(rc)) throw rc;
607
608 /* Wait until the asynchrony process has finished. */
609 srcLock.release();
610 rc = d->pProgress->WaitForAsyncProgressCompletion(progress2);
611 srcLock.acquire();
612 if (FAILED(rc)) throw rc;
613
614 /* Check the result of the asynchrony process. */
615 LONG iRc;
616 rc = progress2->COMGETTER(ResultCode)(&iRc);
617 if (FAILED(rc)) throw rc;
618 if (FAILED(iRc))
619 {
620 /* If the thread of the progress object has an error, then
621 * retrieve the error info from there, or it'll be lost. */
622 ProgressErrorInfo info(progress2);
623 throw p->setError(iRc, Utf8Str(info.getText()).c_str());
624 }
625
626 map.insert(TStrMediumPair(Utf8Str(bstrSrcId), pTarget));
627
628 /* Remember created medias. */
629 newMedias.append(pTarget);
630 /* This medium becomes the parent of the next medium in the
631 * chain. */
632 pNewParent = pTarget;
633 }
634 }
635
636 /* Create diffs for the last image chain. */
637 if (mtc.fCreateDiffs)
638 {
639 Bstr bstrSrcId;
640 rc = pNewParent->COMGETTER(Id)(bstrSrcId.asOutParam());
641 if (FAILED(rc)) throw rc;
642 GuidList *pllRegistriesThatNeedSaving;
643 ComObjPtr<Medium> diff;
644 diff.createObject();
645 rc = diff->init(p->mParent,
646 pNewParent->getPreferredDiffFormat(),
647 Utf8StrFmt("%s%c", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER),
648 d->pTrgMachine->mData->mUuid,
649 NULL); // pllRegistriesThatNeedSaving
650 if (FAILED(rc)) throw rc;
651 MediumLockList *pMediumLockList(new MediumLockList()); /* todo: deleteeeeeeeee */
652 rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
653 true /* fMediumLockWrite */,
654 pNewParent,
655 *pMediumLockList);
656 if (FAILED(rc)) throw rc;
657 rc = pMediumLockList->Lock();
658 if (FAILED(rc)) throw rc;
659 rc = pNewParent->createDiffStorage(diff, MediumVariant_Standard,
660 pMediumLockList,
661 NULL /* aProgress */,
662 true /* aWait */,
663 NULL); // pllRegistriesThatNeedSaving
664 delete pMediumLockList;
665 if (FAILED(rc)) throw rc;
666 pNewParent = diff;
667 newMedias.append(diff);
668 }
669 Bstr bstrSrcId;
670 rc = mtc.chain.first().pMedium->COMGETTER(Id)(bstrSrcId.asOutParam());
671 if (FAILED(rc)) throw rc;
672 Bstr bstrTrgId;
673 rc = pNewParent->COMGETTER(Id)(bstrTrgId.asOutParam());
674 if (FAILED(rc)) throw rc;
675 /* We have to patch the configuration, so it contains the new
676 * medium uuid instead of the old one. */
677 d->updateStorageLists(trgMCF.storageMachine.llStorageControllers, bstrSrcId, bstrTrgId);
678 d->updateSnapshotStorageLists(trgMCF.llFirstSnapshot, bstrSrcId, bstrTrgId);
679 }
680 /* Clone all save state files. */
681 for (size_t i = 0; i < d->llSaveStateFiles.size(); ++i)
682 {
683 SAVESTATETASK sst = d->llSaveStateFiles.at(i);
684 const Utf8Str &strTrgSaveState = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER, RTPathFilename(sst.strSaveStateFile.c_str()));
685
686 /* Move to next sub-operation. */
687 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Copy save state file '%s' ..."), RTPathFilename(sst.strSaveStateFile.c_str())).raw(), sst.cbSize);
688 if (FAILED(rc)) throw rc;
689 /* Copy the file only if it was not copied already. */
690 if (!newFiles.contains(strTrgSaveState.c_str()))
691 {
692 int vrc = RTFileCopyEx(sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), 0, MachineCloneVMPrivate::copyStateFileProgress, &d->pProgress);
693 if (RT_FAILURE(vrc))
694 throw p->setError(VBOX_E_IPRT_ERROR,
695 p->tr("Could not copy state file '%s' to '%s' (%Rrc)"), sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), vrc);
696 newFiles.append(strTrgSaveState);
697 }
698 /* Update the path in the configuration either for the current
699 * machine state or the snapshots. */
700 if (sst.snapshotUuid.isEmpty())
701 trgMCF.strStateFile = strTrgSaveState;
702 else
703 d->updateStateFile(trgMCF.llFirstSnapshot, sst.snapshotUuid, strTrgSaveState);
704 }
705
706 if (false)
707// if (!d->pOldMachineState.isNull())
708 {
709 SafeIfaceArray<IMediumAttachment> sfaAttachments;
710 rc = d->pOldMachineState->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
711 if (FAILED(rc)) throw rc;
712 for (size_t a = 0; a < sfaAttachments.size(); ++a)
713 {
714 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
715 DeviceType_T type;
716 rc = pAtt->COMGETTER(Type)(&type);
717 if (FAILED(rc)) throw rc;
718
719 /* Only harddisk's are of interest. */
720 if (type != DeviceType_HardDisk)
721 continue;
722
723 /* Valid medium attached? */
724 ComPtr<IMedium> pSrcMedium;
725 rc = pAtt->COMGETTER(Medium)(pSrcMedium.asOutParam());
726 if (FAILED(rc)) throw rc;
727 if (pSrcMedium.isNull())
728 continue;
729
730// ComObjPtr<Medium> pMedium = static_cast<Medium*>((IMedium*)pSrcMedium);
731// ComObjPtr<Medium> diff;
732// diff.createObject();
733 // store this diff in the same registry as the parent
734// Guid uuidRegistryParent;
735// if (!medium->getFirstRegistryMachineId(uuidRegistryParent))
736// {
737 // parent image has no registry: this can happen if we're attaching a new immutable
738 // image that has not yet been attached (medium then points to the base and we're
739 // creating the diff image for the immutable, and the parent is not yet registered);
740 // put the parent in the machine registry then
741// addMediumToRegistry(medium, llRegistriesThatNeedSaving, &uuidRegistryParent);
742// }
743// rc = diff->init(mParent,
744// pMedium->getPreferredDiffFormat(),
745// strFullSnapshotFolder.append(RTPATH_SLASH_STR),
746// uuidRegistryParent,
747// pllRegistriesThatNeedSaving);
748// if (FAILED(rc)) throw rc;
749//
750// rc = pMedium->createDiffStorage(diff, MediumVariant_Standard,
751// pMediumLockList,
752// NULL /* aProgress */,
753// true /* aWait */,
754// pllRegistriesThatNeedSaving);
755 }
756 }
757
758 {
759 rc = d->pProgress->SetNextOperation(BstrFmt(p->tr("Create Machine Clone '%s' ..."), trgMCF.machineUserData.strName.c_str()).raw(), 1);
760 if (FAILED(rc)) throw rc;
761 /* After modifying the new machine config, we can copy the stuff
762 * over to the new machine. The machine have to be mutable for
763 * this. */
764 rc = d->pTrgMachine->checkStateDependency(p->MutableStateDep);
765 if (FAILED(rc)) throw rc;
766 rc = d->pTrgMachine->loadMachineDataFromSettings(trgMCF,
767 &d->pTrgMachine->mData->mUuid);
768 if (FAILED(rc)) throw rc;
769 }
770
771 /* The medias are created before the machine was there. We have to make
772 * sure the new medias know of there new parent or we get in trouble
773 * when the media registry is saved for this VM, especially in case of
774 * difference image chain's. See VirtualBox::saveMediaRegistry.*/
775// for (size_t i = 0; i < newBaseMedias.size(); ++i)
776// {
777// rc = newBaseMedias.at(i)->addRegistry(d->pTrgMachine->mData->mUuid, true /* fRecursive */);
778// if (FAILED(rc)) throw rc;
779// }
780
781 /* Now save the new configuration to disk. */
782 rc = d->pTrgMachine->SaveSettings();
783 if (FAILED(rc)) throw rc;
784 }
785 catch(HRESULT rc2)
786 {
787 rc = rc2;
788 }
789 catch (...)
790 {
791 rc = VirtualBox::handleUnexpectedExceptions(RT_SRC_POS);
792 }
793
794 /* Cleanup on failure (CANCEL also) */
795 if (FAILED(rc))
796 {
797 int vrc = VINF_SUCCESS;
798 /* Delete all created files. */
799 for (size_t i = 0; i < newFiles.size(); ++i)
800 {
801 vrc = RTFileDelete(newFiles.at(i).c_str());
802 if (RT_FAILURE(vrc))
803 rc = p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not delete file '%s' (%Rrc)"), newFiles.at(i).c_str(), vrc);
804 }
805 /* Delete all already created medias. (Reverse, cause there could be
806 * parent->child relations.) */
807 for (size_t i = newMedias.size(); i > 0; --i)
808 {
809 bool fFile = false;
810 Utf8Str strLoc;
811 ComObjPtr<Medium> &pMedium = newMedias.at(i - 1);
812 {
813 AutoCaller mac(pMedium);
814 if (FAILED(mac.rc())) { continue; rc = mac.rc(); }
815 AutoReadLock mlock(pMedium COMMA_LOCKVAL_SRC_POS);
816 fFile = pMedium->isMediumFormatFile();
817 strLoc = pMedium->getLocationFull();
818 }
819 if (fFile)
820 {
821 vrc = RTFileDelete(strLoc.c_str());
822 if (RT_FAILURE(vrc))
823 rc = p->setError(VBOX_E_IPRT_ERROR, p->tr("Could not delete file '%s' (%Rrc)"), strLoc.c_str(), vrc);
824 }
825 }
826 /* Delete the snapshot folder when not empty. */
827 if (!strTrgSnapshotFolder.isEmpty())
828 RTDirRemove(strTrgSnapshotFolder.c_str());
829 /* Delete the machine folder when not empty. */
830 RTDirRemove(strTrgMachineFolder.c_str());
831 }
832
833 return rc;
834}
835
836void MachineCloneVM::destroy()
837{
838 delete this;
839}
840
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