Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[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   name_list = strdup(table[0].name);
338   for (i = 1; table[i].name; i++) {
339     name_list = (char *) xbt_realloc(name_list, strlen(name_list) + strlen(table[i].name) + 3);
340     strcat(name_list, ", ");
341     strcat(name_list, table[i].name);
342   }
343   xbt_die("Model '%s' is invalid! Valid models are: %s.", name, name_list);
344   return -1;
345 }
346
347 static XBT_INLINE void routing_asr_host_free(void *p)
348 {
349   delete ((RoutingEdgePtr) p);
350 }
351
352 static XBT_INLINE void routing_asr_prop_free(void *p)
353 {
354   xbt_dict_t elm = (xbt_dict_t) p;
355   xbt_dict_free(&elm);
356 }
357
358 static XBT_INLINE void surf_cpu_free(void *r)
359 {
360   delete static_cast<CpuPtr>(r);
361 }
362
363 static XBT_INLINE void surf_link_free(void *r)
364 {
365   delete static_cast<NetworkLinkPtr>(r);
366 }
367
368 static XBT_INLINE void surf_workstation_free(void *r)
369 {
370   delete static_cast<WorkstationPtr>(r);
371 }
372
373
374 void sg_version(int *ver_major,int *ver_minor,int *ver_patch) {
375   *ver_major = SIMGRID_VERSION_MAJOR;
376   *ver_minor = SIMGRID_VERSION_MINOR;
377   *ver_patch = SIMGRID_VERSION_PATCH;
378 }
379
380 void surf_init(int *argc, char **argv)
381 {
382   XBT_DEBUG("Create all Libs");
383   host_lib = xbt_lib_new();
384   link_lib = xbt_lib_new();
385   as_router_lib = xbt_lib_new();
386   storage_lib = xbt_lib_new();
387   storage_type_lib = xbt_lib_new();
388   file_lib = xbt_lib_new();
389   watched_hosts_lib = xbt_dict_new_homogeneous(NULL);
390
391   XBT_DEBUG("Add routing levels");
392   ROUTING_HOST_LEVEL = xbt_lib_add_level(host_lib,routing_asr_host_free);
393   ROUTING_ASR_LEVEL  = xbt_lib_add_level(as_router_lib,routing_asr_host_free);
394   ROUTING_PROP_ASR_LEVEL = xbt_lib_add_level(as_router_lib,routing_asr_prop_free);
395
396   XBT_DEBUG("Add SURF levels");
397   SURF_CPU_LEVEL = xbt_lib_add_level(host_lib,surf_cpu_free);
398   SURF_WKS_LEVEL = xbt_lib_add_level(host_lib,surf_workstation_free);
399   SURF_LINK_LEVEL = xbt_lib_add_level(link_lib,surf_link_free);
400
401   xbt_init(argc, argv);
402   if (!model_list)
403     model_list = xbt_dynar_new(sizeof(ModelPtr), NULL);
404   if (!model_list_invoke)
405     model_list_invoke = xbt_dynar_new(sizeof(ModelPtr), NULL);
406   if (!history)
407     history = tmgr_history_new();
408
409 #ifdef HAVE_TRACING
410   TRACE_add_start_function(TRACE_surf_alloc);
411   TRACE_add_end_function(TRACE_surf_release);
412 #endif
413
414   sg_config_init(argc, argv);
415
416   if (MC_is_active())
417     MC_memory_init();
418 }
419
420 void surf_exit(void)
421 {
422   unsigned int iter;
423   ModelPtr model = NULL;
424
425 #ifdef HAVE_TRACING
426   TRACE_end();                  /* Just in case it was not called by the upper
427                                  * layer (or there is no upper layer) */
428 #endif
429
430   sg_config_finalize();
431
432   xbt_dynar_free(&host_that_restart);
433   xbt_dynar_free(&surf_path);
434
435   xbt_lib_free(&host_lib);
436   xbt_lib_free(&link_lib);
437   xbt_lib_free(&as_router_lib);
438   xbt_lib_free(&storage_lib);
439   xbt_lib_free(&storage_type_lib);
440
441   xbt_dict_free(&watched_hosts_lib);
442
443   xbt_dynar_foreach(model_list, iter, model)
444     delete model;
445   xbt_dynar_free(&model_list);
446   xbt_dynar_free(&model_list_invoke);
447   routing_exit();
448
449   surf_callback_emit(surfExitCallbacks);
450
451   if (maxmin_system) {
452     lmm_system_free(maxmin_system);
453     maxmin_system = NULL;
454   }
455   if (history) {
456     tmgr_history_free(history);
457     history = NULL;
458   }
459
460 #ifdef CONTEXT_THREADS
461   xbt_parmap_destroy(surf_parmap);
462 #endif
463
464   xbt_free(surf_mins);
465   surf_mins = NULL;
466
467   tmgr_finalize();
468   surf_parse_lex_destroy();
469   surf_parse_free_callbacks();
470
471   NOW = 0;                      /* Just in case the user plans to restart the simulation afterward */
472 }
473
474 /*********
475  * Model *
476  *********/
477
478 Model::Model(const char *name)
479   : p_maxminSystem(NULL)
480   , p_name(name)
481 {
482   p_readyActionSet = new ActionList();
483   p_runningActionSet = new ActionList();
484   p_failedActionSet = new ActionList();
485   p_doneActionSet = new ActionList();
486
487   p_modifiedSet = NULL;
488   p_actionHeap = NULL;
489   p_updateMechanism = UM_UNDEFINED;
490   m_selectiveUpdate = 0;
491 }
492
493 Model::~Model(){
494   delete p_readyActionSet;
495   delete p_runningActionSet;
496   delete p_failedActionSet;
497   delete p_doneActionSet;
498 }
499
500 double Model::shareResources(double now)
501 {
502   //FIXME: set the good function once and for all
503   if (p_updateMechanism == UM_LAZY)
504         return shareResourcesLazy(now);
505   else if (p_updateMechanism == UM_FULL)
506         return shareResourcesFull(now);
507   else
508         xbt_die("Invalid cpu update mechanism!");
509 }
510
511 double Model::shareResourcesLazy(double now)
512 {
513   ActionPtr action = NULL;
514   double min = -1;
515   double value;
516
517   XBT_DEBUG
518       ("Before share resources, the size of modified actions set is %zd",
519        p_modifiedSet->size());
520
521   lmm_solve(p_maxminSystem);
522
523   XBT_DEBUG
524       ("After share resources, The size of modified actions set is %zd",
525        p_modifiedSet->size());
526
527   while(!p_modifiedSet->empty()) {
528         action = &(p_modifiedSet->front());
529         p_modifiedSet->pop_front();
530     int max_dur_flag = 0;
531
532     if (action->getStateSet() != p_runningActionSet)
533       continue;
534
535     /* bogus priority, skip it */
536     if (action->getPriority() <= 0)
537       continue;
538
539     action->updateRemainingLazy(now);
540
541     min = -1;
542     value = lmm_variable_getvalue(action->getVariable());
543     if (value > 0) {
544       if (action->getRemains() > 0) {
545         value = action->getRemainsNoUpdate() / value;
546         min = now + value;
547       } else {
548         value = 0.0;
549         min = now;
550       }
551     }
552
553     if ((action->getMaxDuration() != NO_MAX_DURATION)
554         && (min == -1
555             || action->getStartTime() +
556             action->getMaxDuration() < min)) {
557       min = action->getStartTime() +
558           action->getMaxDuration();
559       max_dur_flag = 1;
560     }
561
562     XBT_DEBUG("Action(%p) Start %f Finish %f Max_duration %f", action,
563         action->getStartTime(), now + value,
564         action->getMaxDuration());
565
566     if (min != -1) {
567       action->heapRemove(p_actionHeap);
568       action->heapInsert(p_actionHeap, min, max_dur_flag ? MAX_DURATION : NORMAL);
569       XBT_DEBUG("Insert at heap action(%p) min %f now %f", action, min,
570                 now);
571     } else DIE_IMPOSSIBLE;
572   }
573
574   //hereafter must have already the min value for this resource model
575   if (xbt_heap_size(p_actionHeap) > 0)
576     min = xbt_heap_maxkey(p_actionHeap) - now;
577   else
578     min = -1;
579
580   XBT_DEBUG("The minimum with the HEAP %f", min);
581
582   return min;
583 }
584
585 double Model::shareResourcesFull(double /*now*/) {
586   THROW_UNIMPLEMENTED;
587 }
588
589 double Model::shareResourcesMaxMin(ActionListPtr running_actions,
590                           lmm_system_t sys,
591                           void (*solve) (lmm_system_t))
592 {
593   ActionPtr action = NULL;
594   double min = -1;
595   double value = -1;
596
597   solve(sys);
598
599   ActionList::iterator it(running_actions->begin()), itend(running_actions->end());
600   for(; it != itend ; ++it) {
601           action = &*it;
602     value = lmm_variable_getvalue(action->getVariable());
603     if ((value > 0) || (action->getMaxDuration() >= 0))
604       break;
605   }
606
607   if (!action)
608     return -1.0;
609
610   if (value > 0) {
611     if (action->getRemains() > 0)
612       min = action->getRemainsNoUpdate() / value;
613     else
614       min = 0.0;
615     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min))
616       min = action->getMaxDuration();
617   } else
618     min = action->getMaxDuration();
619
620
621   for (++it; it != itend; ++it) {
622         action = &*it;
623     value = lmm_variable_getvalue(action->getVariable());
624     if (value > 0) {
625       if (action->getRemains() > 0)
626         value = action->getRemainsNoUpdate() / value;
627       else
628         value = 0.0;
629       if (value < min) {
630         min = value;
631         XBT_DEBUG("Updating min (value) with %p: %f", action, min);
632       }
633     }
634     if ((action->getMaxDuration() >= 0) && (action->getMaxDuration() < min)) {
635       min = action->getMaxDuration();
636       XBT_DEBUG("Updating min (duration) with %p: %f", action, min);
637     }
638   }
639   XBT_DEBUG("min value : %f", min);
640
641   return min;
642 }
643
644 void Model::updateActionsState(double now, double delta)
645 {
646   if (p_updateMechanism == UM_FULL)
647         updateActionsStateFull(now, delta);
648   else if (p_updateMechanism == UM_LAZY)
649         updateActionsStateLazy(now, delta);
650   else
651         xbt_die("Invalid cpu update mechanism!");
652 }
653
654 void Model::updateActionsStateLazy(double /*now*/, double /*delta*/)
655 {
656 }
657
658 void Model::updateActionsStateFull(double /*now*/, double /*delta*/)
659 {
660 }
661
662 /************
663  * Resource *
664  ************/
665
666 Resource::Resource()
667 : p_name(NULL), p_properties(NULL), p_model(NULL)
668 {}
669
670 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props)
671   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
672   , m_running(true), m_stateCurrent(SURF_RESOURCE_ON)
673 {}
674
675 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props, lmm_constraint_t constraint)
676   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
677   , m_running(true), m_stateCurrent(SURF_RESOURCE_ON), p_constraint(constraint)
678 {}
679
680 Resource::Resource(ModelPtr model, const char *name, xbt_dict_t props, e_surf_resource_state_t stateInit)
681   : p_name(xbt_strdup(name)), p_properties(props), p_model(model)
682   , m_running(true), m_stateCurrent(stateInit)
683 {}
684
685 Resource::~Resource() {
686   xbt_free((void*)p_name);
687   xbt_dict_free(&p_properties);
688 }
689
690 e_surf_resource_state_t Resource::getState()
691 {
692   return m_stateCurrent;
693 }
694
695 void Resource::setState(e_surf_resource_state_t state)
696 {
697   m_stateCurrent = state;
698 }
699
700 bool Resource::isOn()
701 {
702   return m_running;
703 }
704
705 void Resource::turnOn()
706 {
707   if (!m_running) {
708     m_running = true;
709   }
710 }
711
712 void Resource::turnOff()
713 {
714   if (m_running) {
715     m_running = false;
716   }
717 }
718
719 ModelPtr Resource::getModel() {
720   return p_model;
721 }
722
723 const char *Resource::getName() {
724   return p_name;
725 }
726
727 xbt_dict_t Resource::getProperties() {
728   if (p_properties==NULL)
729         p_properties = xbt_dict_new();
730   return p_properties;
731 }
732
733 lmm_constraint_t Resource::getConstraint() {
734   return p_constraint;
735 }
736
737 /**********
738  * Action *
739  **********/
740
741 const char *surf_action_state_names[6] = {
742   "SURF_ACTION_READY",
743   "SURF_ACTION_RUNNING",
744   "SURF_ACTION_FAILED",
745   "SURF_ACTION_DONE",
746   "SURF_ACTION_TO_FREE",
747   "SURF_ACTION_NOT_IN_THE_SYSTEM"
748 };
749
750 Action::Action()
751 : m_refcount(1)
752 {}
753
754 Action::Action(ModelPtr model, double cost, bool failed)
755  : m_priority(1.0)
756  , m_refcount(1)
757  , m_remains(cost)
758  , m_maxDuration(NO_MAX_DURATION)
759  , m_finish(-1.0)
760  , m_failed(failed)
761  , m_start(surf_get_clock())
762  , m_cost(cost)
763  , p_model(model)
764  , p_data(NULL)
765  , p_variable(NULL)
766  , m_lastValue(0)
767  , m_lastUpdate(0)
768  , m_suspended(false)
769 {
770   #ifdef HAVE_TRACING
771     p_category = NULL;
772   #endif
773   p_stateHookup.prev = 0;
774   p_stateHookup.next = 0;
775   if (failed)
776     p_stateSet = getModel()->getFailedActionSet();
777   else
778     p_stateSet = getModel()->getRunningActionSet();
779
780   p_stateSet->push_back(*this);
781 }
782
783 Action::Action(ModelPtr model, double cost, bool failed, lmm_variable_t var)
784  : m_priority(1.0)
785  , m_refcount(1)
786  , m_remains(cost)
787  , m_maxDuration(NO_MAX_DURATION)
788  , m_finish(-1.0)
789  , m_failed(failed)
790  , m_start(surf_get_clock())
791  , m_cost(cost)
792  , p_model(model)
793  , p_data(NULL)
794  , p_variable(var)
795  , m_lastValue(0)
796  , m_lastUpdate(0)
797  , m_suspended(false)
798 {
799   #ifdef HAVE_TRACING
800     p_category = NULL;
801   #endif
802   p_stateHookup.prev = 0;
803   p_stateHookup.next = 0;
804   if (failed)
805     p_stateSet = getModel()->getFailedActionSet();
806   else
807     p_stateSet = getModel()->getRunningActionSet();
808
809   p_stateSet->push_back(*this);
810 }
811
812 Action::~Action() {
813 #ifdef HAVE_TRACING
814   xbt_free(p_category);
815 #endif
816 }
817
818 void Action::finish() {
819     m_finish = surf_get_clock();
820 }
821
822 e_surf_action_state_t Action::getState()
823 {
824   if (p_stateSet ==  getModel()->getReadyActionSet())
825     return SURF_ACTION_READY;
826   if (p_stateSet ==  getModel()->getRunningActionSet())
827     return SURF_ACTION_RUNNING;
828   if (p_stateSet ==  getModel()->getFailedActionSet())
829     return SURF_ACTION_FAILED;
830   if (p_stateSet ==  getModel()->getDoneActionSet())
831     return SURF_ACTION_DONE;
832   return SURF_ACTION_NOT_IN_THE_SYSTEM;
833 }
834
835 void Action::setState(e_surf_action_state_t state)
836 {
837   //surf_action_state_t action_state = &(action->model_type->states);
838   XBT_IN("(%p,%s)", this, surf_action_state_names[state]);
839   p_stateSet->erase(p_stateSet->iterator_to(*this));
840   if (state == SURF_ACTION_READY)
841     p_stateSet = getModel()->getReadyActionSet();
842   else if (state == SURF_ACTION_RUNNING)
843     p_stateSet = getModel()->getRunningActionSet();
844   else if (state == SURF_ACTION_FAILED)
845     p_stateSet = getModel()->getFailedActionSet();
846   else if (state == SURF_ACTION_DONE)
847     p_stateSet = getModel()->getDoneActionSet();
848   else
849     p_stateSet = NULL;
850
851   if (p_stateSet)
852         p_stateSet->push_back(*this);
853   XBT_OUT();
854 }
855
856 double Action::getBound()
857 {
858   return (p_variable) ? lmm_variable_getbound(p_variable) : 0;
859 }
860
861 void Action::setBound(double bound)
862 {
863   XBT_IN("(%p,%g)", this, bound);
864   if (p_variable)
865     lmm_update_variable_bound(getModel()->getMaxminSystem(), getVariable(), bound);
866
867   if (getModel()->getUpdateMechanism() == UM_LAZY)
868         heapRemove(getModel()->getActionHeap());
869   XBT_OUT();
870 }
871
872 double Action::getStartTime()
873 {
874   return m_start;
875 }
876
877 double Action::getFinishTime()
878 {
879   /* keep the function behavior, some models (cpu_ti) change the finish time before the action end */
880   return m_remains == 0 ? m_finish : -1;
881 }
882
883 void Action::setData(void* data)
884 {
885   p_data = data;
886 }
887
888 #ifdef HAVE_TRACING
889 void Action::setCategory(const char *category)
890 {
891   XBT_IN("(%p,%s)", this, category);
892   p_category = xbt_strdup(category);
893   XBT_OUT();
894 }
895 #endif
896
897 void Action::ref(){
898   m_refcount++;
899 }
900
901 void Action::setMaxDuration(double duration)
902 {
903   XBT_IN("(%p,%g)", this, duration);
904   m_maxDuration = duration;
905   if (getModel()->getUpdateMechanism() == UM_LAZY)      // remove action from the heap
906     heapRemove(getModel()->getActionHeap());
907   XBT_OUT();
908 }
909
910 void Action::gapRemove() {}
911
912 void Action::setPriority(double priority)
913 {
914   XBT_IN("(%p,%g)", this, priority);
915   m_priority = priority;
916   lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), priority);
917
918   if (getModel()->getUpdateMechanism() == UM_LAZY)
919         heapRemove(getModel()->getActionHeap());
920   XBT_OUT();
921 }
922
923 void Action::cancel(){
924   setState(SURF_ACTION_FAILED);
925   if (getModel()->getUpdateMechanism() == UM_LAZY) {
926         if (actionLmmHook::is_linked())
927           getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
928     heapRemove(getModel()->getActionHeap());
929   }
930 }
931
932 int Action::unref(){
933   m_refcount--;
934   if (!m_refcount) {
935         if (actionHook::is_linked())
936           p_stateSet->erase(p_stateSet->iterator_to(*this));
937         if (getVariable())
938           lmm_variable_free(getModel()->getMaxminSystem(), getVariable());
939         if (getModel()->getUpdateMechanism() == UM_LAZY) {
940           /* remove from heap */
941           heapRemove(getModel()->getActionHeap());
942       if (actionLmmHook::is_linked())
943             getModel()->getModifiedSet()->erase(getModel()->getModifiedSet()->iterator_to(*this));
944     }
945         delete this;
946         return 1;
947   }
948   return 0;
949 }
950
951 void Action::suspend()
952 {
953   XBT_IN("(%p)", this);
954   if (m_suspended != 2) {
955     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), 0.0);
956     m_suspended = 1;
957     if (getModel()->getUpdateMechanism() == UM_LAZY)
958       heapRemove(getModel()->getActionHeap());
959   }
960   XBT_OUT();
961 }
962
963 void Action::resume()
964 {
965   XBT_IN("(%p)", this);
966   if (m_suspended != 2) {
967     lmm_update_variable_weight(getModel()->getMaxminSystem(), getVariable(), m_priority);
968     m_suspended = 0;
969     if (getModel()->getUpdateMechanism() == UM_LAZY)
970       heapRemove(getModel()->getActionHeap());
971   }
972   XBT_OUT();
973 }
974
975 bool Action::isSuspended()
976 {
977   return m_suspended == 1;
978 }
979 /* insert action on heap using a given key and a hat (heap_action_type)
980  * a hat can be of three types for communications:
981  *
982  * NORMAL = this is a normal heap entry stating the date to finish transmitting
983  * LATENCY = this is a heap entry to warn us when the latency is payed
984  * MAX_DURATION =this is a heap entry to warn us when the max_duration limit is reached
985  */
986 void Action::heapInsert(xbt_heap_t heap, double key, enum heap_action_type hat)
987 {
988   m_hat = hat;
989   xbt_heap_push(heap, this, key);
990 }
991
992 void Action::heapRemove(xbt_heap_t heap)
993 {
994   m_hat = NOTSET;
995   if (m_indexHeap >= 0) {
996     xbt_heap_remove(heap, m_indexHeap);
997   }
998 }
999
1000 /* added to manage the communication action's heap */
1001 void surf_action_lmm_update_index_heap(void *action, int i) {
1002   ((ActionPtr)action)->updateIndexHeap(i);
1003 }
1004
1005 void Action::updateIndexHeap(int i) {
1006   m_indexHeap = i;
1007 }
1008
1009 double Action::getRemains()
1010 {
1011   XBT_IN("(%p)", this);
1012   /* update remains before return it */
1013   if (getModel()->getUpdateMechanism() == UM_LAZY)      /* update remains before return it */
1014     updateRemainingLazy(surf_get_clock());
1015   XBT_OUT();
1016   return m_remains;
1017 }
1018
1019 double Action::getRemainsNoUpdate()
1020 {
1021   return m_remains;
1022 }
1023
1024 //FIXME split code in the right places
1025 void Action::updateRemainingLazy(double now)
1026 {
1027   double delta = 0.0;
1028
1029   if(getModel() == static_cast<ModelPtr>(surf_network_model))
1030   {
1031     if (m_suspended != 0)
1032       return;
1033   }
1034   else
1035   {
1036     xbt_assert(p_stateSet == getModel()->getRunningActionSet(),
1037         "You're updating an action that is not running.");
1038
1039       /* bogus priority, skip it */
1040     xbt_assert(m_priority > 0,
1041         "You're updating an action that seems suspended.");
1042   }
1043
1044   delta = now - m_lastUpdate;
1045
1046   if (m_remains > 0) {
1047     XBT_DEBUG("Updating action(%p): remains was %f, last_update was: %f", this, m_remains, m_lastUpdate);
1048     double_update(&m_remains, m_lastValue * delta);
1049
1050 #ifdef HAVE_TRACING
1051     if (getModel() == static_cast<ModelPtr>(surf_cpu_model_pm) && TRACE_is_enabled()) {
1052       ResourcePtr cpu = static_cast<ResourcePtr>(lmm_constraint_id(lmm_get_cnst_from_var(getModel()->getMaxminSystem(), getVariable(), 0)));
1053       TRACE_surf_host_set_utilization(cpu->getName(), getCategory(), m_lastValue, m_lastUpdate, now - m_lastUpdate);
1054     }
1055 #endif
1056     XBT_DEBUG("Updating action(%p): remains is now %f", this, m_remains);
1057   }
1058
1059   if(getModel() == static_cast<ModelPtr>(surf_network_model))
1060   {
1061     if (m_maxDuration != NO_MAX_DURATION)
1062       double_update(&m_maxDuration, delta);
1063
1064     //FIXME: duplicated code
1065     if ((m_remains <= 0) &&
1066         (lmm_get_variable_weight(getVariable()) > 0)) {
1067       finish();
1068       setState(SURF_ACTION_DONE);
1069       heapRemove(getModel()->getActionHeap());
1070     } else if (((m_maxDuration != NO_MAX_DURATION)
1071         && (m_maxDuration <= 0))) {
1072       finish();
1073       setState(SURF_ACTION_DONE);
1074       heapRemove(getModel()->getActionHeap());
1075     }
1076   }
1077
1078   m_lastUpdate = now;
1079   m_lastValue = lmm_variable_getvalue(getVariable());
1080 }
1081