Logo AND Algorithmique Numérique Distribuée

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