Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
8f34a3cfca72a01150cac8529f21f735084ab3a9
[simgrid.git] / src / msg / msg_vm.cpp
1 /* Copyright (c) 2012-2015. 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 "src/plugins/vm/VirtualMachineImpl.hpp"
15 #include <simgrid/s4u/VirtualMachine.hpp>
16 #include <simgrid/s4u/host.hpp>
17
18 #include "msg_private.h"
19 #include "xbt/sysdep.h"
20 #include "xbt/log.h"
21 #include "simgrid/host.h"
22
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(msg_vm, msg, "Cloud-oriented parts of the MSG API");
24
25
26 /* **** ******** GENERAL ********* **** */
27
28 /** \ingroup m_vm_management
29  * \brief Set the parameters of a given host
30  *
31  * \param vm a vm
32  * \param params a parameter object
33  */
34 void MSG_vm_set_params(msg_vm_t vm, vm_params_t params)
35 {
36   static_cast<simgrid::s4u::VirtualMachine*>(vm)->setParameters(params);
37 }
38
39 /** \ingroup m_vm_management
40  * \brief Get the parameters of a given host
41  *
42  * \param host a host
43  * \param params a prameter object
44  */
45 void MSG_vm_get_params(msg_vm_t vm, vm_params_t params)
46 {
47   static_cast<simgrid::s4u::VirtualMachine*>(vm)->parameters(params);
48 }
49
50 /** \ingroup msg_vm_management
51  * \brief Finds a msg_vm_t using its name.
52  *
53  * This is a name directory service
54  * \param name the name of a vm.
55  * \return the corresponding vm
56  *
57  * Please note that a VM is a specific host. Hence, you should give a different name for each VM/PM.
58  */
59 msg_vm_t MSG_vm_get_by_name(const char *name)
60 {
61   return MSG_host_by_name(name);
62 }
63
64 /** \ingroup m_vm_management
65  *
66  * \brief Return the name of the #msg_host_t.
67  *
68  * This functions checks whether \a host is a valid pointer or not and return its name.
69  */
70 const char *MSG_vm_get_name(msg_vm_t vm)
71 {
72   return MSG_host_get_name(vm);
73 }
74
75 /* **** Check state of a VM **** */
76 static inline int __MSG_vm_is_state(msg_vm_t vm, e_surf_vm_state_t state)
77 {
78   return simcall_vm_get_state(vm) == 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 static_cast<simgrid::s4u::VirtualMachine*>(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 /** @brief Returns whether the given VM is being saved (FIXME: live saving or not?).
114  *  @ingroup msg_VMs
115  */
116 int MSG_vm_is_saving(msg_vm_t vm)
117 {
118   return __MSG_vm_is_state(vm, SURF_VM_STATE_SAVING);
119 }
120
121 /** @brief Returns whether the given VM has been saved, not running.
122  *  @ingroup msg_VMs
123  */
124 int MSG_vm_is_saved(msg_vm_t vm)
125 {
126   return __MSG_vm_is_state(vm, SURF_VM_STATE_SAVED);
127 }
128
129 /** @brief Returns whether the given VM is being restored, not running.
130  *  @ingroup msg_VMs
131  */
132 int MSG_vm_is_restoring(msg_vm_t vm)
133 {
134   return __MSG_vm_is_state(vm, SURF_VM_STATE_RESTORING);
135 }
136
137 /* **** ******** MSG vm actions ********* **** */
138 /** @brief Create a new VM with specified parameters.
139  *  @ingroup msg_VMs*
140  *  @param pm        Physical machine that will host the VM
141  *  @param name      [TODO]
142  *  @param ncpus     [TODO]
143  *  @param ramsize   [TODO]
144  *  @param net_cap   Maximal bandwidth that the VM can consume (in MByte/s)
145  *  @param disk_path (unused) Path to the image that boots
146  *  @param disksize  (unused) will represent the size of the VM (will be used during migrations)
147  *  @param mig_netspeed Amount of Mbyte/s allocated to the migration (cannot be larger than net_cap). Use 0 if unsure.
148  *  @param dp_intensity Dirty page percentage according to migNetSpeed, [0-100]. Use 0 if unsure.
149  */
150 msg_vm_t MSG_vm_create(msg_host_t pm, const char *name, int ncpus, int ramsize, int net_cap, char *disk_path,
151                        int disksize, int mig_netspeed, int dp_intensity)
152 {
153   /* For the moment, intensity_rate is the percentage against the migration
154    * bandwidth */
155   double host_speed = MSG_host_get_speed(pm);
156   double update_speed = ((double)dp_intensity/100) * mig_netspeed;
157
158   msg_vm_t vm = MSG_vm_create_core(pm, name);
159   s_vm_params_t params;
160   memset(&params, 0, sizeof(params));
161   params.ramsize = (sg_size_t)ramsize * 1024 * 1024;
162   //params.overcommit = 0;
163   params.devsize = 0;
164   params.skip_stage2 = 0;
165   params.max_downtime = 0.03;
166   params.dp_rate = (update_speed * 1024 * 1024) / host_speed;
167   params.dp_cap = params.ramsize * 0.9; // assume working set memory is 90% of ramsize
168   params.mig_speed = (double)mig_netspeed * 1024 * 1024; // mig_speed
169
170   //XBT_INFO("dp rate %f migspeed : %f intensity mem : %d, updatespeed %f, hostspeed %f",params.dp_rate,
171   //         params.mig_speed, dp_intensity, update_speed, host_speed);
172   static_cast<simgrid::s4u::VirtualMachine*>(vm)->setParameters(&params);
173
174   return vm;
175 }
176
177 /** @brief Create a new VM object. The VM is not yet started. The resource of the VM is allocated upon MSG_vm_start().
178  *  @ingroup msg_VMs*
179  *
180  * A VM is treated as a host. The name of the VM must be unique among all hosts.
181  */
182 msg_vm_t MSG_vm_create_core(msg_host_t ind_pm, const char *name)
183 {
184   /* make sure the VM of the same name does not exit */
185   {
186     simgrid::s4u::Host* ind_host_tmp = sg_host_by_name(name);
187     if (ind_host_tmp != nullptr && sg_host_simix(ind_host_tmp) != nullptr) {
188       XBT_ERROR("host %s already exits", name);
189       return nullptr;
190     }
191   }
192
193   /* Note: ind_vm and vm_workstation point to the same elm object. */
194   /* Ask the SIMIX layer to create the surf vm resource */
195   sg_host_t ind_vm_workstation = simcall_vm_create(name, ind_pm);
196
197   msg_vm_t ind_vm = (msg_vm_t) __MSG_host_create(ind_vm_workstation);
198
199   XBT_DEBUG("A new VM (%s) has been created", name);
200
201   TRACE_msg_vm_create(name, ind_pm);
202
203   return ind_vm;
204 }
205
206 /** @brief Destroy a VM. Destroy the VM object from the simulation.
207  *  @ingroup msg_VMs
208  */
209 void MSG_vm_destroy(msg_vm_t vm)
210 {
211   if (MSG_vm_is_migrating(vm))
212     THROWF(vm_error, 0, "VM(%s) is migrating", sg_host_get_name(vm));
213
214   /* First, terminate all processes on the VM if necessary */
215   if (MSG_vm_is_running(vm))
216       simcall_vm_shutdown(vm);
217
218   if (!MSG_vm_is_created(vm)) {
219     XBT_CRITICAL("shutdown the given VM before destroying it");
220     DIE_IMPOSSIBLE;
221   }
222
223   /* Then, destroy the VM object */
224   simcall_vm_destroy(vm);
225
226   TRACE_msg_vm_end(vm);
227 }
228
229 /** @brief Start a vm (i.e., boot the guest operating system)
230  *  @ingroup msg_VMs
231  *
232  *  If the VM cannot be started, an exception is generated.
233  */
234 void MSG_vm_start(msg_vm_t vm)
235 {
236   simcall_vm_start(vm);
237
238   TRACE_msg_vm_start(vm);
239 }
240
241 /** @brief Immediately kills all processes within the given VM. Any memory that they allocated will be leaked.
242  *  @ingroup msg_VMs
243  *
244  * FIXME: No extra delay occurs. If you want to simulate this too, you want to use a #MSG_process_sleep() or something.
245  *        I'm not quite sure.
246  */
247 void MSG_vm_shutdown(msg_vm_t vm)
248 {
249   /* msg_vm_t equals to msg_host_t */
250   simcall_vm_shutdown(vm);
251
252   // TRACE_msg_vm_(vm);
253 }
254
255 /* We have two mailboxes. mbox is used to transfer migration data between source and destination PMs. mbox_ctl is used
256  * to detect the completion of a migration. The names of these mailboxes must not conflict with others. */
257 static inline char *get_mig_mbox_src_dst(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm)
258 {
259   const char *vm_name = sg_host_get_name(vm);
260   const char *src_pm_name = sg_host_get_name(src_pm);
261   const char *dst_pm_name = sg_host_get_name(dst_pm);
262
263   return bprintf("__mbox_mig_src_dst:%s(%s-%s)", vm_name, src_pm_name, dst_pm_name);
264 }
265
266 static inline char *get_mig_mbox_ctl(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm)
267 {
268   const char *vm_name = sg_host_get_name(vm);
269   const char *src_pm_name = sg_host_get_name(src_pm);
270   const char *dst_pm_name = sg_host_get_name(dst_pm);
271
272   return bprintf("__mbox_mig_ctl:%s(%s-%s)", vm_name, src_pm_name, dst_pm_name);
273 }
274
275 static inline char *get_mig_process_tx_name(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm)
276 {
277   const char *vm_name = sg_host_get_name(vm);
278   const char *src_pm_name = sg_host_get_name(src_pm);
279   const char *dst_pm_name = sg_host_get_name(dst_pm);
280
281   return bprintf("__pr_mig_tx:%s(%s-%s)", vm_name, src_pm_name, dst_pm_name);
282 }
283
284 static inline char *get_mig_process_rx_name(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm)
285 {
286   const char *vm_name = sg_host_get_name(vm);
287   const char *src_pm_name = sg_host_get_name(src_pm);
288   const char *dst_pm_name = sg_host_get_name(dst_pm);
289
290   return bprintf("__pr_mig_rx:%s(%s-%s)", vm_name, src_pm_name, dst_pm_name);
291 }
292
293 static inline char *get_mig_task_name(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm, int stage)
294 {
295   const char *vm_name = sg_host_get_name(vm);
296   const char *src_pm_name = sg_host_get_name(src_pm);
297   const char *dst_pm_name = sg_host_get_name(dst_pm);
298
299   return bprintf("__task_mig_stage%d:%s(%s-%s)", stage, vm_name, src_pm_name, dst_pm_name);
300 }
301
302 struct migration_session {
303   msg_vm_t vm;
304   msg_host_t src_pm;
305   msg_host_t dst_pm;
306
307   /* The miration_rx process uses mbox_ctl to let the caller of do_migration()
308    * know the completion of the migration. */
309   char *mbox_ctl;
310   /* The migration_rx and migration_tx processes use mbox to transfer migration data. */
311   char *mbox;
312 };
313
314 static int migration_rx_fun(int argc, char *argv[])
315 {
316   XBT_DEBUG("mig: rx_start");
317
318   // The structure has been created in the do_migration function and should only be freed in the same place ;)
319   struct migration_session *ms = (migration_session *) MSG_process_get_data(MSG_process_self());
320
321   s_vm_params_t params;
322   static_cast<simgrid::s4u::VirtualMachine*>(ms->vm)->parameters(&params);
323
324   int need_exit = 0;
325
326   char *finalize_task_name = get_mig_task_name(ms->vm, ms->src_pm, ms->dst_pm, 3);
327
328   int ret = 0;
329   for (;;) {
330     msg_task_t task = nullptr;
331     ret = MSG_task_recv(&task, ms->mbox);
332     {
333       if (ret != MSG_OK) {
334         // An error occurred, clean the code and return
335         // The owner did not change, hence the task should be only destroyed on the other side
336         xbt_free(finalize_task_name);
337         return 0;
338       }
339     }
340
341     if (strcmp(task->name, finalize_task_name) == 0)
342       need_exit = 1;
343
344     MSG_task_destroy(task);
345
346     if (need_exit)
347       break;
348   }
349
350   // Here Stage 1, 2  and 3 have been performed.
351   // Hence complete the migration
352
353   // Copy the reference to the vm (if SRC crashes now, do_migration will free ms)
354   // This is clearly ugly but I (Adrien) need more time to do something cleaner (actually we should copy the whole ms
355   // structure at the beginning and free it at the end of each function)
356   simgrid::s4u::VirtualMachine* vm = static_cast<simgrid::s4u::VirtualMachine*>(ms->vm);
357   msg_host_t src_pm                = ms->src_pm;
358   msg_host_t dst_pm                = ms->dst_pm;
359
360   // TODO: we have an issue, if the DST node is turning off during the three next calls, then the VM is in an
361   // inconsistent
362   //       state. I should check with Takahiro in order to make this portion of code atomic
363   //
364   //  /* Update the vm location */
365   //  simcall_vm_migrate(vm, dst_pm);
366   //
367   //  /* Resume the VM */
368   //  simcall_vm_resume(vm);
369   //
370   simcall_vm_migratefrom_resumeto(vm, src_pm, dst_pm);
371
372   {
373    // Now the VM is running on the new host (the migration is completed) (even if the SRC crash)
374    static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_)->isMigrating = false;
375    XBT_DEBUG("VM(%s) moved from PM(%s) to PM(%s)", sg_host_get_name(ms->vm), sg_host_get_name(ms->src_pm),
376              sg_host_get_name(ms->dst_pm));
377    TRACE_msg_vm_change_host(ms->vm, ms->src_pm, ms->dst_pm);
378   }
379   // Inform the SRC that the migration has been correctly performed
380   {
381     char *task_name = get_mig_task_name(ms->vm, ms->src_pm, ms->dst_pm, 4);
382     msg_task_t task = MSG_task_create(task_name, 0, 0, nullptr);
383     msg_error_t ret = MSG_task_send(task, ms->mbox_ctl);
384     // xbt_assert(ret == MSG_OK);
385     if(ret == MSG_HOST_FAILURE){
386       // The DST has crashed, this is a problem has the VM since we are not sure whether SRC is considering that the VM
387       // has been correctly migrated on the DST node
388       // TODO What does it mean ? What should we do ?
389       MSG_task_destroy(task);
390     } else if(ret == MSG_TRANSFER_FAILURE){
391       // The SRC has crashed, this is not a problem has the VM has been correctly migrated on the DST node
392       MSG_task_destroy(task);
393     }
394     xbt_free(task_name);
395   }
396
397   xbt_free(finalize_task_name);
398
399   XBT_DEBUG("mig: rx_done");
400   return 0;
401 }
402
403 static void reset_dirty_pages(msg_vm_t vm)
404 {
405   simgrid::surf::VirtualMachineImpl* pimpl = static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_);
406
407   char *key = nullptr;
408   xbt_dict_cursor_t cursor = nullptr;
409   dirty_page_t dp = nullptr;
410   if (!pimpl->dp_objs)
411     return;
412   xbt_dict_foreach (pimpl->dp_objs, cursor, key, dp) {
413     double remaining = MSG_task_get_flops_amount(dp->task);
414     dp->prev_clock = MSG_get_clock();
415     dp->prev_remaining = remaining;
416
417     // XBT_INFO("%s@%s remaining %f", key, sg_host_name(vm), remaining);
418   }
419 }
420
421 static void start_dirty_page_tracking(msg_vm_t vm)
422 {
423   simgrid::surf::VirtualMachineImpl* pimpl = static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_);
424   pimpl->dp_enabled                        = 1;
425
426   reset_dirty_pages(vm);
427 }
428
429 static void stop_dirty_page_tracking(msg_vm_t vm)
430 {
431   simgrid::surf::VirtualMachineImpl* pimpl = static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_);
432   pimpl->dp_enabled                        = 0;
433 }
434
435 static double get_computed(char *key, msg_vm_t vm, dirty_page_t dp, double remaining, double clock)
436 {
437   double computed = dp->prev_remaining - remaining;
438   double duration = clock - dp->prev_clock;
439
440   XBT_DEBUG("%s@%s: computed %f ops (remaining %f -> %f) in %f secs (%f -> %f)",
441       key, sg_host_get_name(vm), computed, dp->prev_remaining, remaining, duration, dp->prev_clock, clock);
442
443   return computed;
444 }
445
446 static double lookup_computed_flop_counts(msg_vm_t vm, int stage_for_fancy_debug, int stage2_round_for_fancy_debug)
447 {
448   simgrid::surf::VirtualMachineImpl* pimpl = static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_);
449   double total = 0;
450
451   char *key = nullptr;
452   xbt_dict_cursor_t cursor = nullptr;
453   dirty_page_t dp = nullptr;
454   xbt_dict_foreach (pimpl->dp_objs, cursor, key, dp) {
455     double remaining = MSG_task_get_flops_amount(dp->task);
456
457     double clock = MSG_get_clock();
458
459     // total += calc_updated_pages(key, vm, dp, remaining, clock);
460     total += get_computed(key, vm, dp, remaining, clock);
461
462     dp->prev_remaining = remaining;
463     dp->prev_clock = clock;
464   }
465
466   total += pimpl->dp_updated_by_deleted_tasks;
467
468   XBT_DEBUG("mig-stage%d.%d: computed %f flop_counts (including %f by deleted tasks)", stage_for_fancy_debug,
469             stage2_round_for_fancy_debug, total, pimpl->dp_updated_by_deleted_tasks);
470
471   pimpl->dp_updated_by_deleted_tasks = 0;
472
473   return total;
474 }
475
476 // TODO Is this code redundant with the information provided by
477 // msg_process_t MSG_process_create(const char *name, xbt_main_func_t code, void *data, msg_host_t host)
478 /** @brief take care of the dirty page tracking, in case we're adding a task to a migrating VM */
479 void MSG_host_add_task(msg_host_t host, msg_task_t task)
480 {
481   simgrid::s4u::VirtualMachine* vm = dynamic_cast<simgrid::s4u::VirtualMachine*>(host);
482   if (vm == nullptr)
483     return;
484   simgrid::surf::VirtualMachineImpl* pimpl = static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_);
485
486   double remaining = MSG_task_get_flops_amount(task);
487   char *key = bprintf("%s-%p", task->name, task);
488
489   dirty_page_t dp = xbt_new0(s_dirty_page, 1);
490   dp->task = task;
491   if (pimpl->dp_enabled) {
492     dp->prev_clock = MSG_get_clock();
493     dp->prev_remaining = remaining;
494   }
495   if (!pimpl->dp_objs)
496     pimpl->dp_objs = xbt_dict_new();
497   xbt_assert(xbt_dict_get_or_null(pimpl->dp_objs, key) == nullptr);
498   xbt_dict_set(pimpl->dp_objs, key, dp, nullptr);
499   XBT_DEBUG("add %s on %s (remaining %f, dp_enabled %d)", key, sg_host_get_name(host), remaining, pimpl->dp_enabled);
500
501   xbt_free(key);
502 }
503
504 void MSG_host_del_task(msg_host_t host, msg_task_t task)
505 {
506   simgrid::s4u::VirtualMachine* vm = dynamic_cast<simgrid::s4u::VirtualMachine*>(host);
507   if (vm == nullptr)
508     return;
509   simgrid::surf::VirtualMachineImpl* pimpl = static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_);
510
511   char *key = bprintf("%s-%p", task->name, task);
512   dirty_page_t dp = (dirty_page_t)(pimpl->dp_objs ? xbt_dict_get_or_null(pimpl->dp_objs, key) : NULL);
513   xbt_assert(dp->task == task);
514
515   /* If we are in the middle of dirty page tracking, we record how much computation has been done until now, and keep
516    * the information for the lookup_() function that will called soon. */
517   if (pimpl->dp_enabled) {
518     double remaining = MSG_task_get_flops_amount(task);
519     double clock = MSG_get_clock();
520     // double updated = calc_updated_pages(key, host, dp, remaining, clock);
521     double updated = get_computed(key, host, dp, remaining, clock);
522
523     pimpl->dp_updated_by_deleted_tasks += updated;
524   }
525   if (pimpl->dp_objs)
526     xbt_dict_remove(pimpl->dp_objs, key);
527   xbt_free(dp);
528
529   XBT_DEBUG("del %s on %s", key, sg_host_get_name(host));
530   xbt_free(key);
531 }
532
533 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, char *mbox,
534                                      int stage, int stage2_round, double mig_speed, double timeout)
535 {
536   sg_size_t sent = 0;
537   char *task_name = get_mig_task_name(vm, src_pm, dst_pm, stage);
538   msg_task_t task = MSG_task_create(task_name, 0, (double)size, nullptr);
539
540   /* TODO: clean up */
541
542   double clock_sta = MSG_get_clock();
543
544   msg_error_t ret;
545   if (mig_speed > 0)
546     ret = MSG_task_send_with_timeout_bounded(task, mbox, timeout, mig_speed);
547   else
548     ret = MSG_task_send(task, mbox);
549
550   xbt_free(task_name);
551
552   if (ret == MSG_OK) {
553     sent = size;
554   } else if (ret == MSG_TIMEOUT) {
555     sg_size_t remaining = (sg_size_t)MSG_task_get_remaining_communication(task);
556     sent = size - remaining;
557     XBT_VERB("timeout (%lf s) in sending_migration_data, remaining %llu bytes of %llu", timeout, remaining, size);
558   }
559
560   /* FIXME: why try-and-catch is used here? */
561   if(ret == MSG_HOST_FAILURE){
562     //XBT_DEBUG("SRC host failed during migration of %s (stage %d)", sg_host_name(vm), stage);
563     MSG_task_destroy(task);
564     THROWF(host_error, 0, "SRC host failed during migration of %s (stage %d)", sg_host_get_name(vm), stage);
565   }else if(ret == MSG_TRANSFER_FAILURE){
566     //XBT_DEBUG("DST host failed during migration of %s (stage %d)", sg_host_name(vm), stage);
567     MSG_task_destroy(task);
568     THROWF(host_error, 0, "DST host failed during migration of %s (stage %d)", sg_host_get_name(vm), stage);
569   }
570
571   double clock_end = MSG_get_clock();
572   double duration = clock_end - clock_sta;
573   double actual_speed = size / duration;
574
575   if (stage == 2)
576     XBT_DEBUG("mig-stage%d.%d: sent %llu duration %f actual_speed %f (target %f)",
577               stage, stage2_round, size, duration, actual_speed, mig_speed);
578   else
579     XBT_DEBUG("mig-stage%d: sent %llu duration %f actual_speed %f (target %f)",
580               stage, size, duration, actual_speed, mig_speed);
581
582   return sent;
583 }
584
585 static sg_size_t get_updated_size(double computed, double dp_rate, double dp_cap)
586 {
587   double updated_size = computed * dp_rate;
588   XBT_DEBUG("updated_size %f dp_rate %f", updated_size, dp_rate);
589   if (updated_size > dp_cap) {
590     // XBT_INFO("mig-stage2.%d: %f bytes updated, but cap it with the working set size %f", stage2_round, updated_size,
591     //          dp_cap);
592     updated_size = dp_cap;
593   }
594
595   return (sg_size_t) updated_size;
596 }
597
598 static double send_stage1(struct migration_session *ms, sg_size_t ramsize, double mig_speed, double dp_rate,
599                           double dp_cap)
600 {
601   // const long chunksize = (sg_size_t)1024 * 1024 * 100;
602   const sg_size_t chunksize = (sg_size_t)1024 * 1024 * 100000;
603   sg_size_t remaining = ramsize;
604   double computed_total = 0;
605
606   while (remaining > 0) {
607     sg_size_t datasize = chunksize;
608     if (remaining < chunksize)
609       datasize = remaining;
610
611     remaining -= datasize;
612     send_migration_data(ms->vm, ms->src_pm, ms->dst_pm, datasize, ms->mbox, 1, 0, mig_speed, -1);
613     double computed = lookup_computed_flop_counts(ms->vm, 1, 0);
614     computed_total += computed;
615   }
616
617   return computed_total;
618 }
619
620 static double get_threshold_value(double bandwidth, double max_downtime)
621 {
622   return max_downtime * bandwidth;
623 }
624
625 static int migration_tx_fun(int argc, char *argv[])
626 {
627   XBT_DEBUG("mig: tx_start");
628
629   // Note that the ms structure has been allocated in do_migration and hence should be freed in the same function ;)
630   migration_session *ms = (migration_session *) MSG_process_get_data(MSG_process_self());
631
632   s_vm_params_t params;
633   static_cast<simgrid::s4u::VirtualMachine*>(ms->vm)->parameters(&params);
634   const sg_size_t ramsize   = params.ramsize;
635   const sg_size_t devsize   = params.devsize;
636   const int skip_stage1     = params.skip_stage1;
637   int skip_stage2           = params.skip_stage2;
638   const double dp_rate      = params.dp_rate;
639   const double dp_cap       = params.dp_cap;
640   const double mig_speed    = params.mig_speed;
641   double max_downtime       = params.max_downtime;
642
643   /* hard code it temporally. Fix Me */
644 #define MIGRATION_TIMEOUT_DO_NOT_HARDCODE_ME 10000000.0
645   double mig_timeout = MIGRATION_TIMEOUT_DO_NOT_HARDCODE_ME;
646
647   double remaining_size = (double) (ramsize + devsize);
648   double threshold = 0.0;
649
650   /* check parameters */
651   if (ramsize == 0)
652     XBT_WARN("migrate a VM, but ramsize is zero");
653
654   if (max_downtime <= 0) {
655     XBT_WARN("use the default max_downtime value 30ms");
656     max_downtime = 0.03;
657   }
658
659   /* Stage1: send all memory pages to the destination. */
660   XBT_DEBUG("mig-stage1: remaining_size %f", remaining_size);
661   start_dirty_page_tracking(ms->vm);
662
663   double computed_during_stage1 = 0;
664   if (!skip_stage1) {
665     double clock_prev_send = MSG_get_clock();
666
667     try {
668       /* At stage 1, we do not need timeout. We have to send all the memory pages even though the duration of this
669        * transfer exceeds the timeout value. */
670       XBT_VERB("Stage 1: Gonna send %llu", ramsize);
671       sg_size_t sent = send_migration_data(ms->vm, ms->src_pm, ms->dst_pm, ramsize, ms->mbox, 1, 0, mig_speed, -1);
672       remaining_size -= sent;
673       computed_during_stage1 = lookup_computed_flop_counts(ms->vm, 1, 0);
674
675       if (sent < ramsize) {
676         XBT_VERB("mig-stage1: timeout, force moving to stage 3");
677         skip_stage2 = 1;
678       } else if (sent > ramsize)
679         XBT_CRITICAL("bug");
680
681     }
682     catch (xbt_ex& e) {
683       //hostfailure (if you want to know whether this is the SRC or the DST check directly in send_migration_data code)
684       // Stop the dirty page tracking an return (there is no memory space to release)
685       stop_dirty_page_tracking(ms->vm);
686       return 0;
687     }
688
689     double clock_post_send = MSG_get_clock();
690     mig_timeout -= (clock_post_send - clock_prev_send);
691     if (mig_timeout < 0) {
692       XBT_VERB("The duration of stage 1 exceeds the timeout value (%lf > %lf), skip stage 2",
693           (clock_post_send - clock_prev_send), MIGRATION_TIMEOUT_DO_NOT_HARDCODE_ME);
694       skip_stage2 = 1;
695     }
696
697     /* estimate bandwidth */
698     double bandwidth = ramsize / (clock_post_send - clock_prev_send);
699     threshold = get_threshold_value(bandwidth, max_downtime);
700     XBT_DEBUG("actual bandwidth %f (MB/s), threshold %f", bandwidth / 1024 / 1024, threshold);
701   }
702
703
704   /* Stage2: send update pages iteratively until the size of remaining states becomes smaller than threshold value. */
705  if (! skip_stage2) {
706
707   int stage2_round = 0;
708   for (;;) {
709
710     sg_size_t updated_size = 0;
711     if (stage2_round == 0) {
712       /* just after stage1, nothing has been updated. But, we have to send the data updated during stage1 */
713       updated_size = get_updated_size(computed_during_stage1, dp_rate, dp_cap);
714     } else {
715       double computed = lookup_computed_flop_counts(ms->vm, 2, stage2_round);
716       updated_size = get_updated_size(computed, dp_rate, dp_cap);
717     }
718
719     XBT_DEBUG("mig-stage 2:%d updated_size %llu computed_during_stage1 %f dp_rate %f dp_cap %f",
720         stage2_round, updated_size, computed_during_stage1, dp_rate, dp_cap);
721
722     /* Check whether the remaining size is below the threshold value. If so, move to stage 3. */
723     remaining_size += updated_size;
724     XBT_DEBUG("mig-stage2.%d: remaining_size %f (%s threshold %f)", stage2_round,
725         remaining_size, (remaining_size < threshold) ? "<" : ">", threshold);
726     if (remaining_size < threshold)
727       break;
728
729     sg_size_t sent = 0;
730     double clock_prev_send = MSG_get_clock();
731     try {
732       XBT_DEBUG("Stage 2, gonna send %llu", updated_size);
733       sent = send_migration_data(ms->vm, ms->src_pm, ms->dst_pm, updated_size, ms->mbox, 2, stage2_round, mig_speed,
734                                  mig_timeout);
735     }
736     catch (xbt_ex& e) {
737       //hostfailure (if you want to know whether this is the SRC or the DST check directly in send_migration_data code)
738       // Stop the dirty page tracking an return (there is no memory space to release)
739       stop_dirty_page_tracking(ms->vm);
740       return 0;
741     }
742     double clock_post_send = MSG_get_clock();
743
744     if (sent == updated_size) {
745       /* timeout did not happen */
746       double bandwidth = updated_size / (clock_post_send - clock_prev_send);
747       threshold = get_threshold_value(bandwidth, max_downtime);
748       XBT_DEBUG("actual bandwidth %f, threshold %f", bandwidth / 1024 / 1024, threshold);
749       remaining_size -= sent;
750       stage2_round += 1;
751       mig_timeout -= (clock_post_send - clock_prev_send);
752       xbt_assert(mig_timeout > 0);
753
754     } else if (sent < updated_size) {
755       /* When timeout happens, we move to stage 3. The size of memory pages
756        * updated before timeout must be added to the remaining size. */
757       XBT_VERB("mig-stage2.%d: timeout, force moving to stage 3. sent %llu / %llu, eta %lf",
758           stage2_round, sent, updated_size, (clock_post_send - clock_prev_send));
759       remaining_size -= sent;
760
761       double computed = lookup_computed_flop_counts(ms->vm, 2, stage2_round);
762       updated_size = get_updated_size(computed, dp_rate, dp_cap);
763       remaining_size += updated_size;
764       break;
765     } else
766       XBT_CRITICAL("bug");
767   }
768  }
769
770   /* Stage3: stop the VM and copy the rest of states. */
771   XBT_DEBUG("mig-stage3: remaining_size %f", remaining_size);
772   simcall_vm_suspend(ms->vm);
773   stop_dirty_page_tracking(ms->vm);
774
775   try {
776     XBT_DEBUG("Stage 3: Gonna send %f", remaining_size);
777     send_migration_data(ms->vm, ms->src_pm, ms->dst_pm, (sg_size_t)remaining_size, ms->mbox, 3, 0, mig_speed, -1);
778   }
779   catch(xbt_ex& e) {
780     //hostfailure (if you want to know whether this is the SRC or the DST check directly in send_migration_data code)
781     // Stop the dirty page tracking an return (there is no memory space to release)
782     simcall_vm_resume(ms->vm);
783     return 0;
784   }
785
786   // At that point the Migration is considered valid for the SRC node but remind that the DST side should relocate
787   // effectively the VM on the DST node.
788   XBT_DEBUG("mig: tx_done");
789
790   return 0;
791 }
792
793 static int do_migration(msg_vm_t vm, msg_host_t src_pm, msg_host_t dst_pm)
794 {
795   struct migration_session *ms = xbt_new(struct migration_session, 1);
796   ms->vm = vm;
797   ms->src_pm = src_pm;
798   ms->dst_pm = dst_pm;
799   ms->mbox_ctl = get_mig_mbox_ctl(vm, src_pm, dst_pm);
800   ms->mbox = get_mig_mbox_src_dst(vm, src_pm, dst_pm);
801
802   char *pr_rx_name = get_mig_process_rx_name(vm, src_pm, dst_pm);
803   char *pr_tx_name = get_mig_process_tx_name(vm, src_pm, dst_pm);
804
805 //  msg_process_t tx_process, rx_process; 
806 //  MSG_process_create(pr_rx_name, migration_rx_fun, ms, dst_pm);
807 //  MSG_process_create(pr_tx_name, migration_tx_fun, ms, src_pm);
808 #if 1
809  {
810  char **argv = xbt_new(char *, 2);
811  argv[0] = pr_rx_name;
812  argv[1] = nullptr;
813 /*rx_process = */ MSG_process_create_with_arguments(pr_rx_name, migration_rx_fun, ms, dst_pm, 1, argv);
814  }
815  {
816  char **argv = xbt_new(char *, 2);
817  argv[0] = pr_tx_name;
818  argv[1] = nullptr;
819 /* tx_process = */MSG_process_create_with_arguments(pr_tx_name, migration_tx_fun, ms, src_pm, 1, argv);
820  }
821 #endif
822
823   /* wait until the migration have finished or on error has occurred */
824   {
825     XBT_DEBUG("wait for reception of the final ACK (i.e. migration has been correctly performed");
826     msg_task_t task = nullptr;
827     msg_error_t ret = MSG_TIMEOUT;
828     while (ret == MSG_TIMEOUT && MSG_host_is_on(dst_pm)) //Wait while you receive the message o
829      ret = MSG_task_receive_with_timeout(&task, ms->mbox_ctl, 4);
830
831     xbt_free(ms->mbox_ctl);
832     xbt_free(ms->mbox);
833     xbt_free(ms);
834
835     //xbt_assert(ret == MSG_OK);
836     if(ret == MSG_HOST_FAILURE){
837         // Note that since the communication failed, the owner did not change and the task should be destroyed on the
838         // other side. Hence, just throw the execption
839         XBT_ERROR("SRC crashes, throw an exception (m-control)");
840         //MSG_process_kill(tx_process); // Adrien, I made a merge on Nov 28th 2014, I'm not sure whether this line is
841                                         // required or not
842         return -1; 
843     } 
844     else if((ret == MSG_TRANSFER_FAILURE) || (ret == MSG_TIMEOUT)){
845         // MSG_TIMEOUT here means that MSG_host_is_avail() returned false.
846         XBT_ERROR("DST crashes, throw an exception (m-control)");
847         return -2;  
848     }
849
850     char *expected_task_name = get_mig_task_name(vm, src_pm, dst_pm, 4);
851     xbt_assert(strcmp(task->name, expected_task_name) == 0);
852     xbt_free(expected_task_name);
853     MSG_task_destroy(task);
854     return 0;
855   }
856 }
857
858 /** @brief Migrate the VM to the given host.
859  *  @ingroup msg_VMs
860  *
861  * FIXME: No migration cost occurs. If you want to simulate this too, you want to use a MSG_task_send() before or after,
862  * depending on whether you want to do cold or hot migration.
863  */
864 void MSG_vm_migrate(msg_vm_t vm, msg_host_t new_pm)
865 {
866   /* some thoughts:
867    * - One approach is ...
868    *   We first create a new VM (i.e., destination VM) on the destination   physical host. The destination VM will
869    *   receive the state of the source
870    *   VM over network. We will finally destroy the source VM.
871    *   - This behavior is similar to the way of migration in the real world.
872    *     Even before a migration is completed, we will see a destination VM, consuming resources.
873    *   - We have to relocate all processes. The existing process migration code will work for this?
874    *   - The name of the VM is a somewhat unique ID in the code. It is tricky for the destination VM?
875    *
876    * - Another one is ...
877    *   We update the information of the given VM to place it to the destination physical host.
878    *
879    * The second one would be easier.
880    */
881
882   msg_host_t old_pm = (msg_host_t) simcall_vm_get_pm(vm);
883
884   if(MSG_host_is_off(old_pm))
885     THROWF(vm_error, 0, "SRC host(%s) seems off, cannot start a migration", sg_host_get_name(old_pm));
886
887   if(MSG_host_is_off(new_pm))
888     THROWF(vm_error, 0, "DST host(%s) seems off, cannot start a migration", sg_host_get_name(new_pm));
889
890   if (!MSG_vm_is_running(vm))
891     THROWF(vm_error, 0, "VM(%s) is not running", sg_host_get_name(vm));
892
893   if (MSG_vm_is_migrating(vm))
894     THROWF(vm_error, 0, "VM(%s) is already migrating", sg_host_get_name(vm));
895
896   simgrid::surf::VirtualMachineImpl* pimpl = static_cast<simgrid::surf::VirtualMachineImpl*>(vm->pimpl_);
897   pimpl->isMigrating                       = 1;
898
899   {
900     int ret = do_migration(vm, old_pm, new_pm);
901     if (ret == -1){
902       pimpl->isMigrating = 0;
903       THROWF(host_error, 0, "SRC host failed during migration");
904     }
905     else if(ret == -2){
906       pimpl->isMigrating = 0;
907       THROWF(host_error, 0, "DST host failed during migration");
908     }
909   }
910
911   // This part is done in the RX code, to handle the corner case where SRC can crash just at the end of the migration
912   // process. In that case, the VM has been already assigned to the DST node.
913   //XBT_DEBUG("VM(%s) moved from PM(%s) to PM(%s)", vm->key, old_pm->key, new_pm->key);
914   //TRACE_msg_vm_change_host(vm, old_pm, new_pm);
915 }
916
917 /** @brief Immediately suspend the execution of all processes within the given VM.
918  *  @ingroup msg_VMs
919  *
920  * This function stops the execution of the VM. All the processes on this VM
921  * will pause. The state of the VM is preserved. We can later resume it again.
922  *
923  * No suspension cost occurs.
924  */
925 void MSG_vm_suspend(msg_vm_t vm)
926 {
927   if (MSG_vm_is_migrating(vm))
928     THROWF(vm_error, 0, "VM(%s) is migrating", sg_host_get_name(vm));
929
930   simcall_vm_suspend(vm);
931
932   XBT_DEBUG("vm_suspend done");
933
934   TRACE_msg_vm_suspend(vm);
935 }
936
937 /** @brief Resume the execution of the VM. All processes on the VM run again.
938  *  @ingroup msg_VMs
939  *
940  * No resume cost occurs.
941  */
942 void MSG_vm_resume(msg_vm_t vm)
943 {
944   simcall_vm_resume(vm);
945
946   TRACE_msg_vm_resume(vm);
947 }
948
949
950 /** @brief Immediately save the execution of all processes within the given VM.
951  *  @ingroup msg_VMs
952  *
953  * This function stops the execution of the VM. All the processes on this VM
954  * will pause. The state of the VM is preserved. We can later resume it again.
955  *
956  * FIXME: No suspension cost occurs. If you want to simulate this too, you want to use a \ref MSG_file_write() before
957  * or after, depending on the exact semantic of VM save to you.
958  */
959 void MSG_vm_save(msg_vm_t vm)
960 {
961   if (MSG_vm_is_migrating(vm))
962     THROWF(vm_error, 0, "VM(%s) is migrating", sg_host_get_name(vm));
963
964   simcall_vm_save(vm);
965   TRACE_msg_vm_save(vm);
966 }
967
968 /** @brief Restore the execution of the VM. All processes on the VM run again.
969  *  @ingroup msg_VMs
970  *
971  * FIXME: No restore cost occurs. If you want to simulate this too, you want to use a \ref MSG_file_read() before or
972  * after, depending on the exact semantic of VM restore to you.
973  */
974 void MSG_vm_restore(msg_vm_t vm)
975 {
976   simcall_vm_restore(vm);
977
978   TRACE_msg_vm_restore(vm);
979 }
980
981 /** @brief Get the physical host of a given VM.
982  *  @ingroup msg_VMs
983  */
984 msg_host_t MSG_vm_get_pm(msg_vm_t vm)
985 {
986   return (msg_host_t) simcall_vm_get_pm(vm);
987 }
988
989 /** @brief Set a CPU bound for a given VM.
990  *  @ingroup msg_VMs
991  *
992  * 1. Note that in some cases MSG_task_set_bound() may not intuitively work for VMs.
993  *
994  * For example,
995  *  On PM0, there are Task1 and VM0.
996  *  On VM0, there is Task2.
997  * Now we bound 75% to Task1\@PM0 and bound 25% to Task2\@VM0.
998  * Then,
999  *  Task1\@PM0 gets 50%.
1000  *  Task2\@VM0 gets 25%.
1001  * This is NOT 75% for Task1\@PM0 and 25% for Task2\@VM0, respectively.
1002  *
1003  * This is because a VM has the dummy CPU action in the PM layer. Putting a task on the VM does not affect the bound of
1004  * the dummy CPU action. The bound of the dummy CPU action is unlimited.
1005  *
1006  * There are some solutions for this problem. One option is to update the bound of the dummy CPU action automatically.
1007  * It should be the sum of all tasks on the VM. But, this solution might be costly, because we have to scan all tasks
1008  * on the VM in share_resource() or we have to trap both the start and end of task execution.
1009  *
1010  * The current solution is to use MSG_vm_set_bound(), which allows us to directly set the bound of the dummy CPU action.
1011  *
1012  * 2. Note that bound == 0 means no bound (i.e., unlimited). But, if a host has multiple CPU cores, the CPU share of a
1013  *    computation task (or a VM) never exceeds the capacity of a CPU core.
1014  */
1015 void MSG_vm_set_bound(msg_vm_t vm, double bound)
1016 {
1017   simcall_vm_set_bound(vm, bound);
1018 }