Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
3fc0bf9db6063470586ced7aaee6920d321b5fcb
[simgrid.git] / src / msg / msg_vm.cpp
1 /* Copyright (c) 2012-2017. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 /* TODO:
8  * 1. add the support of trace
9  * 2. use parallel tasks to simulate CPU overhead and remove the experimental code generating micro computation tasks
10  */
11
12 #include <xbt/ex.hpp>
13
14 #include "simgrid/plugins/live_migration.h"
15 #include "src/instr/instr_private.hpp"
16 #include "src/plugins/vm/VirtualMachineImpl.hpp"
17 #include "src/plugins/vm/VmHostExt.hpp"
18
19 #include "simgrid/host.h"
20 #include "simgrid/simix.hpp"
21 #include "xbt/string.hpp"
22
23 extern "C" {
24
25 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(msg_vm, msg, "Cloud-oriented parts of the MSG API");
26
27 const char* MSG_vm_get_name(msg_vm_t vm)
28 {
29   return vm->getCname();
30 }
31
32 /** @brief Get the physical host of a given VM.
33  *  @ingroup msg_VMs
34  */
35 msg_host_t MSG_vm_get_pm(msg_vm_t vm)
36 {
37   return vm->getPm();
38 }
39
40 /** \ingroup m_vm_management
41  * \brief Set the parameters of a given host
42  *
43  * \param vm a vm
44  * \param params a parameter object
45  */
46 void MSG_vm_set_params(msg_vm_t vm, vm_params_t params)
47 {
48   vm->setParameters(params);
49 }
50
51 /** \ingroup m_vm_management
52  * \brief Get the parameters of a given host
53  *
54  * \param vm the vm you are interested into
55  * \param params a prameter object
56  */
57 void MSG_vm_get_params(msg_vm_t vm, vm_params_t params)
58 {
59   vm->getParameters(params);
60 }
61
62 void MSG_vm_set_ramsize(msg_vm_t vm, size_t size)
63 {
64   vm->setRamsize(size);
65 }
66 size_t MSG_vm_get_ramsize(msg_vm_t vm)
67 {
68   return vm->getRamsize();
69 }
70
71 /* **** Check state of a VM **** */
72 void MSG_vm_set_bound(msg_vm_t vm, double bound)
73 {
74   vm->setBound(bound);
75 }
76 static inline int __MSG_vm_is_state(msg_vm_t vm, e_surf_vm_state_t state)
77 {
78   return vm->pimpl_vm_ != nullptr && vm->getState() == state;
79 }
80
81 /** @brief Returns whether the given VM has just created, not running.
82  *  @ingroup msg_VMs
83  */
84 int MSG_vm_is_created(msg_vm_t vm)
85 {
86   return __MSG_vm_is_state(vm, SURF_VM_STATE_CREATED);
87 }
88
89 /** @brief Returns whether the given VM is currently running
90  *  @ingroup msg_VMs
91  */
92 int MSG_vm_is_running(msg_vm_t vm)
93 {
94   return __MSG_vm_is_state(vm, SURF_VM_STATE_RUNNING);
95 }
96
97 /** @brief Returns whether the given VM is currently migrating
98  *  @ingroup msg_VMs
99  */
100 int MSG_vm_is_migrating(msg_vm_t vm)
101 {
102   return vm->isMigrating();
103 }
104
105 /** @brief Returns whether the given VM is currently suspended, not running.
106  *  @ingroup msg_VMs
107  */
108 int MSG_vm_is_suspended(msg_vm_t vm)
109 {
110   return __MSG_vm_is_state(vm, SURF_VM_STATE_SUSPENDED);
111 }
112
113 /* **** ******** MSG vm actions ********* **** */
114 /** @brief Create a new VM with specified parameters.
115  *  @ingroup msg_VMs*
116  *  @param pm        Physical machine that will host the VM
117  *  @param name      Must be unique
118  *  @param coreAmount Must be >= 1
119  *  @param ramsize   [TODO]
120  *  @param mig_netspeed Amount of Mbyte/s allocated to the migration (cannot be larger than net_cap). Use 0 if unsure.
121  *  @param dp_intensity Dirty page percentage according to migNetSpeed, [0-100]. Use 0 if unsure.
122  */
123 msg_vm_t MSG_vm_create(msg_host_t pm, const char* name, int coreAmount, int ramsize, int mig_netspeed, int dp_intensity)
124 {
125   simgrid::vm::VmHostExt::ensureVmExtInstalled();
126
127   /* For the moment, intensity_rate is the percentage against the migration bandwidth */
128
129   msg_vm_t vm = new simgrid::s4u::VirtualMachine(name, pm, coreAmount, static_cast<sg_size_t>(ramsize) * 1024 * 1024);
130   s_vm_params_t params;
131   params.max_downtime = 0.03;
132   params.mig_speed    = static_cast<double>(mig_netspeed) * 1024 * 1024; // mig_speed
133   params.dp_intensity = static_cast<double>(dp_intensity) / 100;
134   params.dp_cap       = vm->getRamsize() * 0.9; // assume working set memory is 90% of ramsize
135
136   XBT_DEBUG("migspeed : %f intensity mem : %d", params.mig_speed, dp_intensity);
137   vm->setParameters(&params);
138
139   return vm;
140 }
141
142 /** @brief Create a new VM object with the default parameters
143  *  @ingroup msg_VMs*
144  *
145  * A VM is treated as a host. The name of the VM must be unique among all hosts.
146  */
147 msg_vm_t MSG_vm_create_core(msg_host_t pm, const char* name)
148 {
149   xbt_assert(sg_host_by_name(name) == nullptr,
150              "Cannot create a VM named %s: this name is already used by an host or a VM", name);
151
152   msg_vm_t vm = new simgrid::s4u::VirtualMachine(name, pm, 1);
153   s_vm_params_t params;
154   memset(&params, 0, sizeof(params));
155   vm->setParameters(&params);
156   return vm;
157 }
158 /** @brief Create a new VM object with the default parameters, but with a specified amount of cores
159  *  @ingroup msg_VMs*
160  *
161  * A VM is treated as a host. The name of the VM must be unique among all hosts.
162  */
163 msg_vm_t MSG_vm_create_multicore(msg_host_t pm, const char* name, int coreAmount)
164 {
165   xbt_assert(sg_host_by_name(name) == nullptr,
166              "Cannot create a VM named %s: this name is already used by an host or a VM", name);
167
168   msg_vm_t vm = new simgrid::s4u::VirtualMachine(name, pm, coreAmount);
169   s_vm_params_t params;
170   memset(&params, 0, sizeof(params));
171   vm->setParameters(&params);
172   return vm;
173 }
174
175 /** @brief Start a vm (i.e., boot the guest operating system)
176  *  @ingroup msg_VMs
177  *
178  *  If the VM cannot be started (because of memory over-provisioning), an exception is generated.
179  */
180 void MSG_vm_start(msg_vm_t vm)
181 {
182   vm->start();
183   if (TRACE_msg_vm_is_enabled()) {
184     simgrid::instr::StateType* state = simgrid::instr::Container::byName(vm->getName())->getState("MSG_VM_STATE");
185     state->addEntityValue("start", "0 0 1"); // start is blue
186     state->pushEvent("start");
187   }
188 }
189
190 /** @brief Immediately suspend the execution of all processes within the given VM.
191  *  @ingroup msg_VMs
192  *
193  * This function stops the execution of the VM. All the processes on this VM
194  * will pause. The state of the VM is preserved. We can later resume it again.
195  *
196  * No suspension cost occurs.
197  */
198 void MSG_vm_suspend(msg_vm_t vm)
199 {
200   vm->suspend();
201   if (TRACE_msg_vm_is_enabled()) {
202     simgrid::instr::StateType* state = simgrid::instr::Container::byName(vm->getName())->getState("MSG_VM_STATE");
203     state->addEntityValue("suspend", "1 0 0"); // suspend is red
204     state->pushEvent("suspend");
205   }
206 }
207
208 /** @brief Resume the execution of the VM. All processes on the VM run again.
209  *  @ingroup msg_VMs
210  *
211  * No resume cost occurs.
212  */
213 void MSG_vm_resume(msg_vm_t vm)
214 {
215   vm->resume();
216   if (TRACE_msg_vm_is_enabled())
217     simgrid::instr::Container::byName(vm->getName())->getState("MSG_VM_STATE")->popEvent();
218 }
219
220 /** @brief Immediately kills all processes within the given VM.
221  *  @ingroup msg_VMs
222  *
223  * Any memory that they allocated will be leaked, unless you used #MSG_process_on_exit().
224  *
225  * No extra delay occurs. If you want to simulate this too, you want to use a #MSG_process_sleep().
226  */
227 void MSG_vm_shutdown(msg_vm_t vm)
228 {
229   vm->shutdown();
230 }
231
232 /** @brief Destroy a VM. Destroy the VM object from the simulation.
233  *  @ingroup msg_VMs
234  */
235 void MSG_vm_destroy(msg_vm_t vm)
236 {
237   if (vm->isMigrating())
238     THROWF(vm_error, 0, "Cannot destroy VM '%s', which is migrating.", vm->getCname());
239
240   /* First, terminate all processes on the VM if necessary */
241   vm->shutdown();
242
243   /* Then, destroy the VM object */
244   vm->destroy();
245
246   if (TRACE_msg_vm_is_enabled()) {
247     container_t container = simgrid::instr::Container::byName(vm->getName());
248     container->removeFromParent();
249     delete container;
250   }
251 }
252
253 static std::string get_mig_process_tx_name(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm)
254 {
255   return std::string("__pr_mig_tx:") + vm->getCname() + "(" + src_pm->getCname() + "-" + dst_pm->getCname() + ")";
256 }
257
258 static std::string get_mig_process_rx_name(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm)
259 {
260   return std::string("__pr_mig_rx:") + vm->getCname() + "(" + src_pm->getCname() + "-" + dst_pm->getCname() + ")";
261 }
262
263 static std::string get_mig_task_name(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm, int stage)
264 {
265   return std::string("__task_mig_stage") + std::to_string(stage) + ":" + vm->getCname() + "(" + src_pm->getCname() +
266          "-" + dst_pm->getCname() + ")";
267 }
268
269 struct migration_session {
270   msg_vm_t vm;
271   msg_host_t src_pm;
272   msg_host_t dst_pm;
273
274   /* The miration_rx process uses mbox_ctl to let the caller of do_migration()
275    * know the completion of the migration. */
276   std::string mbox_ctl;
277   /* The migration_rx and migration_tx processes use mbox to transfer migration data. */
278   std::string mbox;
279 };
280
281 static int migration_rx_fun(int argc, char *argv[])
282 {
283   XBT_DEBUG("mig: rx_start");
284
285   // The structure has been created in the do_migration function and should only be freed in the same place ;)
286   migration_session* ms = static_cast<migration_session*>(MSG_process_get_data(MSG_process_self()));
287
288   bool received_finalize = false;
289
290   std::string finalize_task_name = get_mig_task_name(ms->vm, ms->src_pm, ms->dst_pm, 3);
291   while (not received_finalize) {
292     msg_task_t task = nullptr;
293     int ret         = MSG_task_recv(&task, ms->mbox.c_str());
294
295     if (ret != MSG_OK) {
296       // An error occurred, clean the code and return
297       // The owner did not change, hence the task should be only destroyed on the other side
298       return 0;
299     }
300
301     if (finalize_task_name == task->name)
302       received_finalize = 1;
303
304     MSG_task_destroy(task);
305   }
306
307   // Here Stage 1, 2  and 3 have been performed.
308   // Hence complete the migration
309
310   // Copy the reference to the vm (if SRC crashes now, do_migration will free ms)
311   // This is clearly ugly but I (Adrien) need more time to do something cleaner (actually we should copy the whole ms
312   // structure at the beginning and free it at the end of each function)
313   simgrid::s4u::VirtualMachine* vm = ms->vm;
314   msg_host_t dst_pm                = ms->dst_pm;
315
316   // Make sure that we cannot get interrupted between the migrate and the resume to not end in an inconsistent state
317   simgrid::simix::kernelImmediate([vm, dst_pm]() {
318     /* Update the vm location */
319     /* precopy migration makes the VM temporally paused */
320     xbt_assert(vm->getState() == SURF_VM_STATE_SUSPENDED);
321
322     /* Update the vm location and resume it */
323     vm->pimpl_vm_->setPm(dst_pm);
324     vm->resume();
325   });
326
327
328   // Now the VM is running on the new host (the migration is completed) (even if the SRC crash)
329   vm->pimpl_vm_->isMigrating = false;
330   XBT_DEBUG("VM(%s) moved from PM(%s) to PM(%s)", ms->vm->getCname(), ms->src_pm->getCname(), ms->dst_pm->getCname());
331
332   if (TRACE_msg_vm_is_enabled()) {
333     static long long int counter = 0;
334     std::string key              = std::to_string(counter);
335     counter++;
336
337     // start link
338     container_t msg = simgrid::instr::Container::byName(vm->getName());
339     simgrid::instr::Container::getRoot()->getLink("MSG_VM_LINK")->startEvent(msg, "M", key);
340
341     // destroy existing container of this vm
342     container_t existing_container = simgrid::instr::Container::byName(vm->getName());
343     existing_container->removeFromParent();
344     delete existing_container;
345
346     // create new container on the new_host location
347     new simgrid::instr::Container(vm->getCname(), "MSG_VM", simgrid::instr::Container::byName(ms->dst_pm->getName()));
348
349     // end link
350     msg  = simgrid::instr::Container::byName(vm->getName());
351     simgrid::instr::Container::getRoot()->getLink("MSG_VM_LINK")->endEvent(msg, "M", key);
352   }
353
354   // Inform the SRC that the migration has been correctly performed
355   std::string task_name = get_mig_task_name(ms->vm, ms->src_pm, ms->dst_pm, 4);
356   msg_task_t task       = MSG_task_create(task_name.c_str(), 0, 0, nullptr);
357   msg_error_t ret       = MSG_task_send(task, ms->mbox_ctl.c_str());
358   if(ret == MSG_HOST_FAILURE){
359     // The DST has crashed, this is a problem has the VM since we are not sure whether SRC is considering that the VM
360     // has been correctly migrated on the DST node
361     // TODO What does it mean ? What should we do ?
362     MSG_task_destroy(task);
363   } else if(ret == MSG_TRANSFER_FAILURE){
364     // The SRC has crashed, this is not a problem has the VM has been correctly migrated on the DST node
365     MSG_task_destroy(task);
366   }
367
368   XBT_DEBUG("mig: rx_done");
369   return 0;
370 }
371
372 static sg_size_t send_migration_data(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm, sg_size_t size,
373                                      const std::string& mbox, int stage, int stage2_round, double mig_speed,
374                                      double timeout)
375 {
376   sg_size_t sent = 0;
377   std::string task_name = get_mig_task_name(vm, src_pm, dst_pm, stage);
378   msg_task_t task       = MSG_task_create(task_name.c_str(), 0, static_cast<double>(size), nullptr);
379
380   double clock_sta = MSG_get_clock();
381
382   msg_error_t ret;
383   if (mig_speed > 0)
384     ret = MSG_task_send_with_timeout_bounded(task, mbox.c_str(), timeout, mig_speed);
385   else
386     ret = MSG_task_send(task, mbox.c_str());
387
388   if (ret == MSG_OK) {
389     sent = size;
390   } else if (ret == MSG_TIMEOUT) {
391     sg_size_t remaining = static_cast<sg_size_t>(MSG_task_get_remaining_communication(task));
392     sent = size - remaining;
393     XBT_VERB("timeout (%lf s) in sending_migration_data, remaining %llu bytes of %llu", timeout, remaining, size);
394   }
395
396   /* FIXME: why try-and-catch is used here? */
397   if(ret == MSG_HOST_FAILURE){
398     XBT_DEBUG("SRC host failed during migration of %s (stage %d)", vm->getCname(), stage);
399     MSG_task_destroy(task);
400     THROWF(host_error, 0, "SRC host failed during migration of %s (stage %d)", vm->getCname(), stage);
401   }else if(ret == MSG_TRANSFER_FAILURE){
402     XBT_DEBUG("DST host failed during migration of %s (stage %d)", vm->getCname(), stage);
403     MSG_task_destroy(task);
404     THROWF(host_error, 0, "DST host failed during migration of %s (stage %d)", vm->getCname(), stage);
405   }
406
407   double clock_end = MSG_get_clock();
408   double duration = clock_end - clock_sta;
409   double actual_speed = size / duration;
410
411   if (stage == 2)
412     XBT_DEBUG("mig-stage%d.%d: sent %llu duration %f actual_speed %f (target %f)", stage, stage2_round, size, duration,
413               actual_speed, mig_speed);
414   else
415     XBT_DEBUG("mig-stage%d: sent %llu duration %f actual_speed %f (target %f)", stage, size, duration, actual_speed,
416               mig_speed);
417
418   return sent;
419 }
420
421 static sg_size_t get_updated_size(double computed, double dp_rate, double dp_cap)
422 {
423   double updated_size = computed * dp_rate;
424   XBT_DEBUG("updated_size %f dp_rate %f", updated_size, dp_rate);
425   if (updated_size > dp_cap) {
426     updated_size = dp_cap;
427   }
428
429   return static_cast<sg_size_t>(updated_size);
430 }
431
432 static int migration_tx_fun(int argc, char *argv[])
433 {
434   XBT_DEBUG("mig: tx_start");
435
436   // Note that the ms structure has been allocated in do_migration and hence should be freed in the same function ;)
437   migration_session* ms = static_cast<migration_session*>(MSG_process_get_data(MSG_process_self()));
438
439   double host_speed = ms->vm->getPm()->getSpeed();
440   s_vm_params_t params;
441   ms->vm->getParameters(&params);
442   const sg_size_t ramsize   = ms->vm->getRamsize();
443   const double dp_rate      = host_speed ? (params.mig_speed * params.dp_intensity) / host_speed : 1;
444   const double dp_cap       = params.dp_cap;
445   const double mig_speed    = params.mig_speed;
446   double max_downtime       = params.max_downtime;
447
448   double mig_timeout = 10000000.0;
449   bool skip_stage2   = false;
450
451   size_t remaining_size = ramsize;
452   size_t threshold      = 0.0;
453
454   /* check parameters */
455   if (ramsize == 0)
456     XBT_WARN("migrate a VM, but ramsize is zero");
457
458   if (max_downtime <= 0) {
459     XBT_WARN("use the default max_downtime value 30ms");
460     max_downtime = 0.03;
461   }
462
463   /* Stage1: send all memory pages to the destination. */
464   XBT_DEBUG("mig-stage1: remaining_size %zu", remaining_size);
465   sg_vm_start_dirty_page_tracking(ms->vm);
466
467   double computed_during_stage1 = 0;
468   double clock_prev_send        = MSG_get_clock();
469
470   try {
471     /* At stage 1, we do not need timeout. We have to send all the memory pages even though the duration of this
472      * transfer exceeds the timeout value. */
473     XBT_VERB("Stage 1: Gonna send %llu bytes", ramsize);
474     sg_size_t sent = send_migration_data(ms->vm, ms->src_pm, ms->dst_pm, ramsize, ms->mbox, 1, 0, mig_speed, -1);
475     remaining_size -= sent;
476     computed_during_stage1 = sg_vm_lookup_computed_flops(ms->vm);
477
478     if (sent < ramsize) {
479       XBT_VERB("mig-stage1: timeout, force moving to stage 3");
480       skip_stage2 = true;
481     } else if (sent > ramsize)
482       XBT_CRITICAL("bug");
483
484   } catch (xbt_ex& e) {
485     // hostfailure (if you want to know whether this is the SRC or the DST check directly in send_migration_data code)
486     // Stop the dirty page tracking an return (there is no memory space to release)
487     sg_vm_stop_dirty_page_tracking(ms->vm);
488     return 0;
489   }
490
491   double clock_post_send = MSG_get_clock();
492   mig_timeout -= (clock_post_send - clock_prev_send);
493   if (mig_timeout < 0) {
494     XBT_VERB("The duration of stage 1 exceeds the timeout value, skip stage 2");
495     skip_stage2 = true;
496   }
497
498   /* estimate bandwidth */
499   double bandwidth = ramsize / (clock_post_send - clock_prev_send);
500   threshold        = bandwidth * max_downtime;
501   XBT_DEBUG("actual bandwidth %f (MB/s), threshold %zu", bandwidth / 1024 / 1024, threshold);
502
503   /* Stage2: send update pages iteratively until the size of remaining states becomes smaller than threshold value. */
504   if (not skip_stage2) {
505
506     int stage2_round = 0;
507     for (;;) {
508
509       sg_size_t updated_size = 0;
510       if (stage2_round == 0) {
511         /* just after stage1, nothing has been updated. But, we have to send the data updated during stage1 */
512         updated_size = get_updated_size(computed_during_stage1, dp_rate, dp_cap);
513       } else {
514         double computed = sg_vm_lookup_computed_flops(ms->vm);
515         updated_size    = get_updated_size(computed, dp_rate, dp_cap);
516       }
517
518       XBT_DEBUG("mig-stage 2:%d updated_size %llu computed_during_stage1 %f dp_rate %f dp_cap %f", stage2_round,
519                 updated_size, computed_during_stage1, dp_rate, dp_cap);
520
521       /* Check whether the remaining size is below the threshold value. If so, move to stage 3. */
522       remaining_size += updated_size;
523       XBT_DEBUG("mig-stage2.%d: remaining_size %zu (%s threshold %zu)", stage2_round, remaining_size,
524                 (remaining_size < threshold) ? "<" : ">", threshold);
525       if (remaining_size < threshold)
526         break;
527
528       sg_size_t sent         = 0;
529       double clock_prev_send = MSG_get_clock();
530       try {
531         XBT_DEBUG("Stage 2, gonna send %llu", updated_size);
532         sent = send_migration_data(ms->vm, ms->src_pm, ms->dst_pm, updated_size, ms->mbox, 2, stage2_round, mig_speed,
533                                    mig_timeout);
534       } catch (xbt_ex& e) {
535         // hostfailure (if you want to know whether this is the SRC or the DST check directly in send_migration_data
536         // code)
537         // Stop the dirty page tracking an return (there is no memory space to release)
538         sg_vm_stop_dirty_page_tracking(ms->vm);
539         return 0;
540       }
541       double clock_post_send = MSG_get_clock();
542
543       if (sent == updated_size) {
544         /* timeout did not happen */
545         double bandwidth = updated_size / (clock_post_send - clock_prev_send);
546         threshold        = bandwidth * max_downtime;
547         XBT_DEBUG("actual bandwidth %f, threshold %zu", bandwidth / 1024 / 1024, threshold);
548         remaining_size -= sent;
549         stage2_round += 1;
550         mig_timeout -= (clock_post_send - clock_prev_send);
551         xbt_assert(mig_timeout > 0);
552
553       } else if (sent < updated_size) {
554         /* When timeout happens, we move to stage 3. The size of memory pages
555          * updated before timeout must be added to the remaining size. */
556         XBT_VERB("mig-stage2.%d: timeout, force moving to stage 3. sent %llu / %llu, eta %lf", stage2_round, sent,
557                  updated_size, (clock_post_send - clock_prev_send));
558         remaining_size -= sent;
559
560         double computed = sg_vm_lookup_computed_flops(ms->vm);
561         updated_size    = get_updated_size(computed, dp_rate, dp_cap);
562         remaining_size += updated_size;
563         break;
564       } else
565         XBT_CRITICAL("bug");
566     }
567   }
568
569   /* Stage3: stop the VM and copy the rest of states. */
570   XBT_DEBUG("mig-stage3: remaining_size %zu", remaining_size);
571   simgrid::vm::VirtualMachineImpl* pimpl = ms->vm->pimpl_vm_;
572   pimpl->setState(SURF_VM_STATE_RUNNING); // FIXME: this bypass of the checks in suspend() is not nice
573   pimpl->isMigrating = false;             // FIXME: this bypass of the checks in suspend() is not nice
574   pimpl->suspend(SIMIX_process_self());
575   sg_vm_stop_dirty_page_tracking(ms->vm);
576
577   try {
578     XBT_DEBUG("Stage 3: Gonna send %zu bytes", remaining_size);
579     send_migration_data(ms->vm, ms->src_pm, ms->dst_pm, remaining_size, ms->mbox, 3, 0, mig_speed, -1);
580   }
581   catch(xbt_ex& e) {
582     //hostfailure (if you want to know whether this is the SRC or the DST check directly in send_migration_data code)
583     // Stop the dirty page tracking an return (there is no memory space to release)
584     ms->vm->resume();
585     return 0;
586   }
587
588   // At that point the Migration is considered valid for the SRC node but remind that the DST side should relocate
589   // effectively the VM on the DST node.
590   XBT_DEBUG("mig: tx_done");
591
592   return 0;
593 }
594
595 /** @brief Migrate the VM to the given host.
596  *  @ingroup msg_VMs
597  */
598 void MSG_vm_migrate(msg_vm_t vm, msg_host_t dst_pm)
599 {
600   /* some thoughts:
601    * - One approach is ...
602    *   We first create a new VM (i.e., destination VM) on the destination   physical host. The destination VM will
603    *   receive the state of the source
604    *   VM over network. We will finally destroy the source VM.
605    *   - This behavior is similar to the way of migration in the real world.
606    *     Even before a migration is completed, we will see a destination VM, consuming resources.
607    *   - We have to relocate all processes. The existing process migration code will work for this?
608    *   - The name of the VM is a somewhat unique ID in the code. It is tricky for the destination VM?
609    *
610    * - Another one is ...
611    *   We update the information of the given VM to place it to the destination physical host.
612    *
613    * The second one would be easier.
614    */
615
616   msg_host_t src_pm = vm->getPm();
617
618   if (src_pm->isOff())
619     THROWF(vm_error, 0, "Cannot migrate VM '%s' from host '%s', which is offline.", vm->getCname(), src_pm->getCname());
620   if (dst_pm->isOff())
621     THROWF(vm_error, 0, "Cannot migrate VM '%s' to host '%s', which is offline.", vm->getCname(), dst_pm->getCname());
622   if (not MSG_vm_is_running(vm))
623     THROWF(vm_error, 0, "Cannot migrate VM '%s' that is not running yet.", vm->getCname());
624   if (vm->isMigrating())
625     THROWF(vm_error, 0, "Cannot migrate VM '%s' that is already migrating.", vm->getCname());
626
627   vm->pimpl_vm_->isMigrating = true;
628
629   migration_session ms;
630   ms.vm     = vm;
631   ms.src_pm = src_pm;
632   ms.dst_pm = dst_pm;
633
634   /* We have two mailboxes. mbox is used to transfer migration data between source and destination PMs. mbox_ctl is used
635    * to detect the completion of a migration. The names of these mailboxes must not conflict with others. */
636   ms.mbox_ctl =
637       simgrid::xbt::string_printf("__mbox_mig_ctl:%s(%s-%s)", vm->getCname(), src_pm->getCname(), dst_pm->getCname());
638   ms.mbox = simgrid::xbt::string_printf("__mbox_mig_src_dst:%s(%s-%s)", vm->getCname(), src_pm->getCname(),
639                                         dst_pm->getCname());
640
641   std::string pr_rx_name = get_mig_process_rx_name(vm, src_pm, dst_pm);
642   std::string pr_tx_name = get_mig_process_tx_name(vm, src_pm, dst_pm);
643
644   MSG_process_create(pr_rx_name.c_str(), migration_rx_fun, &ms, dst_pm);
645
646   MSG_process_create(pr_tx_name.c_str(), migration_tx_fun, &ms, src_pm);
647
648   /* wait until the migration have finished or on error has occurred */
649   XBT_DEBUG("wait for reception of the final ACK (i.e. migration has been correctly performed");
650   msg_task_t task = nullptr;
651   msg_error_t ret = MSG_task_receive(&task, ms.mbox_ctl.c_str());
652
653   vm->pimpl_vm_->isMigrating = false;
654
655   if (ret == MSG_HOST_FAILURE) {
656     // Note that since the communication failed, the owner did not change and the task should be destroyed on the
657     // other side. Hence, just throw the execption
658     XBT_ERROR("SRC crashes, throw an exception (m-control)");
659     // MSG_process_kill(tx_process); // Adrien, I made a merge on Nov 28th 2014, I'm not sure whether this line is
660     // required or not
661     THROWF(host_error, 0, "Source host '%s' failed during the migration of VM '%s'.", src_pm->getCname(),
662            vm->getCname());
663   } else if ((ret == MSG_TRANSFER_FAILURE) || (ret == MSG_TIMEOUT)) {
664     // MSG_TIMEOUT here means that MSG_host_is_avail() returned false.
665     XBT_ERROR("DST crashes, throw an exception (m-control)");
666     THROWF(host_error, 0, "Destination host '%s' failed during the migration of VM '%s'.", dst_pm->getCname(),
667            vm->getCname());
668   }
669
670   xbt_assert(get_mig_task_name(vm, src_pm, dst_pm, 4) == task->name);
671   MSG_task_destroy(task);
672 }
673 }