Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use boost::lexical_cast instead of xbt_str_parse_* in C++ files.
[simgrid.git] / src / mc / remote / AppSide.cpp
1 /* Copyright (c) 2015-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/mc/remote/AppSide.hpp"
7 #include "simgrid/s4u/Host.hpp"
8 #include "src/internal_config.h"
9 #include "src/kernel/EngineImpl.hpp"
10 #include "src/kernel/actor/ActorImpl.hpp"
11 #include "src/kernel/actor/SimcallObserver.hpp"
12 #include "src/mc/mc_base.hpp"
13 #include "src/mc/mc_config.hpp"
14 #include "src/mc/mc_environ.h"
15 #if HAVE_SMPI
16 #include "src/smpi/include/private.hpp"
17 #endif
18 #include "src/sthread/sthread.h"
19 #include "src/xbt/coverage.h"
20 #include "xbt/str.h"
21 #include <simgrid/modelchecker.h>
22
23 #include <boost/lexical_cast.hpp>
24 #include <cerrno>
25 #include <cinttypes>
26 #include <cstdio> // setvbuf
27 #include <cstdlib>
28 #include <memory>
29 #include <numeric>
30 #include <sys/ptrace.h>
31 #include <sys/socket.h>
32 #include <sys/types.h>
33 #include <sys/un.h>
34 #include <sys/wait.h>
35
36 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_client, mc, "MC client logic");
37 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
38
39 namespace simgrid::mc {
40
41 std::unique_ptr<AppSide> AppSide::instance_;
42
43 AppSide* AppSide::get()
44 {
45   // Only initialize the MC world once
46   if (instance_ != nullptr)
47     return instance_.get();
48
49   if (std::getenv(MC_ENV_SOCKET_FD) == nullptr) // We are not in MC mode: don't initialize the MC world
50     return nullptr;
51
52   XBT_DEBUG("Initialize the MC world.");
53
54   simgrid::mc::set_model_checking_mode(ModelCheckingMode::APP_SIDE);
55
56   setvbuf(stdout, nullptr, _IOLBF, 0);
57
58   // Fetch socket from MC_ENV_SOCKET_FD:
59   const char* fd_env = std::getenv(MC_ENV_SOCKET_FD);
60   int fd;
61   try {
62     fd = boost::lexical_cast<int>(fd_env);
63   } catch (boost::bad_lexical_cast const&) {
64     xbt_die("Not a number in variable '%s': %s", MC_ENV_SOCKET_FD, fd_env);
65   }
66   XBT_DEBUG("Model-checked application found socket FD %i", fd);
67
68   instance_ = std::make_unique<simgrid::mc::AppSide>(fd);
69
70   instance_->handle_messages();
71   return instance_.get();
72 }
73
74 void AppSide::handle_deadlock_check(const s_mc_message_t*) const
75 {
76   const auto* engine     = kernel::EngineImpl::get_instance();
77   const auto& actor_list = engine->get_actor_list();
78   bool deadlock = not actor_list.empty() && std::none_of(begin(actor_list), end(actor_list), [](const auto& kv) {
79     return mc::actor_is_enabled(kv.second);
80   });
81
82   if (deadlock) {
83     XBT_CINFO(mc_global, "**************************");
84     XBT_CINFO(mc_global, "*** DEADLOCK DETECTED ***");
85     XBT_CINFO(mc_global, "**************************");
86     engine->display_all_actor_status();
87   }
88   // Send result:
89   s_mc_message_int_t answer = {};
90   answer.type  = MessageType::DEADLOCK_CHECK_REPLY;
91   answer.value = deadlock;
92   xbt_assert(channel_.send(answer) == 0, "Could not send response: %s", strerror(errno));
93 }
94 void AppSide::handle_simcall_execute(const s_mc_message_simcall_execute_t* message) const
95 {
96   kernel::actor::ActorImpl* actor = kernel::EngineImpl::get_instance()->get_actor_by_pid(message->aid_);
97   xbt_assert(actor != nullptr, "Invalid pid %ld", message->aid_);
98   xbt_assert(actor->simcall_.observer_ == nullptr || actor->simcall_.observer_->is_enabled(),
99              "Please, model-checker, don't execute disabled transitions.");
100
101   // The client may send some messages to the server while processing the transition
102   actor->simcall_handle(message->times_considered_);
103   // Say the server that the transition is over and that it should proceed
104   xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send MESSAGE_WAITING to model-checker: %s",
105              strerror(errno));
106
107   // Finish the RPC from the server: return a serialized observer, to build a Transition on Checker side
108   s_mc_message_simcall_execute_answer_t answer = {};
109   answer.type                                  = MessageType::SIMCALL_EXECUTE_REPLY;
110   std::stringstream stream;
111   if (actor->simcall_.observer_ != nullptr) {
112     actor->simcall_.observer_->serialize(stream);
113   } else {
114     stream << (short)mc::Transition::Type::UNKNOWN;
115   }
116   std::string str = stream.str();
117   xbt_assert(str.size() + 1 <= answer.buffer.size(),
118              "The serialized simcall is too large for the buffer. Please fix the code.");
119   strncpy(answer.buffer.data(), str.c_str(), answer.buffer.size() - 1);
120   answer.buffer.back() = '\0';
121
122   XBT_DEBUG("send SIMCALL_EXECUTE_ANSWER(%s) ~> '%s'", actor->get_cname(), str.c_str());
123   xbt_assert(channel_.send(answer) == 0, "Could not send response: %s", strerror(errno));
124 }
125
126 void AppSide::handle_finalize(const s_mc_message_int_t* msg) const
127 {
128   bool terminate_asap = msg->value;
129   XBT_DEBUG("Finalize (terminate = %d)", (int)terminate_asap);
130   if (not terminate_asap) {
131     if (XBT_LOG_ISENABLED(mc_client, xbt_log_priority_debug))
132       kernel::EngineImpl::get_instance()->display_all_actor_status();
133 #if HAVE_SMPI
134     XBT_DEBUG("Smpi_enabled: %d", SMPI_is_inited());
135     if (SMPI_is_inited())
136       SMPI_finalize();
137 #endif
138   }
139   coverage_checkpoint();
140   xbt_assert(channel_.send(MessageType::FINALIZE_REPLY) == 0, "Could not answer to FINALIZE: %s", strerror(errno));
141   std::fflush(stdout);
142   if (terminate_asap)
143     ::_Exit(0);
144 }
145 void AppSide::handle_fork(const s_mc_message_fork_t* msg)
146 {
147   int status;
148   int pid;
149   /* Reap any zombie child, saving its status for later use in AppSide::handle_wait_child() */
150   while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
151     child_statuses_[pid] = status;
152
153   pid = fork();
154   xbt_assert(pid >= 0, "Could not fork application sub-process: %s.", strerror(errno));
155
156   if (pid == 0) { // Child
157     int sock = socket(AF_UNIX,
158 #ifdef __APPLE__
159                       SOCK_STREAM, /* Mac OSX does not have AF_UNIX + SOCK_SEQPACKET, even if that's faster*/
160 #else
161                       SOCK_SEQPACKET,
162 #endif
163                       0);
164
165     struct sockaddr_un addr = {};
166     addr.sun_family         = AF_UNIX;
167     std::copy_n(begin(msg->socket_name), MC_SOCKET_NAME_LEN, addr.sun_path);
168
169     xbt_assert(connect(sock, (struct sockaddr*)&addr, sizeof addr) >= 0, "Cannot connect to Checker on %c%s: %s.",
170                (addr.sun_path[0] ? addr.sun_path[0] : '@'), addr.sun_path + 1, strerror(errno));
171
172     channel_.reset_socket(sock);
173
174     s_mc_message_int_t answer = {};
175     answer.type               = MessageType::FORK_REPLY;
176     answer.value              = getpid();
177     xbt_assert(channel_.send(answer) == 0, "Could not send response to WAIT_CHILD_REPLY: %s", strerror(errno));
178   } else {
179     XBT_VERB("App %d forks subprocess %d.", getpid(), pid);
180   }
181 }
182 void AppSide::handle_wait_child(const s_mc_message_int_t* msg)
183 {
184   int status;
185   errno = 0;
186   if (auto search = child_statuses_.find(msg->value); search != child_statuses_.end()) {
187     status = search->second;
188     child_statuses_.erase(search); // We only need this info once
189   } else {
190     waitpid(msg->value, &status, 0);
191   }
192   xbt_assert(errno == 0, "Cannot wait on behalf of the checker: %s.", strerror(errno));
193
194   s_mc_message_int_t answer = {};
195   answer.type               = MessageType::WAIT_CHILD_REPLY;
196   answer.value              = status;
197   xbt_assert(channel_.send(answer) == 0, "Could not send response to WAIT_CHILD: %s", strerror(errno));
198 }
199 void AppSide::handle_actors_status() const
200 {
201   auto const& actor_list = kernel::EngineImpl::get_instance()->get_actor_list();
202   XBT_DEBUG("Serialize the actors to answer ACTORS_STATUS from the checker. %zu actors to go.", actor_list.size());
203
204   std::vector<s_mc_message_actors_status_one_t> status;
205   for (auto const& [aid, actor] : actor_list) {
206     xbt_assert(actor);
207     xbt_assert(actor->simcall_.observer_, "simcall %s in actor %s has no observer.", actor->simcall_.get_cname(),
208                actor->get_cname());
209     s_mc_message_actors_status_one_t one = {};
210     one.type                             = MessageType::ACTORS_STATUS_REPLY_TRANSITION;
211     one.aid                              = aid;
212     one.enabled                          = mc::actor_is_enabled(actor);
213     one.max_considered                   = actor->simcall_.observer_->get_max_consider();
214     status.push_back(one);
215   }
216
217   struct s_mc_message_actors_status_answer_t answer = {};
218   answer.type                                       = MessageType::ACTORS_STATUS_REPLY_COUNT;
219   answer.count                                      = static_cast<int>(status.size());
220
221   xbt_assert(channel_.send(answer) == 0, "Could not send ACTORS_STATUS_REPLY msg: %s", strerror(errno));
222   if (answer.count > 0) {
223     size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
224     xbt_assert(channel_.send(status.data(), size) == 0, "Could not send ACTORS_STATUS_REPLY data: %s", strerror(errno));
225   }
226
227   // Serialize each transition to describe what each actor is doing
228   XBT_DEBUG("Deliver ACTOR_TRANSITION_PROBE payload");
229   for (const auto& actor_status : status) {
230     const auto& actor        = actor_list.at(actor_status.aid);
231     const int max_considered = actor_status.max_considered;
232
233     for (int times_considered = 0; times_considered < max_considered; times_considered++) {
234       std::stringstream stream;
235       s_mc_message_simcall_probe_one_t probe;
236       probe.type = MessageType::ACTORS_STATUS_REPLY_SIMCALL;
237
238       if (actor->simcall_.observer_ != nullptr) {
239         actor->simcall_.observer_->prepare(times_considered);
240         actor->simcall_.observer_->serialize(stream);
241       } else {
242         stream << (short)mc::Transition::Type::UNKNOWN;
243       }
244
245       std::string str = stream.str();
246       xbt_assert(str.size() + 1 <= probe.buffer.size(),
247                  "The serialized transition is too large for the buffer. Please fix the code.");
248       strncpy(probe.buffer.data(), str.c_str(), probe.buffer.size() - 1);
249       probe.buffer.back() = '\0';
250
251       XBT_DEBUG("send ACTOR_TRANSITION_PROBE(%s) ~> '%s'", actor->get_cname(), str.c_str());
252       xbt_assert(channel_.send(probe) == 0, "Could not send ACTOR_TRANSITION_PROBE payload: %s", strerror(errno));
253     }
254     // NOTE: We do NOT need to reset `times_considered` for each actor's
255     // simcall observer here to the "original" value (i.e. the value BEFORE
256     // multiple prepare() calls were made for serialization purposes) since
257     // each SIMCALL_EXECUTE provides a `times_considered` to be used to prepare
258     // the transition before execution.
259   }
260 }
261 void AppSide::handle_actors_maxpid() const
262 {
263   s_mc_message_int_t answer = {};
264   answer.type               = MessageType::ACTORS_MAXPID_REPLY;
265   answer.value              = kernel::actor::ActorImpl::get_maxpid();
266   xbt_assert(channel_.send(answer) == 0, "Could not send response: %s", strerror(errno));
267 }
268
269 #define assert_msg_size(_name_, _type_)                                                                                \
270   xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size,            \
271              sizeof(_type_))
272
273 void AppSide::handle_messages()
274 {
275   while (true) { // Until we get a CONTINUE message
276     XBT_DEBUG("Waiting messages from the model-checker");
277
278     std::array<char, MC_MESSAGE_LENGTH> message_buffer;
279     ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
280
281     if (received_size == 0) {
282       XBT_DEBUG("Socket closed on the Checker side, bailing out.");
283       ::_Exit(0); // Nobody's listening to that process anymore => exit as quickly as possible.
284     }
285     xbt_assert(received_size >= 0, "Could not receive commands from the model-checker: %s", strerror(errno));
286     xbt_assert(static_cast<size_t>(received_size) >= sizeof(s_mc_message_t), "Cannot handle short message (size=%zd)",
287                received_size);
288
289     const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
290     switch (message->type) {
291       case MessageType::CONTINUE:
292         assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
293         return;
294
295       case MessageType::DEADLOCK_CHECK:
296         assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
297         handle_deadlock_check(message);
298         break;
299
300       case MessageType::SIMCALL_EXECUTE:
301         assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
302         handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
303         break;
304
305       case MessageType::FINALIZE:
306         assert_msg_size("FINALIZE", s_mc_message_int_t);
307         handle_finalize((s_mc_message_int_t*)message_buffer.data());
308         break;
309
310       case MessageType::FORK:
311         assert_msg_size("FORK", s_mc_message_fork_t);
312         handle_fork((s_mc_message_fork_t*)message_buffer.data());
313         break;
314
315       case MessageType::WAIT_CHILD:
316         assert_msg_size("WAIT_CHILD", s_mc_message_int_t);
317         handle_wait_child((s_mc_message_int_t*)message_buffer.data());
318         break;
319
320       case MessageType::ACTORS_STATUS:
321         assert_msg_size("ACTORS_STATUS", s_mc_message_t);
322         handle_actors_status();
323         break;
324
325       case MessageType::ACTORS_MAXPID:
326         assert_msg_size("ACTORS_MAXPID", s_mc_message_t);
327         handle_actors_maxpid();
328         break;
329
330       default:
331         xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
332         break;
333     }
334   }
335 }
336
337 void AppSide::main_loop()
338 {
339   simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
340
341   sthread_disable();
342   coverage_checkpoint();
343   sthread_enable();
344   while (true) {
345     simgrid::mc::execute_actors();
346     xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker: %s",
347                strerror(errno));
348     this->handle_messages();
349   }
350 }
351
352 void AppSide::report_assertion_failure()
353 {
354   xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker: %s",
355              strerror(errno));
356   this->handle_messages();
357 }
358
359 } // namespace simgrid::mc