VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/MachineImplMoveVM.cpp@ 71253

Last change on this file since 71253 was 71197, checked in by vboxsync, 7 years ago

bugref:8345. The trailing blanks were removed.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 56.1 KB
Line 
1/* $Id: MachineImplMoveVM.cpp 71197 2018-03-05 10:55:30Z vboxsync $ */
2/** @file
3 * Implementation of MachineMoveVM
4 */
5
6/*
7 * Copyright (C) 2011-2017 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#include <iprt/fs.h>
18#include <iprt/dir.h>
19#include <iprt/file.h>
20#include <iprt/path.h>
21#include <iprt/cpp/utils.h>
22#include <iprt/stream.h>
23
24#include "MachineImplMoveVM.h"
25#include "MediumFormatImpl.h"
26#include "VirtualBoxImpl.h"
27#include "Logging.h"
28
29/* This variable is global and used in the different places so it must be cleared each time before usage to avoid failure */
30std::vector< ComObjPtr<Machine> > machineList;
31
32typedef std::multimap<Utf8Str, Utf8Str> list_t;
33typedef std::multimap<Utf8Str, Utf8Str>::const_iterator cit_t;
34typedef std::multimap<Utf8Str, Utf8Str>::iterator it_t;
35typedef std::pair <std::multimap<Utf8Str, Utf8Str>::iterator, std::multimap<Utf8Str, Utf8Str>::iterator> rangeRes_t;
36
37struct fileList_t
38{
39 HRESULT add(const Utf8Str& folder, const Utf8Str& file)
40 {
41 HRESULT rc = S_OK;
42 m_list.insert(std::make_pair(folder, file));
43 return rc;
44 }
45
46 HRESULT add(const Utf8Str& fullPath)
47 {
48 HRESULT rc = S_OK;
49 Utf8Str folder = fullPath;
50 folder.stripFilename();
51 Utf8Str filename = fullPath;
52 filename.stripPath();
53 m_list.insert(std::make_pair(folder, filename));
54 return rc;
55 }
56
57 HRESULT removeFileFromList(const Utf8Str& fullPath)
58 {
59 HRESULT rc = S_OK;
60 Utf8Str folder = fullPath;
61 folder.stripFilename();
62 Utf8Str filename = fullPath;
63 filename.stripPath();
64 rangeRes_t res = m_list.equal_range(folder);
65 for (it_t it=res.first; it!=res.second; ++it)
66 {
67 if (it->second.equals(filename))
68 m_list.erase(it);
69 }
70 return rc;
71 }
72
73 HRESULT removeFileFromList(const Utf8Str& path, const Utf8Str& fileName)
74 {
75 HRESULT rc = S_OK;
76 rangeRes_t res = m_list.equal_range(path);
77 for (it_t it=res.first; it!=res.second; ++it)
78 {
79 if (it->second.equals(fileName))
80 m_list.erase(it);
81 }
82 return rc;
83 }
84
85 HRESULT removeFolderFromList(const Utf8Str& path)
86 {
87 HRESULT rc = S_OK;
88 m_list.erase(path);
89 return rc;
90 }
91
92 rangeRes_t getFilesInRange(const Utf8Str& path)
93 {
94 rangeRes_t res;
95 res = m_list.equal_range(path);
96 return res;
97 }
98
99 std::list<Utf8Str> getFilesInList(const Utf8Str& path)
100 {
101 std::list<Utf8Str> list_;
102 rangeRes_t res = m_list.equal_range(path);
103 for (it_t it=res.first; it!=res.second; ++it)
104 list_.push_back(it->second);
105 return list_;
106 }
107
108
109 list_t m_list;
110
111};
112
113HRESULT MachineMoveVM::init()
114{
115 HRESULT rc = S_OK;
116
117 Utf8Str strTargetFolder;
118 /* adding a trailing slash if it's needed */
119 {
120 size_t len = m_targetPath.length() + 2;
121 if (len >=RTPATH_MAX)
122 {
123 throw m_pMachine->setError(VBOX_E_IPRT_ERROR,
124 m_pMachine->tr(" The destination path isn't correct. "
125 "The length of path exceeded the maximum value."));
126 }
127
128 char* path = new char [len];
129 RTStrCopy(path, len, m_targetPath.c_str());
130 RTPathEnsureTrailingSeparator(path, len);
131 strTargetFolder = m_targetPath = path;
132 delete path;
133 }
134
135 /*
136 * We have a mode which user is able to request
137 * basic mode:
138 * - The images which are solely attached to the VM
139 * and located in the original VM folder will be moved.
140 *
141 * Comment: in the future some other modes can be added.
142 */
143
144 try
145 {
146 Utf8Str info;
147 int vrc = 0;
148
149 RTFOFF cbTotal = 0;
150 RTFOFF cbFree = 0;
151 uint32_t cbBlock = 0;
152 uint32_t cbSector = 0;
153
154 vrc = RTFsQuerySizes(strTargetFolder.c_str(), &cbTotal, &cbFree, &cbBlock, &cbSector);
155 if (FAILED(vrc))
156 {
157 RTPrintf("strTargetFolder is %s\n", strTargetFolder.c_str());
158 rc = m_pMachine->setError(E_FAIL,
159 m_pMachine->tr("Unable to move machine. Can't get the destination storage size (%s)"),
160 strTargetFolder.c_str());
161 throw rc;
162 }
163
164 long long totalFreeSpace = cbFree;
165 long long totalSpace = cbTotal;
166 info = Utf8StrFmt("blocks: total %lld, free %u ", cbTotal, cbFree);
167 LogRelFunc(("%s \n", info.c_str()));
168 LogRelFunc(("total space (Kb) %lld (Mb) %lld (Gb) %lld\n",
169 totalSpace/1024, totalSpace/(1024*1024), totalSpace/(1024*1024*1024)));
170 LogRelFunc(("total free space (Kb) %lld (Mb) %lld (Gb) %lld\n",
171 totalFreeSpace/1024, totalFreeSpace/(1024*1024), totalFreeSpace/(1024*1024*1024)));
172
173 RTFSPROPERTIES properties;
174 vrc = RTFsQueryProperties(strTargetFolder.c_str(), &properties);
175 if (FAILED(vrc)) throw vrc;
176 info = Utf8StrFmt("disk properties:\n"
177 "remote: %s \n"
178 "read only: %s \n"
179 "compressed: %s \n",
180 properties.fRemote == true ? "true":"false",
181 properties.fReadOnly == true ? "true":"false",
182 properties.fCompressed == true ? "true":"false");
183
184 LogRelFunc(("%s \n", info.c_str()));
185
186 /* Get the original VM path */
187 Utf8Str strSettingsFilePath;
188 Bstr bstr_settingsFilePath;
189 m_pMachine->COMGETTER(SettingsFilePath)(bstr_settingsFilePath.asOutParam());
190 strSettingsFilePath = bstr_settingsFilePath;
191 strSettingsFilePath.stripFilename();
192
193 vmFolders.insert(std::make_pair(VBox_SettingFolder, strSettingsFilePath));
194
195 /* Collect all files from the VM's folder */
196 fileList_t fullFileList;
197 rc = getFilesList(strSettingsFilePath, fullFileList);
198 if (FAILED(rc)) throw rc;
199
200 /*
201 * Collect all known folders used by the VM:
202 * - log folder;
203 * - state folder;
204 * - snapshot folder.
205 */
206 Utf8Str strLogFolder;
207 Bstr bstr_logFolder;
208 m_pMachine->COMGETTER(LogFolder)(bstr_logFolder.asOutParam());
209 strLogFolder = bstr_logFolder;
210 if ( m_type.equals("basic")
211 && strLogFolder.contains(strSettingsFilePath))
212 {
213 vmFolders.insert(std::make_pair(VBox_LogFolder, strLogFolder));
214 }
215
216 Utf8Str strStateFilePath;
217 Bstr bstr_stateFilePath;
218 MachineState_T machineState;
219 rc = m_pMachine->COMGETTER(State)(&machineState);
220 if (FAILED(rc)) throw rc;
221 else if (machineState == MachineState_Saved)
222 {
223 m_pMachine->COMGETTER(StateFilePath)(bstr_stateFilePath.asOutParam());
224 strStateFilePath = bstr_stateFilePath;
225 strStateFilePath.stripFilename();
226 if ( m_type.equals("basic")
227 && strStateFilePath.contains(strSettingsFilePath))
228 vmFolders.insert(std::make_pair(VBox_StateFolder, strStateFilePath));//Utf8Str(bstr_stateFilePath)));
229 }
230
231 Utf8Str strSnapshotFolder;
232 Bstr bstr_snapshotFolder;
233 m_pMachine->COMGETTER(SnapshotFolder)(bstr_snapshotFolder.asOutParam());
234 strSnapshotFolder = bstr_snapshotFolder;
235 if ( m_type.equals("basic")
236 && strSnapshotFolder.contains(strSettingsFilePath))
237 vmFolders.insert(std::make_pair(VBox_SnapshotFolder, strSnapshotFolder));
238
239 if (m_pMachine->i_isSnapshotMachine())
240 {
241 Bstr bstrSrcMachineId;
242 rc = m_pMachine->COMGETTER(Id)(bstrSrcMachineId.asOutParam());
243 if (FAILED(rc)) throw rc;
244 ComPtr<IMachine> newSrcMachine;
245 rc = m_pMachine->i_getVirtualBox()->FindMachine(bstrSrcMachineId.raw(), newSrcMachine.asOutParam());
246 if (FAILED(rc)) throw rc;
247 }
248
249 /* Add the current machine and all snapshot machines below this machine
250 * in a list for further processing.
251 */
252
253 long long neededFreeSpace = 0;
254
255 /* Actual file list */
256 fileList_t actualFileList;
257 Utf8Str strTargetImageName;
258
259 /* Global variable (defined at the beginning of file), so clear it before usage */
260 machineList.clear();
261 machineList.push_back(m_pMachine);
262
263 {
264 ULONG cSnapshots = 0;
265 rc = m_pMachine->COMGETTER(SnapshotCount)(&cSnapshots);
266 if (FAILED(rc)) throw rc;
267 if (cSnapshots > 0)
268 {
269 Utf8Str id;
270 if (m_pMachine->i_isSnapshotMachine())
271 id = m_pMachine->i_getSnapshotId().toString();
272 ComPtr<ISnapshot> pSnapshot;
273 rc = m_pMachine->FindSnapshot(Bstr(id).raw(), pSnapshot.asOutParam());
274 if (FAILED(rc)) throw rc;
275 rc = createMachineList(pSnapshot, machineList);
276 if (FAILED(rc)) throw rc;
277 }
278 }
279
280 ULONG uCount = 1;//looks like it should be initialized by 1. See assertion in the Progress::setNextOperation()
281 ULONG uTotalWeight = 1;
282
283 /* The lists llMedias and llSaveStateFiles are filled in the queryMediasForAllStates() */
284 queryMediasForAllStates(machineList);
285
286 {
287 uint64_t totalMediumsSize = 0;
288
289 for (size_t i = 0; i < llMedias.size(); ++i)
290 {
291 LONG64 cbSize = 0;
292 MEDIUMTASKCHAIN &mtc = llMedias.at(i);
293 for (size_t a = mtc.chain.size(); a > 0; --a)
294 {
295 Bstr bstrLocation;
296 Utf8Str strLocation;
297 Utf8Str name = mtc.chain[a - 1].strBaseName;
298 ComPtr<IMedium> plMedium = mtc.chain[a - 1].pMedium;
299 rc = plMedium->COMGETTER(Location)(bstrLocation.asOutParam());
300 if (FAILED(rc)) throw rc;
301 strLocation = bstrLocation;
302
303 /*if an image is located in the actual VM folder it will be added to the actual list */
304 if (strLocation.contains(strSettingsFilePath))
305 {
306 rc = plMedium->COMGETTER(Size)(&cbSize);
307 if (FAILED(rc)) throw rc;
308
309 std::pair<std::map<Utf8Str, MEDIUMTASK>::iterator,bool> ret;
310 ret = finalMediumsMap.insert(std::make_pair(name, mtc.chain[a - 1]));
311 if (ret.second == true)
312 {
313 /* Calculate progress data */
314 ++uCount;
315 uTotalWeight += mtc.chain[a - 1].uWeight;
316 totalMediumsSize += cbSize;
317 LogRelFunc(("Image %s was added into the moved list\n", name.c_str()));
318 }
319 }
320 }
321 }
322
323 LogRelFunc(("Total Size of images is %lld bytes\n", totalMediumsSize));
324 neededFreeSpace += totalMediumsSize;
325 }
326
327 /* Prepare data for moving ".sav" files */
328 {
329 uint64_t totalStateSize = 0;
330
331 for (size_t i = 0; i < llSaveStateFiles.size(); ++i)
332 {
333 uint64_t cbFile = 0;
334 SAVESTATETASK &sst = llSaveStateFiles.at(i);
335
336 Utf8Str name = sst.strSaveStateFile;
337 /*if a state file is located in the actual VM folder it will be added to the actual list */
338 if (name.contains(strSettingsFilePath))
339 {
340 vrc = RTFileQuerySize(name.c_str(), &cbFile);
341 if (RT_SUCCESS(vrc))
342 {
343 std::pair<std::map<Utf8Str, SAVESTATETASK>::iterator,bool> ret;
344 ret = finalSaveStateFilesMap.insert(std::make_pair(name, sst));
345 if (ret.second == true)
346 {
347 totalStateSize += cbFile;
348 ++uCount;
349 uTotalWeight += sst.uWeight;
350 LogRelFunc(("The state file %s was added into the moved list\n", name.c_str()));
351 }
352 }
353 else
354 LogRelFunc(("The state file %s wasn't added into the moved list. Couldn't get the file size.\n",
355 name.c_str()));
356 }
357 }
358
359 neededFreeSpace += totalStateSize;
360 }
361
362 /* Prepare data for moving the log files */
363 {
364 Utf8Str strFolder = vmFolders[VBox_LogFolder];
365
366 if (RTPathExists(strFolder.c_str()))
367 {
368 uint64_t totalLogSize = 0;
369 rc = getFolderSize(strFolder, totalLogSize);
370 if (SUCCEEDED(rc))
371 {
372 neededFreeSpace += totalLogSize;
373 if (totalFreeSpace - neededFreeSpace <= 1024*1024)
374 {
375 throw VERR_OUT_OF_RESOURCES;//less than 1Mb free space on the target location
376 }
377
378 fileList_t filesList;
379 getFilesList(strFolder, filesList);
380 cit_t it = filesList.m_list.begin();
381 while(it != filesList.m_list.end())
382 {
383 Utf8Str strFile = it->first.c_str();
384 strFile.append(RTPATH_DELIMITER).append(it->second.c_str());
385
386 uint64_t cbFile = 0;
387 vrc = RTFileQuerySize(strFile.c_str(), &cbFile);
388 if (RT_SUCCESS(vrc))
389 {
390 uCount += 1;
391 uTotalWeight += (ULONG)((cbFile + _1M - 1) / _1M);
392 actualFileList.add(strFile);
393 LogRelFunc(("The log file %s added into the moved list\n", strFile.c_str()));
394 }
395 else
396 LogRelFunc(("The log file %s wasn't added into the moved list. Couldn't get the file size."
397 "\n", strFile.c_str()));
398 ++it;
399 }
400 }
401 }
402 else
403 {
404 LogRelFunc(("Information: The original log folder %s doesn't exist\n", strFolder.c_str()));
405 rc = S_OK;//it's not error in this case if there isn't an original log folder
406 }
407 }
408
409 LogRelFunc(("Total space needed is %lld bytes\n", neededFreeSpace));
410 /* Check a target location on enough room */
411 if (totalFreeSpace - neededFreeSpace <= 1024*1024)
412 {
413 LogRelFunc(("but free space on destination is %lld\n", totalFreeSpace));
414 throw VERR_OUT_OF_RESOURCES;//less than 1Mb free space on the target location
415 }
416
417 /* Add step for .vbox machine setting file */
418 {
419 ++uCount;
420 uTotalWeight += 1;
421 }
422
423 /* Reserve additional steps in case of failure and rollback all changes */
424 {
425 uTotalWeight += uCount;//just add 1 for each possible rollback operation
426 uCount += uCount;//and increase the steps twice
427 }
428
429 /* Init Progress instance */
430 {
431 rc = m_pProgress->init(m_pMachine->i_getVirtualBox(),
432 static_cast<IMachine*>(m_pMachine) /* aInitiator */,
433 Bstr(m_pMachine->tr("Moving Machine")).raw(),
434 true /* fCancellable */,
435 uCount,
436 uTotalWeight,
437 Bstr(m_pMachine->tr("Initialize Moving")).raw(),
438 1);
439 if (FAILED(rc))
440 {
441 throw m_pMachine->setError(VBOX_E_IPRT_ERROR,
442 m_pMachine->tr("Couldn't correctly setup the progress object "
443 "for moving VM operation (%Rrc)"),
444 rc);
445 }
446 }
447
448 /* save all VM data */
449 m_pMachine->i_setModified(Machine::IsModified_MachineData);
450 rc = m_pMachine->SaveSettings();
451 }
452 catch(HRESULT hrc)
453 {
454 rc = hrc;
455 }
456
457 LogFlowFuncLeave();
458
459 return rc;
460}
461
462void MachineMoveVM::printStateFile(settings::SnapshotsList &snl)
463{
464 settings::SnapshotsList::iterator it;
465 for (it = snl.begin(); it != snl.end(); ++it)
466 {
467 if (!it->strStateFile.isEmpty())
468 {
469 settings::Snapshot snap = (settings::Snapshot)(*it);
470 LogRelFunc(("snap.uuid = %s\n", snap.uuid.toStringCurly().c_str()));
471 LogRelFunc(("snap.strStateFile = %s\n", snap.strStateFile.c_str()));
472 }
473
474 if (!it->llChildSnapshots.empty())
475 printStateFile(it->llChildSnapshots);
476 }
477}
478
479/* static */
480DECLCALLBACK(int) MachineMoveVM::updateProgress(unsigned uPercent, void *pvUser)
481{
482 MachineMoveVM* pTask = *(MachineMoveVM**)pvUser;
483
484 if ( pTask
485 && !pTask->m_pProgress.isNull())
486 {
487 BOOL fCanceled;
488 pTask->m_pProgress->COMGETTER(Canceled)(&fCanceled);
489 if (fCanceled)
490 return -1;
491 pTask->m_pProgress->SetCurrentOperationProgress(uPercent);
492 }
493 return VINF_SUCCESS;
494}
495
496/* static */
497DECLCALLBACK(int) MachineMoveVM::copyFileProgress(unsigned uPercentage, void *pvUser)
498{
499 ComObjPtr<Progress> pProgress = *static_cast< ComObjPtr<Progress>* >(pvUser);
500
501 BOOL fCanceled = false;
502 HRESULT rc = pProgress->COMGETTER(Canceled)(&fCanceled);
503 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
504 /* If canceled by the user tell it to the copy operation. */
505 if (fCanceled) return VERR_CANCELLED;
506 /* Set the new process. */
507 rc = pProgress->SetCurrentOperationProgress(uPercentage);
508 if (FAILED(rc)) return VERR_GENERAL_FAILURE;
509
510 return VINF_SUCCESS;
511}
512
513
514/* static */
515void MachineMoveVM::i_MoveVMThreadTask(MachineMoveVM* task)
516{
517 LogFlowFuncEnter();
518 HRESULT rc = S_OK;
519
520 MachineMoveVM* taskMoveVM = task;
521 ComObjPtr<Machine> &machine = taskMoveVM->m_pMachine;
522
523 AutoCaller autoCaller(machine);
524// if (FAILED(autoCaller.rc())) return;//Should we return something here?
525
526 Utf8Str strTargetFolder = taskMoveVM->m_targetPath;
527 {
528 Bstr bstrMachineName;
529 machine->COMGETTER(Name)(bstrMachineName.asOutParam());
530 strTargetFolder.append(Utf8Str(bstrMachineName));
531 }
532
533 RTCList<Utf8Str> newFiles; /* All extra created files (save states, ...) */
534 RTCList<Utf8Str> originalFiles; /* All original files except images */
535 typedef std::map<Utf8Str, ComObjPtr<Medium> > MediumMap;
536 MediumMap mapOriginalMedium;
537
538 /*
539 * We have the couple modes which user is able to request
540 * basic mode:
541 * - The images which are solely attached to the VM
542 * and located in the original VM folder will be moved.
543 * All subfolders related to the original VM are also moved from the original location
544 * (Standard - snapshots and logs folders).
545 *
546 * canonical mode:
547 * - All disks tied with the VM will be moved into a new location if it's possible.
548 * All folders related to the original VM are also moved.
549 * This mode is intended to collect all files/images/snapshots related to the VM in the one place.
550 *
551 */
552
553 /*
554 * A way to handle shareable disk:
555 * Collect the shareable disks attched to the VM.
556 * Get the machines whom the shareable disks attach to.
557 * Return an error if the state of any VM doesn't allow to move a shareable disk and
558 * this disk is located in the VM's folder (it means the disk is intended for "moving").
559 */
560
561
562 /*
563 * Check new destination whether enough room for the VM or not. if "not" return an error.
564 * Make a copy of VM settings and a list with all files which are moved. Save the list on the disk.
565 * Start "move" operation.
566 * Check the result of operation.
567 * if the operation was successful:
568 * - delete all files in the original VM folder;
569 * - update VM disks info with new location;
570 * - update all other VM if it's needed;
571 * - update global settings
572 */
573
574 try
575 {
576 /* Move all disks */
577 rc = taskMoveVM->moveAllDisks(taskMoveVM->finalMediumsMap, &strTargetFolder);
578 if (FAILED(rc))
579 throw rc;
580
581 /* Get Machine::Data here because moveAllDisks() change it */
582 Machine::Data *machineData = machine->mData.data();
583 settings::MachineConfigFile *machineConfFile = machineData->pMachineConfigFile;
584
585 /* Copy all save state files. */
586 Utf8Str strTrgSnapshotFolder;
587 {
588 /* When the current snapshot folder is absolute we reset it to the
589 * default relative folder. */
590 if (RTPathStartsWithRoot((*machineConfFile).machineUserData.strSnapshotFolder.c_str()))
591 (*machineConfFile).machineUserData.strSnapshotFolder = "Snapshots";
592 (*machineConfFile).strStateFile = "";
593
594 /* The absolute name of the snapshot folder. */
595 strTrgSnapshotFolder = Utf8StrFmt("%s%c%s", strTargetFolder.c_str(), RTPATH_DELIMITER,
596 (*machineConfFile).machineUserData.strSnapshotFolder.c_str());
597
598 /* Check if a snapshot folder is necessary and if so doesn't already
599 * exists. */
600 if ( taskMoveVM->finalSaveStateFilesMap.size() != 0
601 && !RTDirExists(strTrgSnapshotFolder.c_str()))
602 {
603 int vrc = RTDirCreateFullPath(strTrgSnapshotFolder.c_str(), 0700);
604 if (RT_FAILURE(vrc))
605 throw machine->setError(VBOX_E_IPRT_ERROR,
606 machine->tr("Could not create snapshots folder '%s' (%Rrc)"),
607 strTrgSnapshotFolder.c_str(), vrc);
608 }
609
610 std::map<Utf8Str, SAVESTATETASK>::iterator itState = taskMoveVM->finalSaveStateFilesMap.begin();
611 while (itState != taskMoveVM->finalSaveStateFilesMap.end())
612 {
613 const SAVESTATETASK &sst = itState->second;
614 const Utf8Str &strTrgSaveState = Utf8StrFmt("%s%c%s", strTrgSnapshotFolder.c_str(), RTPATH_DELIMITER,
615 RTPathFilename(sst.strSaveStateFile.c_str()));
616
617 /* Move to next sub-operation. */
618 rc = taskMoveVM->m_pProgress->SetNextOperation(BstrFmt(machine->tr("Copy the save state file '%s' ..."),
619 RTPathFilename(sst.strSaveStateFile.c_str())).raw(), sst.uWeight);
620 if (FAILED(rc)) throw rc;
621
622 int vrc = RTFileCopyEx(sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), 0,
623 MachineMoveVM::copyFileProgress, &taskMoveVM->m_pProgress);
624 if (RT_FAILURE(vrc))
625 throw machine->setError(VBOX_E_IPRT_ERROR,
626 machine->tr("Could not copy state file '%s' to '%s' (%Rrc)"),
627 sst.strSaveStateFile.c_str(), strTrgSaveState.c_str(), vrc);
628
629 /* save new file in case of restoring */
630 newFiles.append(strTrgSaveState);
631 /* save original file for deletion in the end */
632 originalFiles.append(sst.strSaveStateFile);
633 ++itState;
634 }
635 }
636
637 /*
638 * Update state file path
639 * very important step!
640 */
641 {
642 rc = taskMoveVM->updatePathsToStateFiles(taskMoveVM->finalSaveStateFilesMap,
643 taskMoveVM->vmFolders[VBox_SettingFolder],
644 strTargetFolder);
645 if (FAILED(rc))
646 throw rc;
647 }
648
649 /*
650 * Moving Machine settings file
651 * The settings file are moved after all disks and snapshots because this file should be updated
652 * with actual information and only then should be moved.
653 */
654 {
655 LogRelFunc(("Copy Machine settings file \n"));
656
657 rc = taskMoveVM->m_pProgress->SetNextOperation(BstrFmt(machine->tr("Copy Machine settings file '%s' ..."),
658 (*machineConfFile).machineUserData.strName.c_str()).raw(), 1);
659 if (FAILED(rc)) throw rc;
660
661 Utf8Str strTargetSettingsFilePath = strTargetFolder;
662
663 /* Check a folder existing and create one if it's not */
664 if (!RTDirExists(strTargetSettingsFilePath.c_str()))
665 {
666 int vrc = RTDirCreateFullPath(strTargetSettingsFilePath.c_str(), 0700);
667 if (RT_FAILURE(vrc))
668 throw machine->setError(VBOX_E_IPRT_ERROR,
669 machine->tr("Could not create a home machine folder '%s' (%Rrc)"),
670 strTargetSettingsFilePath.c_str(), vrc);
671 LogRelFunc(("Created a home machine folder %s\n", strTargetSettingsFilePath.c_str()));
672 }
673
674 /* Create a full path */
675 Bstr bstrMachineName;
676 machine->COMGETTER(Name)(bstrMachineName.asOutParam());
677 strTargetSettingsFilePath.append(RTPATH_DELIMITER).append(Utf8Str(bstrMachineName));
678 strTargetSettingsFilePath.append(".vbox");
679
680 Utf8Str strSettingsFilePath;
681 Bstr bstr_settingsFilePath;
682 machine->COMGETTER(SettingsFilePath)(bstr_settingsFilePath.asOutParam());
683 strSettingsFilePath = bstr_settingsFilePath;
684
685 int vrc = RTFileCopyEx(strSettingsFilePath.c_str(), strTargetSettingsFilePath.c_str(), 0,
686 MachineMoveVM::copyFileProgress, &taskMoveVM->m_pProgress);
687 if (RT_FAILURE(vrc))
688 throw machine->setError(VBOX_E_IPRT_ERROR,
689 machine->tr("Could not copy the setting file '%s' to '%s' (%Rrc)"),
690 strSettingsFilePath.c_str(), strTargetSettingsFilePath.stripFilename().c_str(), vrc);
691
692 LogRelFunc(("The setting file %s has been copied into the folder %s\n", strSettingsFilePath.c_str(),
693 strTargetSettingsFilePath.stripFilename().c_str()));
694
695 /* save new file in case of restoring */
696 newFiles.append(strTargetSettingsFilePath);
697 /* save original file for deletion in the end */
698 originalFiles.append(strSettingsFilePath);
699 }
700
701 /* Moving Machine log files */
702 {
703 LogRelFunc(("Copy machine log files \n"));
704
705 if (taskMoveVM->vmFolders[VBox_LogFolder].isNotEmpty())
706 {
707 /* Check an original log folder existence */
708 if (RTDirExists(taskMoveVM->vmFolders[VBox_LogFolder].c_str()))
709 {
710 Utf8Str strTargetLogFolderPath = strTargetFolder;
711 strTargetLogFolderPath.append(RTPATH_DELIMITER).append("Logs");
712
713 /* Check a destination log folder existence and create one if it's not */
714 if (!RTDirExists(strTargetLogFolderPath.c_str()))
715 {
716 int vrc = RTDirCreateFullPath(strTargetLogFolderPath.c_str(), 0700);
717 if (RT_FAILURE(vrc))
718 throw machine->setError(VBOX_E_IPRT_ERROR,
719 machine->tr("Could not create log folder '%s' (%Rrc)"),
720 strTargetLogFolderPath.c_str(), vrc);
721 LogRelFunc(("Created a log machine folder %s\n", strTargetLogFolderPath.c_str()));
722 }
723
724 fileList_t filesList;
725 taskMoveVM->getFilesList(taskMoveVM->vmFolders[VBox_LogFolder], filesList);
726 cit_t it = filesList.m_list.begin();
727 while(it != filesList.m_list.end())
728 {
729 Utf8Str strFullSourceFilePath = it->first.c_str();
730 strFullSourceFilePath.append(RTPATH_DELIMITER).append(it->second.c_str());
731
732 Utf8Str strFullTargetFilePath = strTargetLogFolderPath;
733 strFullTargetFilePath.append(RTPATH_DELIMITER).append(it->second.c_str());
734
735 /* Move to next sub-operation. */
736 rc = taskMoveVM->m_pProgress->SetNextOperation(BstrFmt(machine->tr("Copying the log file '%s' ..."),
737 RTPathFilename(strFullSourceFilePath.c_str())).raw(), 1);
738 if (FAILED(rc)) throw rc;
739
740 int vrc = RTFileCopyEx(strFullSourceFilePath.c_str(), strFullTargetFilePath.c_str(), 0,
741 MachineMoveVM::copyFileProgress, &taskMoveVM->m_pProgress);
742 if (RT_FAILURE(vrc))
743 throw machine->setError(VBOX_E_IPRT_ERROR,
744 machine->tr("Could not copy the log file '%s' to '%s' (%Rrc)"),
745 strFullSourceFilePath.c_str(), strFullTargetFilePath.stripFilename().c_str(), vrc);
746
747 LogRelFunc(("The log file %s has been copied into the folder %s\n", strFullSourceFilePath.c_str(),
748 strFullTargetFilePath.stripFilename().c_str()));
749
750 /* save new file in case of restoring */
751 newFiles.append(strFullTargetFilePath);
752 /* save original file for deletion in the end */
753 originalFiles.append(strFullSourceFilePath);
754
755 ++it;
756 }
757 }
758 }
759 }
760
761 /* save all VM data */
762 {
763 rc = machine->SaveSettings();
764 }
765
766 {
767 LogRelFunc(("Update path to XML setting file\n"));
768 Utf8Str strTargetSettingsFilePath = strTargetFolder;
769 Bstr bstrMachineName;
770 machine->COMGETTER(Name)(bstrMachineName.asOutParam());
771 strTargetSettingsFilePath.append(RTPATH_DELIMITER).append(Utf8Str(bstrMachineName)).append(".vbox");
772 machineData->m_strConfigFileFull = strTargetSettingsFilePath;
773 machine->mParent->i_copyPathRelativeToConfig(strTargetSettingsFilePath, machineData->m_strConfigFile);
774 }
775
776 /* Save global settings in the VirtualBox.xml */
777 {
778 /* Marks the global registry for uuid as modified */
779 Guid uuid = machine->mData->mUuid;
780 machine->mParent->i_markRegistryModified(uuid);
781
782 /* for saving the global settings we should hold only the VirtualBox lock */
783 AutoWriteLock vboxLock(machine->mParent COMMA_LOCKVAL_SRC_POS);
784
785 rc = machine->mParent->i_saveSettings();
786 }
787 }
788 catch(HRESULT hrc)
789 {
790 LogRelFunc(("Moving machine to a new destination was failed. Check original and destination places.\n"));
791 rc = hrc;
792 taskMoveVM->result = rc;
793 }
794 catch (...)
795 {
796 LogRelFunc(("Moving machine to a new destination was failed. Check original and destination places.\n"));
797 rc = VirtualBoxBase::handleUnexpectedExceptions(machine, RT_SRC_POS);
798 taskMoveVM->result = rc;
799 }
800
801 /* Cleanup on failure */
802 if (FAILED(rc))
803 {
804 Machine::Data *machineData = machine->mData.data();
805
806 /* ! Apparently we should update the Progress object !*/
807 ULONG operationCount = 0;
808 rc = taskMoveVM->m_pProgress->COMGETTER(OperationCount)(&operationCount);
809 ULONG operation = 0;
810 rc = taskMoveVM->m_pProgress->COMGETTER(Operation)(&operation);
811 Bstr bstrOperationDescription;
812 rc = taskMoveVM->m_pProgress->COMGETTER(OperationDescription)(bstrOperationDescription.asOutParam());
813 Utf8Str strOperationDescription = bstrOperationDescription;
814 ULONG operationPercent = 0;
815 rc = taskMoveVM->m_pProgress->COMGETTER(OperationPercent)(&operationPercent);
816
817 Bstr bstrMachineName;
818 machine->COMGETTER(Name)(bstrMachineName.asOutParam());
819 LogRelFunc(("Moving machine %s was failed on operation %s\n",
820 Utf8Str(bstrMachineName.raw()).c_str(), Utf8Str(bstrOperationDescription.raw()).c_str()));
821
822 /* Restoring the original mediums */
823 try
824 {
825 /*
826 * Fix the progress count
827 * In instance, the whole "move vm" operation is failed on 9th step. But total count is 20.
828 * Where 20 = 2 * 10 operations, where 10 is the real number of operations. And this value was doubled
829 * earlier in the init() exactly for one reason - rollback operation. Because in this case we must do
830 * the same operations but in backward direction.
831 * Thus now we want to correct progress operation count from 9 to 11. Why?
832 * Because we should have evaluated count as "20/2 + (20/2 - 9)" = 11 or just "20 - 9" = 11
833 */
834 for (ULONG i = operation; i < operationCount - operation; ++i)
835 {
836 rc = taskMoveVM->m_pProgress->SetNextOperation(BstrFmt("Skip the empty operation %d...", i + 1).raw(), 1);
837 if (FAILED(rc)) throw rc;
838 }
839
840 rc = taskMoveVM->moveAllDisks(taskMoveVM->finalMediumsMap);
841 if (FAILED(rc))
842 throw rc;
843 }
844 catch(HRESULT hrc)
845 {
846 LogRelFunc(("Rollback scenario: restoration the original mediums were failed. Machine can be corrupted.\n"));
847 taskMoveVM->result = hrc;
848 }
849 catch (...)
850 {
851 LogRelFunc(("Rollback scenario: restoration the original mediums were failed. Machine can be corrupted.\n"));
852 rc = VirtualBoxBase::handleUnexpectedExceptions(machine, RT_SRC_POS);
853 taskMoveVM->result = rc;
854 }
855
856 /* Revert original paths to the state files */
857 rc = taskMoveVM->updatePathsToStateFiles(taskMoveVM->finalSaveStateFilesMap,
858 strTargetFolder,
859 taskMoveVM->vmFolders[VBox_SettingFolder]);
860 if (FAILED(rc))
861 {
862 LogRelFunc(("Rollback scenario: can't restore the original paths to the state files. "
863 "Machine settings %s can be corrupted.\n", machineData->m_strConfigFileFull.c_str()));
864 }
865
866 /* Delete all created files. Here we update progress object */
867 rc = taskMoveVM->deleteFiles(newFiles);
868 if (FAILED(rc))
869 LogRelFunc(("Rollback scenario: can't delete new created files. Check the destination folder."));
870
871 /* Delete destination folder */
872 RTDirRemove(strTargetFolder.c_str());
873
874 /* save all VM data */
875 {
876 AutoWriteLock srcLock(machine COMMA_LOCKVAL_SRC_POS);
877 srcLock.release();
878 rc = machine->SaveSettings();
879 srcLock.acquire();
880 }
881
882 /* Restore an original path to XML setting file */
883 {
884 LogRelFunc(("Rollback scenario: Restore an original path to XML setting file\n"));
885 Utf8Str strOriginalSettingsFilePath = taskMoveVM->vmFolders[VBox_SettingFolder];
886 strOriginalSettingsFilePath.append(RTPATH_DELIMITER).append(Utf8Str(bstrMachineName)).append(".vbox");
887 machineData->m_strConfigFileFull = strOriginalSettingsFilePath;
888 machine->mParent->i_copyPathRelativeToConfig(strOriginalSettingsFilePath, machineData->m_strConfigFile);
889 }
890
891 /* Marks the global registry for uuid as modified */
892 {
893 AutoWriteLock srcLock(machine COMMA_LOCKVAL_SRC_POS);
894 srcLock.release();
895 Guid uuid = machine->mData->mUuid;
896 machine->mParent->i_markRegistryModified(uuid);
897 srcLock.acquire();
898
899 // save the global settings; for that we should hold only the VirtualBox lock
900 AutoWriteLock vboxLock(machine->mParent COMMA_LOCKVAL_SRC_POS);
901
902 rc = machine->mParent->i_saveSettings();
903 }
904
905 /* In case of failure the progress object on the other side (user side) get notification about operation
906 completion but the operation percentage may not be set to 100% */
907 }
908 else /*Operation was successful and now we can delete the original files like the state files, XML setting, log files */
909 {
910 /*
911 * In case of success it's not urgent to update the progress object because we call i_notifyComplete() with
912 * the success result. As result, the last number of progress operation can be not equal the number of operations
913 * because we doubled the number of operations for rollback case.
914 * But if we want to update the progress object corectly it's needed to add all medium moved by standard
915 * "move medium" logic (for us it's taskMoveVM->finalMediumsMap) to the current number of operation.
916 */
917
918 ULONG operationCount = 0;
919 rc = taskMoveVM->m_pProgress->COMGETTER(OperationCount)(&operationCount);
920 ULONG operation = 0;
921 rc = taskMoveVM->m_pProgress->COMGETTER(Operation)(&operation);
922
923 for (ULONG i = operation; i < operation + taskMoveVM->finalMediumsMap.size() - 1; ++i)
924 {
925 rc = taskMoveVM->m_pProgress->SetNextOperation(BstrFmt("Skip the empty operation %d...", i).raw(), 1);
926 if (FAILED(rc)) throw rc;
927 }
928
929 rc = taskMoveVM->deleteFiles(originalFiles);
930 if (FAILED(rc))
931 LogRelFunc(("Forward scenario: can't delete all original files.\n"));
932 }
933
934 if (!taskMoveVM->m_pProgress.isNull())
935 taskMoveVM->m_pProgress->i_notifyComplete(taskMoveVM->result);
936
937 LogFlowFuncLeave();
938}
939
940HRESULT MachineMoveVM::moveAllDisks(const std::map<Utf8Str, MEDIUMTASK>& listOfDisks,
941 const Utf8Str* strTargetFolder)
942{
943 HRESULT rc = S_OK;
944 ComObjPtr<Machine> &machine = m_pMachine;
945 Utf8Str strLocation;
946
947 AutoWriteLock machineLock(machine COMMA_LOCKVAL_SRC_POS);
948
949 try{
950 std::map<Utf8Str, MEDIUMTASK>::const_iterator itMedium = listOfDisks.begin();
951 while(itMedium != listOfDisks.end())
952 {
953 const MEDIUMTASK &mt = itMedium->second;
954 ComPtr<IMedium> pMedium = mt.pMedium;
955 Utf8Str strTargetImageName;
956 Bstr bstrLocation;
957 Bstr bstrSrcName;
958
959 rc = pMedium->COMGETTER(Name)(bstrSrcName.asOutParam());
960 if (FAILED(rc)) throw rc;
961
962 if (strTargetFolder != NULL && !strTargetFolder->isEmpty())
963 {
964 strTargetImageName = *strTargetFolder;
965 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
966 if (FAILED(rc)) throw rc;
967 strLocation = bstrLocation;
968
969 if (mt.fSnapshot == true)
970 {
971 strLocation.stripFilename().stripPath().append(RTPATH_DELIMITER).append(Utf8Str(bstrSrcName));
972 }
973 else
974 {
975 strLocation.stripPath();
976 }
977
978 strTargetImageName.append(RTPATH_DELIMITER).append(strLocation);
979 rc = m_pProgress->SetNextOperation(BstrFmt(machine->tr("Moving medium '%ls' ..."),
980 bstrSrcName.raw()).raw(),
981 mt.uWeight);
982 if (FAILED(rc)) throw rc;
983 }
984 else
985 {
986 strTargetImageName = mt.strBaseName;//Should contain full path to the image
987 rc = m_pProgress->SetNextOperation(BstrFmt(machine->tr("Moving medium '%ls' back..."),
988 bstrSrcName.raw()).raw(),
989 mt.uWeight);
990 if (FAILED(rc)) throw rc;
991 }
992
993
994
995 /* consistency: use \ if appropriate on the platform */
996 RTPathChangeToDosSlashes(strTargetImageName.mutableRaw(), false);
997
998 bstrLocation = strTargetImageName.c_str();
999
1000 MediumType_T mediumType;//immutable, shared, passthrough
1001 rc = pMedium->COMGETTER(Type)(&mediumType);
1002 if (FAILED(rc)) throw rc;
1003
1004 DeviceType_T deviceType;//floppy, hard, DVD
1005 rc = pMedium->COMGETTER(DeviceType)(&deviceType);
1006 if (FAILED(rc)) throw rc;
1007
1008 ComPtr<IProgress> moveDiskProgress;
1009 rc = pMedium->SetLocation(bstrLocation.raw(), moveDiskProgress.asOutParam());
1010 /* Wait until the async process has finished. */
1011 machineLock.release();
1012
1013 rc = m_pProgress->WaitForAsyncProgressCompletion(moveDiskProgress);
1014
1015 machineLock.acquire();
1016 if (FAILED(rc)) throw rc;
1017
1018 LogRelFunc(("Moving %s has been finished\n", strTargetImageName.c_str()));
1019
1020 /* Check the result of the async process. */
1021 LONG iRc;
1022 rc = moveDiskProgress->COMGETTER(ResultCode)(&iRc);
1023 if (FAILED(rc)) throw rc;
1024 /* If the thread of the progress object has an error, then
1025 * retrieve the error info from there, or it'll be lost. */
1026 if (FAILED(iRc))
1027 throw machine->setError(ProgressErrorInfo(moveDiskProgress));
1028
1029 ++itMedium;
1030 }
1031
1032 machineLock.release();
1033 }
1034 catch(HRESULT hrc)
1035 {
1036 LogRelFunc(("\nException during moving the disk %s\n", strLocation.c_str()));
1037 rc = hrc;
1038 machineLock.release();
1039 }
1040 catch (...)
1041 {
1042 LogRelFunc(("\nException during moving the disk %s\n", strLocation.c_str()));
1043 rc = VirtualBoxBase::handleUnexpectedExceptions(m_pMachine, RT_SRC_POS);
1044 machineLock.release();
1045 }
1046
1047 return rc;
1048}
1049
1050HRESULT MachineMoveVM::updatePathsToStateFiles(const std::map<Utf8Str, SAVESTATETASK>& listOfFiles,
1051 const Utf8Str& sourcePath, const Utf8Str& targetPath)
1052{
1053 HRESULT rc = S_OK;
1054
1055 std::map<Utf8Str, SAVESTATETASK>::const_iterator itState = listOfFiles.begin();
1056 while (itState != listOfFiles.end())
1057 {
1058 const SAVESTATETASK &sst = itState->second;
1059
1060 Utf8Str strGuidMachine = sst.snapshotUuid.toString();
1061 ComObjPtr<Snapshot> snapshotMachineObj;
1062
1063 rc = m_pMachine->i_findSnapshotById(sst.snapshotUuid, snapshotMachineObj, true);
1064 if (SUCCEEDED(rc) && !snapshotMachineObj.isNull())
1065 {
1066 snapshotMachineObj->i_updateSavedStatePaths(sourcePath.c_str(),
1067 targetPath.c_str());
1068 }
1069
1070 ++itState;
1071 }
1072
1073 return rc;
1074}
1075
1076HRESULT MachineMoveVM::getFilesList(const Utf8Str& strRootFolder, fileList_t &filesList)
1077{
1078 RTDIR hDir;
1079 HRESULT rc = S_OK;
1080 int vrc = RTDirOpen(&hDir, strRootFolder.c_str());
1081 if (RT_SUCCESS(vrc))
1082 {
1083 RTDIRENTRY DirEntry;
1084 while (RT_SUCCESS(RTDirRead(hDir, &DirEntry, NULL)))
1085 {
1086 if (RTDirEntryIsStdDotLink(&DirEntry))
1087 continue;
1088
1089 if (DirEntry.enmType == RTDIRENTRYTYPE_FILE)
1090 {
1091 Utf8Str fullPath(strRootFolder);
1092 filesList.add(strRootFolder, DirEntry.szName);
1093 }
1094 else if (DirEntry.enmType == RTDIRENTRYTYPE_DIRECTORY)
1095 {
1096 Utf8Str strNextFolder(strRootFolder);
1097 strNextFolder.append(RTPATH_DELIMITER).append(DirEntry.szName);
1098 rc = getFilesList(strNextFolder, filesList);
1099 if (FAILED(rc))
1100 break;
1101 }
1102 }
1103
1104 vrc = RTDirClose(hDir);
1105 }
1106 else if (vrc == VERR_FILE_NOT_FOUND)
1107 {
1108 m_pMachine->setError(VBOX_E_IPRT_ERROR,
1109 m_pMachine->tr("Folder '%s' doesn't exist (%Rrc)"),
1110 strRootFolder.c_str(), vrc);
1111 rc = vrc;
1112 }
1113 else
1114 throw m_pMachine->setError(VBOX_E_IPRT_ERROR,
1115 m_pMachine->tr("Could not open folder '%s' (%Rrc)"),
1116 strRootFolder.c_str(), vrc);
1117 return rc;
1118}
1119
1120HRESULT MachineMoveVM::deleteFiles(const RTCList<Utf8Str>& listOfFiles)
1121{
1122 HRESULT rc = S_OK;
1123 /* Delete all created files. */
1124 try
1125 {
1126 for (size_t i = 0; i < listOfFiles.size(); ++i)
1127 {
1128 LogRelFunc(("Deleting file %s ...\n", listOfFiles.at(i).c_str()));
1129 rc = m_pProgress->SetNextOperation(BstrFmt("Deleting file %s...", listOfFiles.at(i).c_str()).raw(), 1);
1130 if (FAILED(rc)) throw rc;
1131
1132 int vrc = RTFileDelete(listOfFiles.at(i).c_str());
1133 if (RT_FAILURE(vrc))
1134 rc = m_pMachine->setError(VBOX_E_IPRT_ERROR,
1135 m_pMachine->tr("Could not delete file '%s' (%Rrc)"),
1136 listOfFiles.at(i).c_str(), rc);
1137 else
1138 LogRelFunc(("File %s has been deleted\n", listOfFiles.at(i).c_str()));
1139 }
1140 }
1141 catch(HRESULT hrc)
1142 {
1143 rc = hrc;
1144 }
1145 catch (...)
1146 {
1147 rc = VirtualBoxBase::handleUnexpectedExceptions(m_pMachine, RT_SRC_POS);
1148 }
1149
1150 return rc;
1151}
1152
1153HRESULT MachineMoveVM::getFolderSize(const Utf8Str& strRootFolder, uint64_t& size)
1154{
1155 HRESULT rc = S_OK;
1156 int vrc = 0;
1157 uint64_t totalFolderSize = 0;
1158 fileList_t filesList;
1159
1160 bool ex = RTPathExists(strRootFolder.c_str());
1161 if (ex == true)
1162 {
1163 rc = getFilesList(strRootFolder, filesList);
1164 if (SUCCEEDED(rc))
1165 {
1166 cit_t it = filesList.m_list.begin();
1167 while(it != filesList.m_list.end())
1168 {
1169 uint64_t cbFile = 0;
1170 Utf8Str fullPath = it->first;
1171 fullPath.append(RTPATH_DELIMITER).append(it->second);
1172 vrc = RTFileQuerySize(fullPath.c_str(), &cbFile);
1173 if (RT_SUCCESS(vrc))
1174 {
1175 totalFolderSize += cbFile;
1176 }
1177 else
1178 throw m_pMachine->setError(VBOX_E_IPRT_ERROR,
1179 m_pMachine->tr("Could not get the size of file '%s' (%Rrc)"),
1180 fullPath.c_str(), vrc);
1181 ++it;
1182 }
1183
1184 size = totalFolderSize;
1185 }
1186 else
1187 m_pMachine->setError(VBOX_E_IPRT_ERROR,
1188 m_pMachine->tr("Could not calculate the size of folder '%s' (%Rrc)"),
1189 strRootFolder.c_str(), vrc);
1190 }
1191 else
1192 size = 0;
1193
1194 return rc;
1195}
1196
1197HRESULT MachineMoveVM::queryBaseName(const ComPtr<IMedium> &pMedium, Utf8Str &strBaseName) const
1198{
1199 ComPtr<IMedium> pBaseMedium;
1200 HRESULT rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
1201 if (FAILED(rc)) return rc;
1202 Bstr bstrBaseName;
1203 rc = pBaseMedium->COMGETTER(Name)(bstrBaseName.asOutParam());
1204 if (FAILED(rc)) return rc;
1205 strBaseName = bstrBaseName;
1206 return rc;
1207}
1208
1209HRESULT MachineMoveVM::createMachineList(const ComPtr<ISnapshot> &pSnapshot,
1210 std::vector< ComObjPtr<Machine> > &aMachineList) const
1211{
1212 HRESULT rc = S_OK;
1213 Bstr name;
1214 rc = pSnapshot->COMGETTER(Name)(name.asOutParam());
1215 if (FAILED(rc)) return rc;
1216
1217 ComPtr<IMachine> l_pMachine;
1218 rc = pSnapshot->COMGETTER(Machine)(l_pMachine.asOutParam());
1219 if (FAILED(rc)) return rc;
1220 aMachineList.push_back((Machine*)(IMachine*)l_pMachine);
1221
1222 SafeIfaceArray<ISnapshot> sfaChilds;
1223 rc = pSnapshot->COMGETTER(Children)(ComSafeArrayAsOutParam(sfaChilds));
1224 if (FAILED(rc)) return rc;
1225 for (size_t i = 0; i < sfaChilds.size(); ++i)
1226 {
1227 rc = createMachineList(sfaChilds[i], aMachineList);
1228 if (FAILED(rc)) return rc;
1229 }
1230
1231 return rc;
1232}
1233
1234HRESULT MachineMoveVM::queryMediasForAllStates(const std::vector<ComObjPtr<Machine> > &aMachineList)
1235{
1236 /* In this case we create a exact copy of the original VM. This means just
1237 * adding all directly and indirectly attached disk images to the worker
1238 * list. */
1239 HRESULT rc = S_OK;
1240 for (size_t i = 0; i < aMachineList.size(); ++i)
1241 {
1242 const ComObjPtr<Machine> &machine = aMachineList.at(i);
1243
1244 /* Add all attachments (and their parents) of the different
1245 * machines to a worker list. */
1246 SafeIfaceArray<IMediumAttachment> sfaAttachments;
1247 rc = machine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
1248 if (FAILED(rc)) return rc;
1249 for (size_t a = 0; a < sfaAttachments.size(); ++a)
1250 {
1251 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[a];
1252 DeviceType_T deviceType;//floppy, hard, DVD
1253 rc = pAtt->COMGETTER(Type)(&deviceType);
1254 if (FAILED(rc)) return rc;
1255
1256 /* Valid medium attached? */
1257 ComPtr<IMedium> pMedium;
1258 rc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
1259 if (FAILED(rc)) return rc;
1260
1261 if (pMedium.isNull())
1262 continue;
1263
1264 Bstr bstrLocation;
1265 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
1266 if (FAILED(rc)) throw rc;
1267
1268 /* Cast to ComObjPtr<Medium> */
1269 ComObjPtr<Medium> pObjMedium = (Medium *)(IMedium *)pMedium;
1270
1271 /*Check for "read-only" medium in terms that VBox can't create this one */
1272 bool fPass = isMediumTypeSupportedForMoving(pMedium);
1273 if(!fPass)
1274 {
1275 LogRelFunc(("Skipping file %s because of this medium type hasn't been supported for moving.\n",
1276 Utf8Str(bstrLocation.raw()).c_str()));
1277 continue;
1278 }
1279
1280 MEDIUMTASKCHAIN mtc;
1281 mtc.devType = deviceType;
1282
1283 while (!pMedium.isNull())
1284 {
1285 /* Refresh the state so that the file size get read. */
1286 MediumState_T e;
1287 rc = pMedium->RefreshState(&e);
1288 if (FAILED(rc)) return rc;
1289
1290 LONG64 lSize;
1291 rc = pMedium->COMGETTER(Size)(&lSize);
1292 if (FAILED(rc)) return rc;
1293
1294 MediumType_T mediumType;//immutable, shared, passthrough
1295 rc = pMedium->COMGETTER(Type)(&mediumType);
1296 if (FAILED(rc)) throw rc;
1297
1298 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
1299 if (FAILED(rc)) throw rc;
1300
1301 MEDIUMTASK mt;
1302 mt.strBaseName = bstrLocation;
1303 Utf8Str strFolder = vmFolders[VBox_SnapshotFolder];
1304 if (strFolder.isNotEmpty() && mt.strBaseName.contains(strFolder))
1305 {
1306 mt.fSnapshot = true;
1307 }
1308 else
1309 mt.fSnapshot = false;
1310
1311 mt.uIdx = UINT32_MAX;
1312 mt.pMedium = pMedium;
1313 mt.uWeight = (ULONG)((lSize + _1M - 1) / _1M);
1314 mtc.chain.append(mt);
1315
1316 /* Query next parent. */
1317 rc = pMedium->COMGETTER(Parent)(pMedium.asOutParam());
1318 if (FAILED(rc)) return rc;
1319 }
1320
1321 llMedias.append(mtc);
1322 }
1323 /* Add the save state files of this machine if there is one. */
1324 rc = addSaveState(machine);
1325 if (FAILED(rc)) return rc;
1326
1327 }
1328 /* Build up the index list of the image chain. Unfortunately we can't do
1329 * that in the previous loop, cause there we go from child -> parent and
1330 * didn't know how many are between. */
1331 for (size_t i = 0; i < llMedias.size(); ++i)
1332 {
1333 uint32_t uIdx = 0;
1334 MEDIUMTASKCHAIN &mtc = llMedias.at(i);
1335 for (size_t a = mtc.chain.size(); a > 0; --a)
1336 mtc.chain[a - 1].uIdx = uIdx++;
1337 }
1338
1339 return rc;
1340}
1341
1342HRESULT MachineMoveVM::addSaveState(const ComObjPtr<Machine> &machine)
1343{
1344 Bstr bstrSrcSaveStatePath;
1345 HRESULT rc = machine->COMGETTER(StateFilePath)(bstrSrcSaveStatePath.asOutParam());
1346 if (FAILED(rc)) return rc;
1347 if (!bstrSrcSaveStatePath.isEmpty())
1348 {
1349 SAVESTATETASK sst;
1350
1351 sst.snapshotUuid = machine->i_getSnapshotId();
1352 sst.strSaveStateFile = bstrSrcSaveStatePath;
1353 uint64_t cbSize;
1354
1355 int vrc = RTFileQuerySize(sst.strSaveStateFile.c_str(), &cbSize);
1356 if (RT_FAILURE(vrc))
1357 return m_pMachine->setError(VBOX_E_IPRT_ERROR, m_pMachine->tr("Could not query file size of '%s' (%Rrc)"),
1358 sst.strSaveStateFile.c_str(), vrc);
1359 /* same rule as above: count both the data which needs to
1360 * be read and written */
1361 sst.uWeight = (ULONG)(2 * (cbSize + _1M - 1) / _1M);
1362 llSaveStateFiles.append(sst);
1363 }
1364 return S_OK;
1365}
1366
1367void MachineMoveVM::updateProgressStats(MEDIUMTASKCHAIN &mtc, ULONG &uCount, ULONG &uTotalWeight) const
1368{
1369
1370 /* Currently the copying of diff images involves reading at least
1371 * the biggest parent in the previous chain. So even if the new
1372 * diff image is small in size, it could need some time to create
1373 * it. Adding the biggest size in the chain should balance this a
1374 * little bit more, i.e. the weight is the sum of the data which
1375 * needs to be read and written. */
1376 ULONG uMaxWeight = 0;
1377 for (size_t e = mtc.chain.size(); e > 0; --e)
1378 {
1379 MEDIUMTASK &mt = mtc.chain.at(e - 1);
1380 mt.uWeight += uMaxWeight;
1381
1382 /* Calculate progress data */
1383 ++uCount;
1384 uTotalWeight += mt.uWeight;
1385
1386 /* Save the max size for better weighting of diff image
1387 * creation. */
1388 uMaxWeight = RT_MAX(uMaxWeight, mt.uWeight);
1389 }
1390}
1391
1392bool MachineMoveVM::isMediumTypeSupportedForMoving(const ComPtr<IMedium> &pMedium)
1393{
1394 HRESULT rc = S_OK;
1395 bool fSupported = true;
1396 Bstr bstrLocation;
1397 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
1398 if (FAILED(rc))
1399 {
1400 fSupported = false;
1401 throw rc;
1402 }
1403
1404 DeviceType_T deviceType;
1405 rc = pMedium->COMGETTER(DeviceType)(&deviceType);
1406 if (FAILED(rc))
1407 {
1408 fSupported = false;
1409 throw rc;
1410 }
1411
1412 ComPtr<IMediumFormat> mediumFormat;
1413 rc = pMedium->COMGETTER(MediumFormat)(mediumFormat.asOutParam());
1414 if (FAILED(rc))
1415 {
1416 fSupported = false;
1417 throw rc;
1418 }
1419
1420 /*Check whether VBox is able to create this medium format or not, i.e. medium can be "read-only" */
1421 Bstr bstrFormatName;
1422 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
1423 if (FAILED(rc))
1424 {
1425 fSupported = false;
1426 throw rc;
1427 }
1428
1429 Utf8Str formatName = Utf8Str(bstrFormatName);
1430 if (formatName.compare("VHDX", Utf8Str::CaseInsensitive) == 0)
1431 {
1432 LogRelFunc(("Skipping medium %s. VHDX format is supported in \"read-only\" mode only. \n",
1433 Utf8Str(bstrLocation.raw()).c_str()));
1434 fSupported = false;
1435 }
1436
1437 /* Check whether medium is represented by file on the disk or not */
1438 if (fSupported)
1439 {
1440 ComObjPtr<Medium> pObjMedium = (Medium *)(IMedium *)pMedium;
1441 fSupported = pObjMedium->i_isMediumFormatFile();
1442 if (!fSupported)
1443 {
1444 LogRelFunc(("Skipping medium %s because it's not a real file on the disk.\n",
1445 Utf8Str(bstrLocation.raw()).c_str()));
1446 }
1447 }
1448
1449 /* some special checks for DVD */
1450 if (fSupported && deviceType == DeviceType_DVD)
1451 {
1452 Utf8Str ext = bstrLocation;
1453 ext.assignEx(RTPathSuffix(ext.c_str()));//returns extension with dot (".iso")
1454
1455 //only ISO image is moved. Otherwise adding some information into log file
1456 int equality = ext.compare(".iso", Utf8Str::CaseInsensitive);
1457 if (equality != false)
1458 {
1459 LogRelFunc(("Skipping file %s. Only ISO images are supported for now.\n",
1460 Utf8Str(bstrLocation.raw()).c_str()));
1461 fSupported = false;
1462 }
1463 }
1464
1465 return fSupported;
1466}
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