Logo AND Algorithmique Numérique Distribuée

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