Logo AND Algorithmique Numérique Distribuée

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