Logo AND Algorithmique Numérique Distribuée

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