Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
7d10b6fcc4962f4e212c738928d4c9fc8100264b
[simgrid.git] / src / xbt / xbt_replay.cpp
1 /* Copyright (c) 2010, 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 #include <xbt/ex.hpp>
8 #include "src/internal_config.h"
9 #include "xbt/sysdep.h"
10 #include "xbt/log.h"
11 #include "xbt/str.h"
12 #include "xbt/file.h"
13 #include "xbt/replay.h"
14
15 #include <boost/algorithm/string.hpp>
16 #include <ctype.h>
17 #include <errno.h>
18 #include <fstream>
19 #include <wchar.h>
20
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(replay,xbt,"Replay trace reader");
22
23 namespace simgrid {
24 namespace xbt {
25
26 class ReplayReader {
27   std::ifstream* fs;
28   std::string line;
29
30 public:
31   char* filename_;
32   int linenum = 0;
33
34   ReplayReader(const char* filename)
35   {
36     filename_ = xbt_strdup(filename);
37     fs        = new std::ifstream(filename, std::ifstream::in);
38   }
39   ~ReplayReader()
40   {
41     free(filename_);
42     delete fs;
43   }
44   bool get(std::vector<std::string>* evt);
45 };
46
47 bool ReplayReader::get(std::vector<std::string>* evt)
48 {
49   std::getline(*fs, line);
50   boost::trim(line);
51   XBT_DEBUG("got from trace: %s", line.c_str());
52   linenum++;
53
54   if (line.length() > 0 && line.find("#") == std::string::npos) {
55     std::vector<std::string> res;
56     boost::split(*evt, line, boost::is_any_of(" \t"), boost::token_compress_on);
57     return !fs->eof();
58   } else {
59     if (fs->eof())
60       return false;
61     else
62       return this->get(evt);
63   }
64 }
65 }
66 }
67
68 typedef struct s_replay_reader {
69   FILE *fp;
70   char *line;
71   size_t line_len;
72   char *position; /* stable storage */
73   char *filename; 
74   int linenum;
75 } s_xbt_replay_reader_t;
76
77 FILE *xbt_action_fp;
78
79 xbt_dict_t xbt_action_funs = nullptr;
80 xbt_dict_t xbt_action_queues = nullptr;
81
82 static char *action_line = nullptr;
83 static size_t action_len = 0;
84
85 int is_replay_active = 0 ;
86
87 static char **action_get_action(char *name);
88
89 static char *str_tolower (const char *str)
90 {
91   char *ret = xbt_strdup (str);
92   int n     = strlen(ret);
93   for (int i = 0; i < n; i++)
94     ret[i] = tolower (str[i]);
95   return ret;
96 }
97
98 int _xbt_replay_is_active(){
99   return is_replay_active;
100 }
101
102 /**
103  * \ingroup XBT_replay
104  * \brief Registers a function to handle a kind of action
105  *
106  * Registers a function to handle a kind of action
107  * This table is then used by \ref xbt_replay_action_runner
108  *
109  * The argument of the function is the line describing the action, splitted on spaces with xbt_str_split_quoted()
110  *
111  * \param action_name the reference name of the action.
112  * \param function prototype given by the type: void...(xbt_dynar_t action)
113  */
114 void xbt_replay_action_register(const char *action_name, action_fun function)
115 {
116   if (xbt_action_funs == nullptr) // If the user registers a function before the start
117     _xbt_replay_action_init();
118
119   char* lowername = str_tolower (action_name);
120   xbt_dict_set(xbt_action_funs, lowername, (void*) function, nullptr);
121   xbt_free(lowername);
122 }
123
124 /** @brief Initializes the replay mechanism, and returns true if (and only if) it was necessary
125  *
126  * It returns false if it was already done by another process.
127  */
128 int _xbt_replay_action_init()
129 {
130   if (xbt_action_funs)
131     return 0;
132   is_replay_active = 1;
133   xbt_action_funs = xbt_dict_new_homogeneous(nullptr);
134   xbt_action_queues = xbt_dict_new_homogeneous(nullptr);
135   return 1;
136 }
137
138 void _xbt_replay_action_exit()
139 {
140   xbt_dict_free(&xbt_action_queues);
141   xbt_dict_free(&xbt_action_funs);
142   free(action_line);
143   xbt_action_queues = nullptr;
144   xbt_action_funs = nullptr;
145   action_line = nullptr;
146 }
147
148 /**
149  * \ingroup XBT_replay
150  * \brief function used internally to actually run the replay
151
152  * \param argc argc .
153  * \param argv argv
154  */
155 int xbt_replay_action_runner(int argc, char *argv[])
156 {
157   if (xbt_action_fp) {              // A unique trace file
158     while (true) {
159       char **evt = action_get_action(argv[0]);
160       if (evt == nullptr)
161         break;
162
163       char* lowername = str_tolower (evt[1]);
164       action_fun function = (action_fun)xbt_dict_get(xbt_action_funs, lowername);
165       xbt_free(lowername);
166       try {
167         function((const char **)evt);
168       }
169       catch(xbt_ex& e) {
170         xbt_die("Replay error :\n %s", e.what());
171       }
172       for (int i=0;evt[i]!= nullptr;i++)
173         free(evt[i]);
174       free(evt);
175     }
176   } else {                      // Should have got my trace file in argument
177     std::vector<std::string>* evt = new std::vector<std::string>();
178     xbt_assert(argc >= 2,
179                 "No '%s' agent function provided, no simulation-wide trace file provided, "
180                 "and no process-wide trace file provided in deployment file. Aborting.", argv[0]
181         );
182     simgrid::xbt::ReplayReader* reader = new simgrid::xbt::ReplayReader(argv[1]);
183     while (reader->get(evt)) {
184       if (evt->at(0).compare(argv[0]) == 0) {
185         std::string lowername = evt->at(1);
186         boost::algorithm::to_lower(lowername);
187         char** args = new char*[evt->size() + 1];
188         int i       = 0;
189         for (auto arg : *evt) {
190           args[i] = xbt_strdup(arg.c_str());
191           i++;
192         }
193         args[i]             = nullptr;
194         action_fun function = (action_fun)xbt_dict_get(xbt_action_funs, lowername.c_str());
195         try {
196           function(args);
197         } catch(xbt_ex& e) {
198           for (unsigned int j = 0; j < evt->size(); j++)
199             xbt_free(args[j]);
200           delete args;
201           evt->clear();
202           xbt_die("Replay error on line %d of file %s :\n %s", reader->linenum, reader->filename_, e.what());
203         }
204         for (unsigned int j = 0; j < evt->size(); j++)
205           xbt_free(args[j]);
206         delete[] args;
207       } else {
208         XBT_WARN("%s:%d: Ignore trace element not for me", reader->filename_, reader->linenum);
209       }
210       evt->clear();
211     }
212     delete evt;
213     delete reader;
214   }
215   return 0;
216 }
217
218 static char **action_get_action(char *name)
219 {
220   xbt_dynar_t evt = nullptr;
221   char *evtname = nullptr;
222
223   xbt_dynar_t myqueue = (xbt_dynar_t) xbt_dict_get_or_null(xbt_action_queues, name);
224   if (myqueue == nullptr || xbt_dynar_is_empty(myqueue)) {      // nothing stored for me. Read the file further
225     if (xbt_action_fp == nullptr) {    // File closed now. There's nothing more to read. I'm out of here
226       goto todo_done;
227     }
228     // Read lines until I reach something for me (which breaks in loop body)
229     // or end of file reached
230     while (xbt_getline(&action_line, &action_len, xbt_action_fp) != -1) {
231       // cleanup and split the string I just read
232       char *comment = strchr(action_line, '#');
233       if (comment != nullptr)
234         *comment = '\0';
235       xbt_str_trim(action_line, nullptr);
236       if (action_line[0] == '\0')
237         continue;
238       /* we cannot split in place here because we parse&store several lines for
239        * the colleagues... */
240       evt = xbt_str_split_quoted(action_line);
241
242       // if it's for me, I'm done
243       evtname = xbt_dynar_get_as(evt, 0, char *);
244       if (!strcasecmp(name, evtname)) {
245         return (char**) xbt_dynar_to_array(evt);
246       } else {
247         // Else, I have to store it for the relevant colleague
248         xbt_dynar_t otherqueue =
249             (xbt_dynar_t) xbt_dict_get_or_null(xbt_action_queues, evtname);
250         if (otherqueue == nullptr) {       // Damn. Create the queue of that guy
251           otherqueue = xbt_dynar_new(sizeof(xbt_dynar_t), xbt_dynar_free_voidp);
252           xbt_dict_set(xbt_action_queues, evtname, otherqueue, nullptr);
253         }
254         xbt_dynar_push(otherqueue, &evt);
255       }
256     }
257     // end of file reached while searching in vain for more work
258   } else {
259     // Get something from my queue and return it
260     xbt_dynar_shift(myqueue, &evt);
261     return (char**) xbt_dynar_to_array(evt);
262   }
263
264   // I did all my actions for me in the file (either I closed the file, or a colleague did)
265   // Let's cleanup before leaving
266 todo_done:
267   if (myqueue != nullptr) {
268     xbt_dynar_free(&myqueue);
269     xbt_dict_remove(xbt_action_queues, name);
270   }
271   return nullptr;
272 }