Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Really check the privatization option in the MCed SMPI app.
[simgrid.git] / src / mc / api / RemoteApp.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/api/RemoteApp.hpp"
7 #include "src/mc/explo/Exploration.hpp"
8 #include "src/mc/mc_config.hpp"
9 #include "xbt/asserts.h"
10 #include "src/mc/api/State.hpp"
11 #include "src/mc/mc_config.hpp"
12 #include "src/mc/mc_exit.hpp"
13 #include "src/mc/mc_private.hpp"
14 #include "xbt/log.h"
15 #include "xbt/system_error.hpp"
16 #include <signal.h>
17
18 #include <algorithm>
19 #include <array>
20 #include <boost/tokenizer.hpp>
21 #include <memory>
22 #include <numeric>
23 #include <string>
24
25 #include <fcntl.h>
26 #ifdef __linux__
27 #include <sys/prctl.h>
28 #endif
29
30 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_Session, mc, "Model-checker session");
31 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
32
33 static simgrid::config::Flag<std::string> _sg_mc_setenv{
34     "model-check/setenv", "Extra environment variables to pass to the child process (ex: 'AZE=aze;QWE=qwe').", "",
35     [](std::string_view value) {
36       xbt_assert(value.empty() || value.find('=', 0) != std::string_view::npos,
37                  "The 'model-check/setenv' parameter must be like 'AZE=aze', but it does not contain an equal sign.");
38     }};
39
40 namespace simgrid::mc {
41
42 XBT_ATTRIB_NORETURN static void run_child_process(int socket, const std::vector<char*>& args)
43 {
44   /* On startup, simix_global_init() calls simgrid::mc::Client::initialize(), which checks whether the MC_ENV_SOCKET_FD
45    * env variable is set. If so, MC mode is assumed, and the client is setup from its side
46    */
47
48 #ifdef __linux__
49   // Make sure we do not outlive our parent
50   sigset_t mask;
51   sigemptyset(&mask);
52   xbt_assert(sigprocmask(SIG_SETMASK, &mask, nullptr) >= 0, "Could not unblock signals");
53   xbt_assert(prctl(PR_SET_PDEATHSIG, SIGHUP) == 0, "Could not PR_SET_PDEATHSIG");
54 #endif
55
56   // Remove CLOEXEC to pass the socket to the application
57   int fdflags = fcntl(socket, F_GETFD, 0);
58   xbt_assert(fdflags != -1 && fcntl(socket, F_SETFD, fdflags & ~FD_CLOEXEC) != -1,
59              "Could not remove CLOEXEC for socket");
60
61   setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
62
63   /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
64   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
65   boost::char_separator<char> semicol_sep(";");
66   boost::char_separator<char> equal_sep("=");
67   Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
68   for (const auto& token : token_vars) {
69     std::vector<std::string> kv;
70     Tokenizer token_kv(token, equal_sep);
71     for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
72       kv.push_back(t);
73     xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
74                token.c_str());
75     XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
76     setenv(kv[0].c_str(), kv[1].c_str(), 1);
77   }
78
79   /* And now, exec the child process */
80   int i = 1;
81   while (args[i] != nullptr && args[i][0] == '-')
82     i++;
83
84   xbt_assert(args[i] != nullptr,
85              "Unable to find a binary to exec on the command line. Did you only pass config flags?");
86
87   execvp(args[i], args.data() + i);
88   XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
89                "        Make sure that your binary exists on disk and is executable.",
90                args[i], strerror(errno));
91   if (strchr(args[i], '=') != nullptr)
92     XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
93                  args[i]);
94
95   xbt_die("Aborting now.");
96 }
97
98 RemoteApp::RemoteApp(const std::vector<char*>& args)
99 {
100   // Create an AF_LOCAL socketpair used for exchanging messages
101   // between the model-checker process (ourselves) and the model-checked
102   // process:
103   int sockets[2];
104   xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != -1, "Could not create socketpair");
105
106   pid_t pid = fork();
107   xbt_assert(pid >= 0, "Could not fork model-checked process");
108
109   if (pid == 0) { // Child
110     ::close(sockets[1]);
111     run_child_process(sockets[0], args);
112     DIE_IMPOSSIBLE;
113   }
114
115   // Parent (model-checker):
116   ::close(sockets[0]);
117
118   xbt_assert(mc_model_checker == nullptr, "Did you manage to start the MC twice in this process?");
119
120   auto process   = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid);
121   model_checker_ = std::make_unique<simgrid::mc::ModelChecker>(std::move(process), sockets[1]);
122
123   mc_model_checker = model_checker_.get();
124   model_checker_->start();
125
126   /* Take the initial snapshot */
127   wait_for_requests();
128   initial_snapshot_ =
129       std::make_shared<simgrid::mc::Snapshot>(0, page_store_, model_checker_->get_remote_process_memory());
130 }
131
132 RemoteApp::~RemoteApp()
133 {
134   initial_snapshot_ = nullptr;
135   if (model_checker_) {
136     shutdown();
137     model_checker_   = nullptr;
138     mc_model_checker = nullptr;
139   }
140 }
141
142 void RemoteApp::restore_initial_state() const
143 {
144   this->initial_snapshot_->restore(model_checker_->get_remote_process_memory());
145 }
146
147 unsigned long RemoteApp::get_maxpid() const
148 {
149   // note: we could maybe cache it and count the actor creation on checker side too.
150   // But counting correctly accross state checkpoint/restore would be annoying.
151
152   model_checker_->get_channel().send(MessageType::ACTORS_MAXPID);
153   s_mc_message_int_t answer;
154   ssize_t answer_size = model_checker_->get_channel().receive(answer);
155   xbt_assert(answer_size != -1, "Could not receive message");
156   xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
157   xbt_assert(answer.type == MessageType::ACTORS_MAXPID_REPLY,
158              "Received unexpected message %s (%i); expected MessageType::ACTORS_MAXPID_REPLY (%i)",
159              to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_MAXPID_REPLY);
160
161   return answer.value;
162 }
163
164 void RemoteApp::get_actors_status(std::map<aid_t, ActorState>& whereto) const
165 {
166   // The messaging happens as follows:
167   //
168   // CheckerSide                  AppSide
169   // send ACTORS_STATUS ---->
170   //                    <----- send ACTORS_STATUS_REPLY
171   //                    <----- send `N` `s_mc_message_actors_status_one_t` structs
172   //                    <----- send `M` `s_mc_message_simcall_probe_one_t` structs
173   model_checker_->get_channel().send(MessageType::ACTORS_STATUS);
174
175   s_mc_message_actors_status_answer_t answer;
176   ssize_t answer_size = model_checker_->get_channel().receive(answer);
177   xbt_assert(answer_size != -1, "Could not receive message");
178   xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
179   xbt_assert(answer.type == MessageType::ACTORS_STATUS_REPLY,
180              "Received unexpected message %s (%i); expected MessageType::ACTORS_STATUS_REPLY (%i)",
181              to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_STATUS_REPLY);
182
183   // Message sanity checks
184   xbt_assert(answer.count >= 0, "Received an ACTOR_STATUS_REPLY message with an actor count of '%d' < 0", answer.count);
185   xbt_assert(answer.transition_count >= 0, "Received an ACTOR_STATUS_REPLY message with transition_count '%d' < 0",
186              answer.transition_count);
187   xbt_assert(answer.transition_count == 0 || answer.count >= 0,
188              "Received an ACTOR_STATUS_REPLY message with no actor data "
189              "but with transition data nonetheless");
190
191   std::vector<s_mc_message_actors_status_one_t> status(answer.count);
192   if (answer.count > 0) {
193     size_t size      = status.size() * sizeof(s_mc_message_actors_status_one_t);
194     ssize_t received = model_checker_->get_channel().receive(status.data(), size);
195     xbt_assert(static_cast<size_t>(received) == size);
196   }
197
198   // Ensures that each actor sends precisely `answer.transition_count` transitions. While technically
199   // this doesn't catch the edge case where actor A sends 3 instead of 2 and actor B sends 2 instead
200   // of 3 transitions, that is ignored here since that invariant needs to be enforced on the AppSide
201   const auto expected_transitions = std::accumulate(
202       status.begin(), status.end(), 0, [](int total, const auto& actor) { return total + actor.n_transitions; });
203   xbt_assert(expected_transitions == answer.transition_count,
204              "Expected to receive %d transition(s) but was only notified of %d by the app side", expected_transitions,
205              answer.transition_count);
206
207   std::vector<s_mc_message_simcall_probe_one_t> probes(answer.transition_count);
208   if (answer.transition_count > 0) {
209     for (auto& probe : probes) {
210       ssize_t received = model_checker_->get_channel().receive(probe);
211       xbt_assert(received >= 0, "Could not receive response to ACTORS_PROBE message (%s)", strerror(errno));
212       xbt_assert(static_cast<size_t>(received) == sizeof probe,
213                  "Could not receive response to ACTORS_PROBE message (%zd bytes received != %zu bytes expected",
214                  received, sizeof probe);
215     }
216   }
217
218   whereto.clear();
219   std::move_iterator probes_iter(probes.begin());
220
221   for (const auto& actor : status) {
222     xbt_assert(actor.n_transitions == 0 || actor.n_transitions == actor.max_considered,
223                "If any transitions are serialized for an actor, it must match the "
224                "total number of transitions that can be considered for the actor "
225                "(currently %d), but only %d transition(s) was/were said to be encoded",
226                actor.max_considered, actor.n_transitions);
227
228     std::vector<std::shared_ptr<Transition>> actor_transitions;
229     for (int times_considered = 0; times_considered < actor.n_transitions; times_considered++, probes_iter++) {
230       std::stringstream stream((*probes_iter).buffer.data());
231       actor_transitions.emplace_back(deserialize_transition(actor.aid, times_considered, stream));
232     }
233
234     XBT_DEBUG("Received %zu transitions for actor %ld", actor_transitions.size(), actor.aid);
235     whereto.try_emplace(actor.aid, actor.aid, actor.enabled, actor.max_considered, std::move(actor_transitions));
236   }
237 }
238
239 void RemoteApp::check_deadlock() const
240 {
241   xbt_assert(model_checker_->get_channel().send(MessageType::DEADLOCK_CHECK) == 0, "Could not check deadlock state");
242   s_mc_message_int_t message;
243   ssize_t received = model_checker_->get_channel().receive(message);
244   xbt_assert(received != -1, "Could not receive message");
245   xbt_assert(received == sizeof message, "Broken message (size=%zd; expected %zu)", received, sizeof message);
246   xbt_assert(message.type == MessageType::DEADLOCK_CHECK_REPLY,
247              "Received unexpected message %s (%i); expected MessageType::DEADLOCK_CHECK_REPLY (%i)",
248              to_c_str(message.type), (int)message.type, (int)MessageType::DEADLOCK_CHECK_REPLY);
249
250   if (message.value != 0) {
251     XBT_CINFO(mc_global, "Counter-example execution trace:");
252     for (auto const& frame : model_checker_->get_exploration()->get_textual_trace())
253       XBT_CINFO(mc_global, "  %s", frame.c_str());
254     XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
255              "--cfg=model-check/replay:'%s'",
256              model_checker_->get_exploration()->get_record_trace().to_string().c_str());
257     model_checker_->get_exploration()->log_state();
258     throw DeadlockError();
259   }
260 }
261
262 void RemoteApp::wait_for_requests()
263 {
264   /* Resume the application */
265   if (model_checker_->get_channel().send(MessageType::CONTINUE) != 0)
266     throw xbt::errno_error();
267   get_remote_process_memory().clear_cache();
268
269   if (this->get_remote_process_memory().running())
270     model_checker_->channel_handle_events();
271 }
272
273 void RemoteApp::shutdown()
274 {
275   XBT_DEBUG("Shutting down model-checker");
276
277   RemoteProcessMemory& process = get_remote_process_memory();
278   if (process.running()) {
279     XBT_DEBUG("Killing process");
280     finalize_app(true);
281     kill(process.pid(), SIGKILL);
282     process.terminate();
283   }
284 }
285
286 void RemoteApp::finalize_app(bool terminate_asap)
287 {
288   s_mc_message_int_t m = {};
289   m.type               = MessageType::FINALIZE;
290   m.value              = terminate_asap;
291   xbt_assert(model_checker_->get_channel().send(m) == 0, "Could not ask the app to finalize on need");
292
293   s_mc_message_t answer;
294   ssize_t s = model_checker_->get_channel().receive(answer);
295   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
296   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
297   xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
298              "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
299              (int)answer.type, (int)MessageType::FINALIZE_REPLY);
300 }
301
302 } // namespace simgrid::mc