Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Check return value for posix_memalign.
[simgrid.git] / src / surf / surf_interface.cpp
1 /* Copyright (c) 2004-2014. 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 #include "surf_private.h"
8 #include "surf_interface.hpp"
9 #include "network_interface.hpp"
10 #include "cpu_interface.hpp"
11 #include "workstation_interface.hpp"
12 #include "vm_workstation_interface.hpp"
13 #include "simix/smx_host_private.h"
14 #include "surf_routing.hpp"
15 #include "simgrid/sg_config.h"
16 #include "mc/mc.h"
17
18 XBT_LOG_NEW_CATEGORY(surf, "All SURF categories");
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_kernel, surf,
20                                 "Logging specific to SURF (kernel)");
21
22 /*********
23  * Utils *
24  *********/
25
26 /* This function is a pimple that we ought to fix. But it won't be easy.
27  *
28  * The surf_solve() function does properly return the set of actions that changed.
29  * Instead, each model change a global data, and then the caller of surf_solve must
30  * pick into these sets of action_failed and action_done.
31  *
32  * This was not clean but ok as long as we didn't had to restart the processes when the resource comes back up.
33  * We worked by putting sentinel actions on every resources we are interested in,
34  * so that surf informs us if/when the corresponding resource fails.
35  *
36  * But this does not work to get Simix informed of when a resource comes back up, and this is where this pimple comes.
37  * We have a set of resources that are currently down and for which simix needs to know when it comes back up.
38  * And the current function is called *at every simulation step* to sweep over that set, searching for a resource
39  * that was turned back up in the meanwhile. This is UGLY and slow.
40  *
41  * The proper solution would be to not rely on globals for the action_failed and action_done swags.
42  * They must be passed as parameter by the caller (the handling of these actions in simix may let you
43  * think that these two sets can be merged, but their handling in SimDag induce the contrary unless this
44  * simdag code can check by itself whether the action is done of failed -- seems very doable, but yet more
45  * cleanup to do).
46  *
47  * Once surf_solve() is passed the set of actions that changed, you want to add a new set of resources back up
48  * as parameter to this function. You also want to add a boolean field "restart_watched" to each resource, and
49  * make sure that whenever a resource with this field enabled comes back up, it's added to that set so that Simix
50  * sees it and react accordingly. This would kill that need for surf to call simix.
51  *
52  */
53
54 /*static void remove_watched_host(void *key)
55 {
56   xbt_dict_remove(watched_hosts_lib, *(char**)key);
57 }*/
58
59 /*void surf_watched_hosts(void)
60 {
61   char *key;
62   void *host;
63   xbt_dict_cursor_t cursor;
64   xbt_dynar_t hosts = xbt_dynar_new(sizeof(char*), NULL);
65
66   XBT_DEBUG("Check for host SURF_RESOURCE_ON on watched_hosts_lib");
67   xbt_dict_foreach(watched_hosts_lib, cursor, key, host)
68   {
69     if(SIMIX_host_get_state((smx_host_t)host) == SURF_RESOURCE_ON){
70       XBT_INFO("Restart processes on host: %s", SIMIX_host_get_name((smx_host_t)host));
71       SIMIX_host_autorestart((smx_host_t)host);
72       xbt_dynar_push_as(hosts, char*, key);
73     }
74     else
75       XBT_DEBUG("See SURF_RESOURCE_OFF on host: %s",key);
76   }
77   xbt_dynar_map(hosts, remove_watched_host);
78   xbt_dynar_free(&hosts);
79 }*/
80
81 /* model_list_invoke contains only surf_workstation and surf_vm_workstation.
82  * The callback functions of cpu_model and network_model will be called from
83  * those of these workstation models. */
84 xbt_dynar_t model_list = NULL; /* for destroying all models correctly */
85 xbt_dynar_t model_list_invoke = NULL;  /* for invoking callbacks */
86
87 tmgr_history_t history = NULL;
88 lmm_system_t maxmin_system = NULL;
89 xbt_dynar_t surf_path = NULL;
90 xbt_dynar_t host_that_restart = NULL;
91 xbt_dict_t watched_hosts_lib;
92
93 surf_callback(void, void) surfExitCallbacks;
94
95 s_surf_model_description_t surf_plugin_description[] = {
96                   {"Energy",
97                    "Cpu energy consumption.",
98                    sg_energy_plugin_init},
99                   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
100 };
101
102 /* Don't forget to update the option description in smx_config when you change this */
103 s_surf_model_description_t surf_network_model_description[] = {
104   {"LV08",
105    "Realistic network analytic model (slow-start modeled by multiplying latency by 10.4, bandwidth by .92; bottleneck sharing uses a payload of S=8775 for evaluating RTT). ",
106    surf_network_model_init_LegrandVelho},
107   {"Constant",
108    "Simplistic network model where all communication take a constant time (one second). This model provides the lowest realism, but is (marginally) faster.",
109    surf_network_model_init_Constant},
110   {"SMPI",
111    "Realistic network model specifically tailored for HPC settings (accurate modeling of slow start with correction factors on three intervals: < 1KiB, < 64 KiB, >= 64 KiB)",
112    surf_network_model_init_SMPI},
113   {"CM02",
114    "Legacy network analytic model (Very similar to LV08, but without corrective factors. The timings of small messages are thus poorly modeled).",
115    surf_network_model_init_CM02},
116 #ifdef HAVE_GTNETS
117   {"GTNets",
118    "Network pseudo-model using the GTNets simulator instead of an analytic model",
119    surf_network_model_init_GTNETS},
120 #endif
121 #ifdef HAVE_NS3
122   {"NS3",
123    "Network pseudo-model using the NS3 tcp model instead of an analytic model",
124   surf_network_model_init_NS3},
125 #endif
126   {"Reno",
127    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
128    surf_network_model_init_Reno},
129   {"Reno2",
130    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
131    surf_network_model_init_Reno2},
132   {"Vegas",
133    "Model from Steven H. Low using lagrange_solve instead of lmm_solve (experts only; check the code for more info).",
134    surf_network_model_init_Vegas},
135   {NULL, NULL, NULL}      /* this array must be NULL terminated */
136 };
137
138 s_surf_model_description_t surf_cpu_model_description[] = {
139   {"Cas01",
140    "Simplistic CPU model (time=size/power).",
141    surf_cpu_model_init_Cas01},
142   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
143 };
144
145 s_surf_model_description_t surf_workstation_model_description[] = {
146   {"default",
147    "Default workstation model. Currently, CPU:Cas01 and network:LV08 (with cross traffic enabled)",
148    surf_workstation_model_init_current_default},
149   {"compound",
150    "Workstation model that is automatically chosen if you change the network and CPU models",
151    surf_workstation_model_init_compound},
152   {"ptask_L07", "Workstation model somehow similar to Cas01+CM02 but allowing parallel tasks",
153    surf_workstation_model_init_ptask_L07},
154   {NULL, NULL, NULL}      /* this array must be NULL terminated */
155 };
156
157 s_surf_model_description_t surf_vm_workstation_model_description[] = {
158   {"default",
159    "Default vm workstation model.",
160    surf_vm_workstation_model_init_current_default},
161   {NULL, NULL, NULL}      /* this array must be NULL terminated */
162 };
163
164 s_surf_model_description_t surf_optimization_mode_description[] = {
165   {"Lazy",
166    "Lazy action management (partial invalidation in lmm + heap in action remaining).",
167    NULL},
168   {"TI",
169    "Trace integration. Highly optimized mode when using availability traces (only available for the Cas01 CPU model for now).",
170     NULL},
171   {"Full",
172    "Full update of remaining and variables. Slow but may be useful when debugging.",
173    NULL},
174   {NULL, NULL, NULL}      /* this array must be NULL terminated */
175 };
176
177 s_surf_model_description_t surf_storage_model_description[] = {
178   {"default",
179    "Simplistic storage model.",
180    surf_storage_model_init_default},
181   {NULL, NULL,  NULL}      /* this array must be NULL terminated */
182 };
183
184 #ifdef CONTEXT_THREADS
185 static xbt_parmap_t surf_parmap = NULL; /* parallel map on models */
186 #endif
187
188 double NOW = 0;
189 double *surf_mins = NULL; /* return value of share_resources for each model */
190 int surf_min_index;       /* current index in surf_mins */
191 double surf_min;               /* duration determined by surf_solve */
192
193 double surf_get_clock(void)
194 {
195   return NOW;
196 }
197
198 #ifdef _XBT_WIN32
199 # define FILE_DELIM "\\"
200 #else
201 # define FILE_DELIM "/"         /* FIXME: move to better location */
202 #endif
203
204 FILE *surf_fopen(const char *name, const char *mode)
205 {
206   unsigned int cpt;
207   char *path_elm = NULL;
208   char *buff;
209   FILE *file = NULL;
210
211   xbt_assert(name);
212
213   if (__surf_is_absolute_file_path(name))       /* don't mess with absolute file names */
214     return fopen(name, mode);
215
216   /* search relative files in the path */
217   xbt_dynar_foreach(surf_path, cpt, path_elm) {
218     buff = bprintf("%s" FILE_DELIM "%s", path_elm, name);
219     file = fopen(buff, mode);
220     free(buff);
221
222     if (file)
223       return file;
224   }
225   return NULL;
226 }
227
228
229 #ifndef MAX_DRIVE
230 #define MAX_DRIVE 26
231 #endif
232
233 #ifdef _XBT_WIN32
234 #include <windows.h>
235 static const char *disk_drives_letter_table[MAX_DRIVE] = {
236   "A:\\",
237   "B:\\",
238   "C:\\",
239   "D:\\",
240   "E:\\",
241   "F:\\",
242   "G:\\",
243   "H:\\",
244   "I:\\",
245   "J:\\",
246   "K:\\",
247   "L:\\",
248   "M:\\",
249   "N:\\",
250   "O:\\",
251   "P:\\",
252   "Q:\\",
253   "R:\\",
254   "S:\\",
255   "T:\\",
256   "U:\\",
257   "V:\\",
258   "W:\\",
259   "X:\\",
260   "Y:\\",
261   "Z:\\"
262 };
263 #endif  
264
265 /*
266  * Returns the initial path. On Windows the initial path is
267  * the current directory for the current process in the other
268  * case the function returns "./" that represents the current
269  * directory on Unix/Linux platforms.
270  */
271
272 const char *__surf_get_initial_path(void)
273 {
274
275 #ifdef _XBT_WIN32
276   unsigned i;
277   char current_directory[MAX_PATH + 1] = { 0 };
278   unsigned int len = GetCurrentDirectory(MAX_PATH + 1, current_directory);
279   char root[4] = { 0 };
280
281   if (!len)
282     return NULL;
283
284   strncpy(root, current_directory, 3);
285
286   for (i = 0; i < MAX_DRIVE; i++) {
287     if (toupper(root[0]) == disk_drives_letter_table[i][0])
288       return disk_drives_letter_table[i];
289   }
290
291   return NULL;
292 #else
293   return "./";
294 #endif
295 }
296
297 /* The __surf_is_absolute_file_path() returns 1 if
298  * file_path is a absolute file path, in the other
299  * case the function returns 0.
300  */
301 int __surf_is_absolute_file_path(const char *file_path)
302 {
303 #ifdef _XBT_WIN32
304   WIN32_FIND_DATA wfd = { 0 };
305   HANDLE hFile = FindFirstFile(file_path, &wfd);
306
307   if (INVALID_HANDLE_VALUE == hFile)
308     return 0;
309
310   FindClose(hFile);
311   return 1;
312 #else
313   return (file_path[0] == '/');
314 #endif
315 }
316
317 /** Displays the long description of all registered models, and quit */
318 void model_help(const char *category, s_surf_model_description_t * table)
319 {
320   int i;
321   printf("Long description of the %s models accepted by this simulator:\n",
322          category);
323   for (i = 0; table[i].name; i++)
324     printf("  %s: %s\n", table[i].name, table[i].description);
325 }
326
327 int find_model_description(s_surf_model_description_t * table,
328                            const char *name)
329 {
330   int i;
331   char *name_list = NULL;
332
333   for (i = 0; table[i].name; i++)
334     if (!strcmp(name, table[i].name)) {
335       return i;
336     }
337   if (!table[0].name)
338     xbt_die("No model is valid! This is a bug.");
339   name_list = xbt_strdup(table[0].name);
340   for (i = 1; table[i].name; i++) {
341     name_list = (char *) xbt_realloc(name_list, strlen(name_list) + strlen(table[i].name) + 3);
342     strcat(name_list, ", ");
343     strcat(name_list, table[i].name);
344   }
345   xbt_die("Model '%s' is invalid! Valid models are: %s.", name, name_list);
346   return -1;
347 }
348
349 static XBT_INLINE void routing_asr_host_free(void *p)
350 {
351   delete ((RoutingEdgePtr) p);
352 }
353
354 static XBT_INLINE void routing_asr_prop_free(void *p)
355 {
356   xbt_dict_t elm = (xbt_dict_t) p;
357   xbt_dict_free(&elm);
358 }
359
360 static XBT_INLINE void surf_cpu_free(void *r)
361 {
362   delete static_cast<CpuPtr>(r);
363 }
364
365 static XBT_INLINE void surf_link_free(void *r)
366 {
367   delete static_cast<NetworkLinkPtr>(r);
368 }
369
370 static XBT_INLINE void surf_workstation_free(void *r)
371 {
372   delete static_cast<WorkstationPtr>(r);
373 }
374
375 static XBT_INLINE void surf_storage_free(void *r)
376 {
377   delete static_cast<StoragePtr>(r);
378 }
379
380
381 void sg_version(int *ver_major,int *ver_minor,int *ver_patch) {
382   *ver_major = SIMGRID_VERSION_MAJOR;
383   *ver_minor = SIMGRID_VERSION_MINOR;
384   *ver_patch = SIMGRID_VERSION_PATCH;
385 }
386
387 void surf_init(int *argc, char **argv)
388 {
389   XBT_DEBUG("Create all Libs");
390   host_lib = xbt_lib_new();
391   link_lib = xbt_lib_new();
392   as_router_lib = xbt_lib_new();
393   storage_lib = xbt_lib_new();
394   storage_type_lib = xbt_lib_new();
395   file_lib = xbt_lib_new();
396   watched_hosts_lib = xbt_dict_new_homogeneous(NULL);
397
398   XBT_DEBUG("Add routing levels");
399   ROUTING_HOST_LEVEL = xbt_lib_add_level(host_lib,routing_asr_host_free);
400   ROUTING_ASR_LEVEL  = xbt_lib_add_level(as_router_lib,routing_asr_host_free);
401   ROUTING_PROP_ASR_LEVEL = xbt_lib_add_level(as_router_lib,routing_asr_prop_free);
402
403   XBT_DEBUG("Add SURF levels");
404   SURF_CPU_LEVEL = xbt_lib_add_level(host_lib,surf_cpu_free);
405   SURF_WKS_LEVEL = xbt_lib_add_level(host_lib,surf_workstation_free);
406   SURF_LINK_LEVEL = xbt_lib_add_level(link_lib,surf_link_free);
407   SURF_STORAGE_LEVEL = xbt_lib_add_level(storage_lib,surf_storage_free);
408
409   xbt_init(argc, argv);
410   if (!model_list)
411     model_list = xbt_dynar_new(sizeof(ModelPtr), NULL);
412   if (!model_list_invoke)
413     model_list_invoke = xbt_dynar_new(sizeof(ModelPtr), NULL);
414   if (!history)
415     history = tmgr_history_new();
416
417 #ifdef HAVE_TRACING
418   TRACE_add_start_function(TRACE_surf_alloc);
419   TRACE_add_end_function(TRACE_surf_release);
420 #endif
421
422   sg_config_init(argc, argv);
423
424   if (MC_is_active())
425     MC_memory_init();
426 }
427
428 void surf_exit(void)
429 {
430   unsigned int iter;
431   ModelPtr model = NULL;
432
433 #ifdef HAVE_TRACING
434   TRACE_end();                  /* Just in case it was not called by the upper
435                                  * layer (or there is no upper layer) */
436 #endif
437
438   sg_config_finalize();
439
440   xbt_dynar_free(&host_that_restart);
441   xbt_dynar_free(&surf_path);
442
443   xbt_lib_free(&host_lib);
444   xbt_lib_free(&link_lib);
445   xbt_lib_free(&as_router_lib);
446   xbt_lib_free(&storage_lib);
447   xbt_lib_free(&storage_type_lib);
448   xbt_lib_free(&file_lib);
449   xbt_dict_free(&watched_hosts_lib);
450
451   xbt_dynar_foreach(model_list, iter, model)
452     delete model;
453   xbt_dynar_free(&model_list);
454   xbt_dynar_free(&model_list_invoke);
455   routing_exit();
456
457   surf_callback_emit(surfExitCallbacks);
458
459   if (maxmin_system) {
460     lmm_system_free(maxmin_system);
461     maxmin_system = NULL;
462   }
463   if (history) {
464     tmgr_history_free(history);
465     history = NULL;
466   }
467
468 #ifdef CONTEXT_THREADS
469   xbt_parmap_destroy(surf_parmap);
470 #endif
471
472   xbt_free(surf_mins);
473   surf_mins = NULL;
474
475   tmgr_finalize();
476   surf_parse_lex_destroy();
477   surf_parse_free_callbacks();
478
479   NOW = 0;                      /* Just in case the user plans to restart the simulation afterward */
480 }
481
482 /*********
483  * Model *
484  *********/
485
486 Model::Model(const char *name)
487   : p_maxminSystem(NULL)
488   , p_name(name)
489 {
490   p_readyActionSet = new ActionList();
491   p_runningActionSet = new ActionList();
492   p_failedActionSet = new ActionList();
493   p_doneActionSet = new ActionList();
494
495   p_modifiedSet = NULL;
496   p_actionHeap = NULL;
497   p_updateMechanism = UM_UNDEFINED;
498   m_selectiveUpdate = 0;
499 }
500
501 Model::~Model(){
502   delete p_readyActionSet;
503   delete p_runningActionSet;
504   delete p_failedActionSet;
505   delete p_doneActionSet;
506 }
507
508 double Model::shareResources(double now)
509 {
510   //FIXME: set the good function once and for all
511   if (p_updateMechanism == UM_LAZY)
512         return shareResourcesLazy(now);
513   else if (p_updateMechanism == UM_FULL)
514         return shareResourcesFull(now);
515   else
516         xbt_die("Invalid cpu update mechanism!");
517 }
518
519 double Model::shareResourcesLazy(double now)
520 {
521   ActionPtr action = NULL;
522   double min = -1;
523   double value;
524
525   XBT_DEBUG
526       ("Before share resources, the size of modified actions set is %zd",
527        p_modifiedSet->size());
528
529   lmm_solve(p_maxminSystem);
530
531   XBT_DEBUG
532       ("After share resources, The size of modified actions set is %zd",
533        p_modifiedSet->size());
534
535   while(!p_modifiedSet->empty()) {
536         action = &(p_modifiedSet->front());
537         p_modifiedSet->pop_front();
538     int max_dur_flag = 0;
539
540     if (action->getStateSet() != p_runningActionSet)
541       continue;
542
543     /* bogus priority, skip it */
544     if (action->getPriority() <= 0)
545       continue;
546
547     action->updateRemainingLazy(now);
548
549     min = -1;
550     value = lmm_variable_getvalue(action->getVariable());
551     if (value > 0) {
552       if (action->getRemains() > 0) {
553         value = action->getRemainsNoUpdate() / value;
554         min = now + value;
555       } else {
556         value = 0.0;
557         min = now;
558       }
559     }
560
561     if ((action->getMaxDuration() != NO_MAX_DURATION)
562         && (min == -1
563             || action->getStartTime() +
564             action->getMaxDuration() < min)) {
565       min = action->getStartTime() +
566           action->getMaxDuration();
567       max_dur_flag = 1;
568     }
569
570     XBT_DEBUG("Action(%p) Start %f Finish %f Max_duration %f", action,
571         action->getStartTime(), now + value,
572         action->getMaxDuration());
573
574     if (min != -1) {
575       action->heapRemove(p_actionHeap);
576       action->heapInsert(p_actionHeap, min, max_dur_flag ? MAX_DURATION : NORMAL);
577       XBT_DEBUG("Insert at heap action(%p) min %f now %f", action, min,
578                 now);
579     } else DIE_IMPOSSIBLE;
580   }
581
582   //hereafter must have already the min value for this resource model
583   if (xbt_heap_size(p_actionHeap) > 0)
584     min = xbt_heap_maxkey(p_actionHeap) - now;
585   else
586     min = -1;
587
588   XBT_DEBUG("The minimum with the HEAP %f", min);
589
590   return min;
591 }
592
593 double Model::shareResourcesFull(double /*now*/) {
594   THROW_UNIMPLEMENTED;
595 }
596
597 double Model::shareResourcesMaxMin(ActionListPtr running_actions,
598                           lmm_system_t sys,
599                           void (*solve) (lmm_system_t))
600 {
601   ActionPtr action = NULL;
602   double min = -1;
603   double value = -1;
604
605   solve(sys);
606
607   ActionList::iterator it(running_actions->begin()), itend(running_actions->end());
608   for(; it != itend ; ++it) {
609           action = &*it;
610     value = lmm_variable_getvalue(action->getVariable());
611     if ((value > 0) || (action->getMaxDuration() >= 0))
612       break;
613   }
614
615   if (!action)
616     return -1.0;
617
618   if (value > 0) {
619     if (action->getRemains() > 0)
620       min = action->getRemainsNoUpdate() / value;
621     else
622       min = 0.0;
623     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min))
624       min = action->getMaxDuration();
625   } else
626     min = action->getMaxDuration();
627
628
629   for (++it; it != itend; ++it) {
630         action = &*it;
631     value = lmm_variable_getvalue(action->getVariable());
632     if (value > 0) {
633       if (action->getRemains() > 0)
634         value = action->getRemainsNoUpdate() / value;
635       else
636         value = 0.0;
637       if (value < min) {
638         min = value;
639         XBT_DEBUG("Updating min (value) with %p: %f", action, min);
640       }
641     }
642     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min)) {
643       min = action->getMaxDuration();
644       XBT_DEBUG("Updating min (duration) with %p: %f", action, min);
645     }
646   }
647   XBT_DEBUG("min value : %f", min);
648
649   return min;
650 }
651
652 void Model::updateActionsState(double now, double delta)
653 {
654   if (p_updateMechanism == UM_FULL)
655         updateActionsStateFull(now, delta);
656   else if (p_updateMechanism == UM_LAZY)
657         updateActionsStateLazy(now, delta);
658   else
659         xbt_die("Invalid cpu update mechanism!");
660 }
661
662 void Model::updateActionsStateLazy(double /*now*/, double /*delta*/)
663 {
664 }
665
666 void Model::updateActionsStateFull(double /*now*/, double /*delta*/)
667 {
668 }
669
670 /************
671  * Resource *
672  ************/
673
674 Resource::Resource()
675 : p_name(NULL), p_properties(NULL), p_model(NULL)
676 {}
677
678 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props)
679   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
680   , m_running(true), m_stateCurrent(SURF_RESOURCE_ON)
681 {}
682
683 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props, lmm_constraint_t constraint)
684   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
685   , m_running(true), m_stateCurrent(SURF_RESOURCE_ON), p_constraint(constraint)
686 {}
687
688 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props, e_surf_resource_state_t stateInit)
689   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
690   , m_running(true), m_stateCurrent(stateInit)
691 {}
692
693 Resource::~Resource() {
694   xbt_free((void*)p_name);
695   xbt_dict_free(&p_properties);
696 }
697
698 e_surf_resource_state_t Resource::getState()
699 {
700   return m_stateCurrent;
701 }
702
703 void Resource::setState(e_surf_resource_state_t state)
704 {
705   m_stateCurrent = state;
706 }
707
708 bool Resource::isOn()
709 {
710   return m_running;
711 }
712
713 void Resource::turnOn()
714 {
715   if (!m_running) {
716     m_running = true;
717   }
718 }
719
720 void Resource::turnOff()
721 {
722   if (m_running) {
723     m_running = false;
724   }
725 }
726
727 ModelPtr Resource::getModel() {
728   return p_model;
729 }
730
731 const char *Resource::getName() {
732   return p_name;
733 }
734
735 xbt_dict_t Resource::getProperties() {
736   if (p_properties==NULL)
737         p_properties = xbt_dict_new();
738   return p_properties;
739 }
740
741 lmm_constraint_t Resource::getConstraint() {
742   return p_constraint;
743 }
744
745 /**********
746  * Action *
747  **********/
748
749 const char *surf_action_state_names[6] = {
750   "SURF_ACTION_READY",
751   "SURF_ACTION_RUNNING",
752   "SURF_ACTION_FAILED",
753   "SURF_ACTION_DONE",
754   "SURF_ACTION_TO_FREE",
755   "SURF_ACTION_NOT_IN_THE_SYSTEM"
756 };
757
758 Action::Action()
759 : m_refcount(1)
760 {}
761
762 Action::Action(ModelPtr model, double cost, bool failed)
763  : m_priority(1.0)
764  , m_refcount(1)
765  , m_remains(cost)
766  , m_maxDuration(NO_MAX_DURATION)
767  , m_finish(-1.0)
768  , m_failed(failed)
769  , m_start(surf_get_clock())
770  , m_cost(cost)
771  , p_model(model)
772  , p_data(NULL)
773  , p_variable(NULL)
774  , m_lastValue(0)
775  , m_lastUpdate(0)
776  , m_suspended(false)
777 {
778   #ifdef HAVE_TRACING
779     p_category = NULL;
780   #endif
781   p_stateHookup.prev = 0;
782   p_stateHookup.next = 0;
783   if (failed)
784     p_stateSet = getModel()->getFailedActionSet();
785   else
786     p_stateSet = getModel()->getRunningActionSet();
787
788   p_stateSet->push_back(*this);
789 }
790
791 Action::Action(ModelPtr model, double cost, bool failed, lmm_variable_t var)
792  : m_priority(1.0)
793  , m_refcount(1)
794  , m_remains(cost)
795  , m_maxDuration(NO_MAX_DURATION)
796  , m_finish(-1.0)
797  , m_failed(failed)
798  , m_start(surf_get_clock())
799  , m_cost(cost)
800  , p_model(model)
801  , p_data(NULL)
802  , p_variable(var)
803  , m_lastValue(0)
804  , m_lastUpdate(0)
805  , m_suspended(false)
806 {
807   #ifdef HAVE_TRACING
808     p_category = NULL;
809   #endif
810   p_stateHookup.prev = 0;
811   p_stateHookup.next = 0;
812   if (failed)
813     p_stateSet = getModel()->getFailedActionSet();
814   else
815     p_stateSet = getModel()->getRunningActionSet();
816
817   p_stateSet->push_back(*this);
818 }
819
820 Action::~Action() {
821 #ifdef HAVE_TRACING
822   xbt_free(p_category);
823 #endif
824 }
825
826 void Action::finish() {
827     m_finish = surf_get_clock();
828 }
829
830 e_surf_action_state_t Action::getState()
831 {
832   if (p_stateSet ==  getModel()->getReadyActionSet())
833     return SURF_ACTION_READY;
834   if (p_stateSet ==  getModel()->getRunningActionSet())
835     return SURF_ACTION_RUNNING;
836   if (p_stateSet ==  getModel()->getFailedActionSet())
837     return SURF_ACTION_FAILED;
838   if (p_stateSet ==  getModel()->getDoneActionSet())
839     return SURF_ACTION_DONE;
840   return SURF_ACTION_NOT_IN_THE_SYSTEM;
841 }
842
843 void Action::setState(e_surf_action_state_t state)
844 {
845   //surf_action_state_t action_state = &(action->model_type->states);
846   XBT_IN("(%p,%s)", this, surf_action_state_names[state]);
847   p_stateSet->erase(p_stateSet->iterator_to(*this));
848   if (state == SURF_ACTION_READY)
849     p_stateSet = getModel()->getReadyActionSet();
850   else if (state == SURF_ACTION_RUNNING)
851     p_stateSet = getModel()->getRunningActionSet();
852   else if (state == SURF_ACTION_FAILED)
853     p_stateSet = getModel()->getFailedActionSet();
854   else if (state == SURF_ACTION_DONE)
855     p_stateSet = getModel()->getDoneActionSet();
856   else
857     p_stateSet = NULL;
858
859   if (p_stateSet)
860         p_stateSet->push_back(*this);
861   XBT_OUT();
862 }
863
864 double Action::getBound()
865 {
866   return (p_variable) ? lmm_variable_getbound(p_variable) : 0;
867 }
868
869 void Action::setBound(double bound)
870 {
871   XBT_IN("(%p,%g)", this, bound);
872   if (p_variable)
873     lmm_update_variable_bound(getModel()->getMaxminSystem(), getVariable(), bound);
874
875   if (getModel()->getUpdateMechanism() == UM_LAZY)
876         heapRemove(getModel()->getActionHeap());
877   XBT_OUT();
878 }
879
880 double Action::getStartTime()
881 {
882   return m_start;
883 }
884
885 double Action::getFinishTime()
886 {
887   /* keep the function behavior, some models (cpu_ti) change the finish time before the action end */
888   return m_remains == 0 ? m_finish : -1;
889 }
890
891 void Action::setData(void* data)
892 {
893   p_data = data;
894 }
895
896 #ifdef HAVE_TRACING
897 void Action::setCategory(const char *category)
898 {
899   XBT_IN("(%p,%s)", this, category);
900   p_category = xbt_strdup(category);
901   XBT_OUT();
902 }
903 #endif
904
905 void Action::ref(){
906   m_refcount++;
907 }
908
909 void Action::setMaxDuration(double duration)
910 {
911   XBT_IN("(%p,%g)", this, duration);
912   m_maxDuration = duration;
913   if (getModel()->getUpdateMechanism() == UM_LAZY)      // remove action from the heap
914     heapRemove(getModel()->getActionHeap());
915   XBT_OUT();
916 }
917
918 void Action::gapRemove() {}
919
920 void Action::setPriority(double priority)
921 {
922   XBT_IN("(%p,%g)", this, priority);
923   m_priority = priority;
924   lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), priority);
925
926   if (getModel()->getUpdateMechanism() == UM_LAZY)
927         heapRemove(getModel()->getActionHeap());
928   XBT_OUT();
929 }
930
931 void Action::cancel(){
932   setState(SURF_ACTION_FAILED);
933   if (getModel()->getUpdateMechanism() == UM_LAZY) {
934         if (actionLmmHook::is_linked())
935           getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
936     heapRemove(getModel()->getActionHeap());
937   }
938 }
939
940 int Action::unref(){
941   m_refcount--;
942   if (!m_refcount) {
943         if (actionHook::is_linked())
944           p_stateSet->erase(p_stateSet->iterator_to(*this));
945         if (getVariable())
946           lmm_variable_free(getModel()->getMaxminSystem(), getVariable());
947         if (getModel()->getUpdateMechanism() == UM_LAZY) {
948           /* remove from heap */
949           heapRemove(getModel()->getActionHeap());
950       if (actionLmmHook::is_linked())
951             getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
952     }
953         delete this;
954         return 1;
955   }
956   return 0;
957 }
958
959 void Action::suspend()
960 {
961   XBT_IN("(%p)", this);
962   if (m_suspended != 2) {
963     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), 0.0);
964     m_suspended = 1;
965     if (getModel()->getUpdateMechanism() == UM_LAZY)
966       heapRemove(getModel()->getActionHeap());
967   }
968   XBT_OUT();
969 }
970
971 void Action::resume()
972 {
973   XBT_IN("(%p)", this);
974   if (m_suspended != 2) {
975     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), m_priority);
976     m_suspended = 0;
977     if (getModel()->getUpdateMechanism() == UM_LAZY)
978       heapRemove(getModel()->getActionHeap());
979   }
980   XBT_OUT();
981 }
982
983 bool Action::isSuspended()
984 {
985   return m_suspended == 1;
986 }
987 /* insert action on heap using a given key and a hat (heap_action_type)
988  * a hat can be of three types for communications:
989  *
990  * NORMAL = this is a normal heap entry stating the date to finish transmitting
991  * LATENCY = this is a heap entry to warn us when the latency is payed
992  * MAX_DURATION =this is a heap entry to warn us when the max_duration limit is reached
993  */
994 void Action::heapInsert(xbt_heap_t heap, double key, enum heap_action_type hat)
995 {
996   m_hat = hat;
997   xbt_heap_push(heap, this, key);
998 }
999
1000 void Action::heapRemove(xbt_heap_t heap)
1001 {
1002   m_hat = NOTSET;
1003   if (m_indexHeap >= 0) {
1004     xbt_heap_remove(heap, m_indexHeap);
1005   }
1006 }
1007
1008 /* added to manage the communication action's heap */
1009 void surf_action_lmm_update_index_heap(void *action, int i) {
1010   ((ActionPtr)action)->updateIndexHeap(i);
1011 }
1012
1013 void Action::updateIndexHeap(int i) {
1014   m_indexHeap = i;
1015 }
1016
1017 double Action::getRemains()
1018 {
1019   XBT_IN("(%p)", this);
1020   /* update remains before return it */
1021   if (getModel()->getUpdateMechanism() == UM_LAZY)      /* update remains before return it */
1022     updateRemainingLazy(surf_get_clock());
1023   XBT_OUT();
1024   return m_remains;
1025 }
1026
1027 double Action::getRemainsNoUpdate()
1028 {
1029   return m_remains;
1030 }
1031
1032 //FIXME split code in the right places
1033 void Action::updateRemainingLazy(double now)
1034 {
1035   double delta = 0.0;
1036
1037   if(getModel() == static_cast<ModelPtr>(surf_network_model))
1038   {
1039     if (m_suspended != 0)
1040       return;
1041   }
1042   else
1043   {
1044     xbt_assert(p_stateSet == getModel()->getRunningActionSet(),
1045         "You're updating an action that is not running.");
1046
1047       /* bogus priority, skip it */
1048     xbt_assert(m_priority > 0,
1049         "You're updating an action that seems suspended.");
1050   }
1051
1052   delta = now - m_lastUpdate;
1053
1054   if (m_remains > 0) {
1055     XBT_DEBUG("Updating action(%p): remains was %f, last_update was: %f", this, m_remains, m_lastUpdate);
1056     double_update(&m_remains, m_lastValue * delta);
1057
1058 #ifdef HAVE_TRACING
1059     if (getModel() == static_cast<ModelPtr>(surf_cpu_model_pm) && TRACE_is_enabled()) {
1060       ResourcePtr cpu = static_cast<ResourcePtr>(lmm_constraint_id(lmm_get_cnst_from_var(getModel()->getMaxminSystem(), getVariable(), 0)));
1061       TRACE_surf_host_set_utilization(cpu->getName(), getCategory(), m_lastValue, m_lastUpdate, now - m_lastUpdate);
1062     }
1063 #endif
1064     XBT_DEBUG("Updating action(%p): remains is now %f", this, m_remains);
1065   }
1066
1067   if(getModel() == static_cast<ModelPtr>(surf_network_model))
1068   {
1069     if (m_maxDuration != NO_MAX_DURATION)
1070       double_update(&m_maxDuration, delta);
1071
1072     //FIXME: duplicated code
1073     if ((m_remains <= 0) &&
1074         (lmm_get_variable_weight(getVariable()) > 0)) {
1075       finish();
1076       setState(SURF_ACTION_DONE);
1077       heapRemove(getModel()->getActionHeap());
1078     } else if (((m_maxDuration != NO_MAX_DURATION)
1079         && (m_maxDuration <= 0))) {
1080       finish();
1081       setState(SURF_ACTION_DONE);
1082       heapRemove(getModel()->getActionHeap());
1083     }
1084   }
1085
1086   m_lastUpdate = now;
1087   m_lastValue = lmm_variable_getvalue(getVariable());
1088 }
1089