Logo AND Algorithmique Numérique Distribuée

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