Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Move the checker_side_ from the ModelChecker to the RemoteApp
[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 #include <sys/ptrace.h>
30 #include <sys/wait.h>
31
32 #ifdef __linux__
33 #define WAITPID_CHECKED_FLAGS __WALL
34 #else
35 #define WAITPID_CHECKED_FLAGS 0
36 #endif
37
38 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_Session, mc, "Model-checker session");
39 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
40
41 static simgrid::config::Flag<std::string> _sg_mc_setenv{
42     "model-check/setenv", "Extra environment variables to pass to the child process (ex: 'AZE=aze;QWE=qwe').", "",
43     [](std::string_view value) {
44       xbt_assert(value.empty() || value.find('=', 0) != std::string_view::npos,
45                  "The 'model-check/setenv' parameter must be like 'AZE=aze', but it does not contain an equal sign.");
46     }};
47
48 namespace simgrid::mc {
49
50 XBT_ATTRIB_NORETURN static void run_child_process(int socket, const std::vector<char*>& args)
51 {
52   /* On startup, simix_global_init() calls simgrid::mc::Client::initialize(), which checks whether the MC_ENV_SOCKET_FD
53    * env variable is set. If so, MC mode is assumed, and the client is setup from its side
54    */
55
56 #ifdef __linux__
57   // Make sure we do not outlive our parent
58   sigset_t mask;
59   sigemptyset(&mask);
60   xbt_assert(sigprocmask(SIG_SETMASK, &mask, nullptr) >= 0, "Could not unblock signals");
61   xbt_assert(prctl(PR_SET_PDEATHSIG, SIGHUP) == 0, "Could not PR_SET_PDEATHSIG");
62 #endif
63
64   // Remove CLOEXEC to pass the socket to the application
65   int fdflags = fcntl(socket, F_GETFD, 0);
66   xbt_assert(fdflags != -1 && fcntl(socket, F_SETFD, fdflags & ~FD_CLOEXEC) != -1,
67              "Could not remove CLOEXEC for socket");
68
69   setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
70
71   /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
72   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
73   boost::char_separator<char> semicol_sep(";");
74   boost::char_separator<char> equal_sep("=");
75   Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
76   for (const auto& token : token_vars) {
77     std::vector<std::string> kv;
78     Tokenizer token_kv(token, equal_sep);
79     for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
80       kv.push_back(t);
81     xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
82                token.c_str());
83     XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
84     setenv(kv[0].c_str(), kv[1].c_str(), 1);
85   }
86
87   /* And now, exec the child process */
88   int i = 1;
89   while (args[i] != nullptr && args[i][0] == '-')
90     i++;
91
92   xbt_assert(args[i] != nullptr,
93              "Unable to find a binary to exec on the command line. Did you only pass config flags?");
94
95   execvp(args[i], args.data() + i);
96   XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
97                "        Make sure that your binary exists on disk and is executable.",
98                args[i], strerror(errno));
99   if (strchr(args[i], '=') != nullptr)
100     XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
101                  args[i]);
102
103   xbt_die("Aborting now.");
104 }
105
106 RemoteApp::RemoteApp(const std::vector<char*>& args)
107 {
108   // Create an AF_LOCAL socketpair used for exchanging messages
109   // between the model-checker process (ourselves) and the model-checked
110   // process:
111   int sockets[2];
112   xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != -1, "Could not create socketpair");
113
114   pid_t pid = fork();
115   xbt_assert(pid >= 0, "Could not fork model-checked process");
116
117   if (pid == 0) { // Child
118     ::close(sockets[1]);
119     run_child_process(sockets[0], args);
120     DIE_IMPOSSIBLE;
121   }
122
123   // Parent (model-checker):
124   ::close(sockets[0]);
125
126   xbt_assert(mc_model_checker == nullptr, "Did you manage to start the MC twice in this process?");
127
128   checker_side_  = std::make_unique<simgrid::mc::CheckerSide>(sockets[1]);
129   auto process   = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid);
130   model_checker_ = std::make_unique<simgrid::mc::ModelChecker>(std::move(process));
131
132   mc_model_checker = model_checker_.get();
133   start();
134
135   /* Take the initial snapshot */
136   wait_for_requests();
137   initial_snapshot_ =
138       std::make_shared<simgrid::mc::Snapshot>(0, page_store_, model_checker_->get_remote_process_memory());
139 }
140
141 RemoteApp::~RemoteApp()
142 {
143   initial_snapshot_ = nullptr;
144   if (model_checker_) {
145     shutdown();
146     model_checker_   = nullptr;
147     mc_model_checker = nullptr;
148   }
149 }
150 void RemoteApp::start()
151 {
152   checker_side_->start(
153       [](evutil_socket_t sig, short events, void* arg) {
154         auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
155         if (events == EV_READ) {
156           std::array<char, MC_MESSAGE_LENGTH> buffer;
157           ssize_t size = recv(checker->get_channel().get_socket(), buffer.data(), buffer.size(), MSG_DONTWAIT);
158           if (size == -1) {
159             XBT_ERROR("Channel::receive failure: %s", strerror(errno));
160             if (errno != EAGAIN)
161               throw simgrid::xbt::errno_error();
162           }
163
164           if (not mc_model_checker->handle_message(buffer.data(), size))
165             checker->break_loop();
166         } else {
167           xbt_die("Unexpected event");
168         }
169       },
170       [](evutil_socket_t sig, short events, void* arg) {
171         auto mc = static_cast<simgrid::mc::ModelChecker*>(arg);
172         if (events == EV_SIGNAL) {
173           if (sig == SIGCHLD)
174             mc->handle_waitpid();
175           else
176             xbt_die("Unexpected signal: %d", sig);
177         } else {
178           xbt_die("Unexpected event");
179         }
180       },
181       model_checker_.get());
182
183   XBT_DEBUG("Waiting for the model-checked process");
184   int status;
185
186   // The model-checked process SIGSTOP itself to signal it's ready:
187   const pid_t pid = get_remote_process_memory().pid();
188
189   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
190              "Could not wait model-checked process");
191
192   errno = 0;
193 #ifdef __linux__
194   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
195   ptrace(PTRACE_CONT, pid, 0, 0);
196 #elif defined BSD
197   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
198 #else
199 #error "no ptrace equivalent coded for this platform"
200 #endif
201   xbt_assert(errno == 0,
202              "Ptrace does not seem to be usable in your setup (errno: %d). "
203              "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
204              "If it does not help, please report this bug.",
205              errno);
206 }
207 void RemoteApp::restore_initial_state() const
208 {
209   this->initial_snapshot_->restore(model_checker_->get_remote_process_memory());
210 }
211
212 unsigned long RemoteApp::get_maxpid() const
213 {
214   // note: we could maybe cache it and count the actor creation on checker side too.
215   // But counting correctly accross state checkpoint/restore would be annoying.
216
217   checker_side_->get_channel().send(MessageType::ACTORS_MAXPID);
218   s_mc_message_int_t answer;
219   ssize_t answer_size = checker_side_->get_channel().receive(answer);
220   xbt_assert(answer_size != -1, "Could not receive message");
221   xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
222   xbt_assert(answer.type == MessageType::ACTORS_MAXPID_REPLY,
223              "Received unexpected message %s (%i); expected MessageType::ACTORS_MAXPID_REPLY (%i)",
224              to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_MAXPID_REPLY);
225
226   return answer.value;
227 }
228
229 void RemoteApp::get_actors_status(std::map<aid_t, ActorState>& whereto) const
230 {
231   // The messaging happens as follows:
232   //
233   // CheckerSide                  AppSide
234   // send ACTORS_STATUS ---->
235   //                    <----- send ACTORS_STATUS_REPLY
236   //                    <----- send `N` `s_mc_message_actors_status_one_t` structs
237   //                    <----- send `M` `s_mc_message_simcall_probe_one_t` structs
238   checker_side_->get_channel().send(MessageType::ACTORS_STATUS);
239
240   s_mc_message_actors_status_answer_t answer;
241   ssize_t answer_size = checker_side_->get_channel().receive(answer);
242   xbt_assert(answer_size != -1, "Could not receive message");
243   xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
244   xbt_assert(answer.type == MessageType::ACTORS_STATUS_REPLY,
245              "Received unexpected message %s (%i); expected MessageType::ACTORS_STATUS_REPLY (%i)",
246              to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_STATUS_REPLY);
247
248   // Message sanity checks
249   xbt_assert(answer.count >= 0, "Received an ACTOR_STATUS_REPLY message with an actor count of '%d' < 0", answer.count);
250   xbt_assert(answer.transition_count >= 0, "Received an ACTOR_STATUS_REPLY message with transition_count '%d' < 0",
251              answer.transition_count);
252   xbt_assert(answer.transition_count == 0 || answer.count >= 0,
253              "Received an ACTOR_STATUS_REPLY message with no actor data "
254              "but with transition data nonetheless");
255
256   std::vector<s_mc_message_actors_status_one_t> status(answer.count);
257   if (answer.count > 0) {
258     size_t size      = status.size() * sizeof(s_mc_message_actors_status_one_t);
259     ssize_t received = checker_side_->get_channel().receive(status.data(), size);
260     xbt_assert(static_cast<size_t>(received) == size);
261   }
262
263   // Ensures that each actor sends precisely `answer.transition_count` transitions. While technically
264   // this doesn't catch the edge case where actor A sends 3 instead of 2 and actor B sends 2 instead
265   // of 3 transitions, that is ignored here since that invariant needs to be enforced on the AppSide
266   const auto expected_transitions = std::accumulate(
267       status.begin(), status.end(), 0, [](int total, const auto& actor) { return total + actor.n_transitions; });
268   xbt_assert(expected_transitions == answer.transition_count,
269              "Expected to receive %d transition(s) but was only notified of %d by the app side", expected_transitions,
270              answer.transition_count);
271
272   std::vector<s_mc_message_simcall_probe_one_t> probes(answer.transition_count);
273   if (answer.transition_count > 0) {
274     for (auto& probe : probes) {
275       ssize_t received = checker_side_->get_channel().receive(probe);
276       xbt_assert(received >= 0, "Could not receive response to ACTORS_PROBE message (%s)", strerror(errno));
277       xbt_assert(static_cast<size_t>(received) == sizeof probe,
278                  "Could not receive response to ACTORS_PROBE message (%zd bytes received != %zu bytes expected",
279                  received, sizeof probe);
280     }
281   }
282
283   whereto.clear();
284   std::move_iterator probes_iter(probes.begin());
285
286   for (const auto& actor : status) {
287     xbt_assert(actor.n_transitions == 0 || actor.n_transitions == actor.max_considered,
288                "If any transitions are serialized for an actor, it must match the "
289                "total number of transitions that can be considered for the actor "
290                "(currently %d), but only %d transition(s) was/were said to be encoded",
291                actor.max_considered, actor.n_transitions);
292
293     std::vector<std::shared_ptr<Transition>> actor_transitions;
294     for (int times_considered = 0; times_considered < actor.n_transitions; times_considered++, probes_iter++) {
295       std::stringstream stream((*probes_iter).buffer.data());
296       actor_transitions.emplace_back(deserialize_transition(actor.aid, times_considered, stream));
297     }
298
299     XBT_DEBUG("Received %zu transitions for actor %ld", actor_transitions.size(), actor.aid);
300     whereto.try_emplace(actor.aid, actor.aid, actor.enabled, actor.max_considered, std::move(actor_transitions));
301   }
302 }
303
304 void RemoteApp::check_deadlock() const
305 {
306   xbt_assert(checker_side_->get_channel().send(MessageType::DEADLOCK_CHECK) == 0, "Could not check deadlock state");
307   s_mc_message_int_t message;
308   ssize_t received = checker_side_->get_channel().receive(message);
309   xbt_assert(received != -1, "Could not receive message");
310   xbt_assert(received == sizeof message, "Broken message (size=%zd; expected %zu)", received, sizeof message);
311   xbt_assert(message.type == MessageType::DEADLOCK_CHECK_REPLY,
312              "Received unexpected message %s (%i); expected MessageType::DEADLOCK_CHECK_REPLY (%i)",
313              to_c_str(message.type), (int)message.type, (int)MessageType::DEADLOCK_CHECK_REPLY);
314
315   if (message.value != 0) {
316     XBT_CINFO(mc_global, "Counter-example execution trace:");
317     for (auto const& frame : model_checker_->get_exploration()->get_textual_trace())
318       XBT_CINFO(mc_global, "  %s", frame.c_str());
319     XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
320              "--cfg=model-check/replay:'%s'",
321              model_checker_->get_exploration()->get_record_trace().to_string().c_str());
322     model_checker_->get_exploration()->log_state();
323     throw DeadlockError();
324   }
325 }
326
327 void RemoteApp::wait_for_requests()
328 {
329   /* Resume the application */
330   if (checker_side_->get_channel().send(MessageType::CONTINUE) != 0)
331     throw xbt::errno_error();
332   get_remote_process_memory().clear_cache();
333
334   if (this->get_remote_process_memory().running())
335     checker_side_->dispatch();
336 }
337
338 void RemoteApp::shutdown()
339 {
340   XBT_DEBUG("Shutting down model-checker");
341
342   RemoteProcessMemory& process = get_remote_process_memory();
343   if (process.running()) {
344     XBT_DEBUG("Killing process");
345     finalize_app(true);
346     kill(process.pid(), SIGKILL);
347     process.terminate();
348   }
349 }
350
351 Transition* RemoteApp::handle_simcall(aid_t aid, int times_considered, bool new_transition)
352 {
353   s_mc_message_simcall_execute_t m = {};
354   m.type                           = MessageType::SIMCALL_EXECUTE;
355   m.aid_                           = aid;
356   m.times_considered_              = times_considered;
357   checker_side_->get_channel().send(m);
358
359   get_remote_process_memory().clear_cache();
360   if (this->get_remote_process_memory().running())
361     checker_side_->dispatch(); // The app may send messages while processing the transition
362
363   s_mc_message_simcall_execute_answer_t answer;
364   ssize_t s = checker_side_->get_channel().receive(answer);
365   xbt_assert(s != -1, "Could not receive message");
366   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
367   xbt_assert(answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
368              "Received unexpected message %s (%i); expected MessageType::SIMCALL_EXECUTE_ANSWER (%i)",
369              to_c_str(answer.type), (int)answer.type, (int)MessageType::SIMCALL_EXECUTE_ANSWER);
370
371   if (new_transition) {
372     std::stringstream stream(answer.buffer.data());
373     return deserialize_transition(aid, times_considered, stream);
374   } else
375     return nullptr;
376 }
377
378 void RemoteApp::finalize_app(bool terminate_asap)
379 {
380   s_mc_message_int_t m = {};
381   m.type               = MessageType::FINALIZE;
382   m.value              = terminate_asap;
383   xbt_assert(checker_side_->get_channel().send(m) == 0, "Could not ask the app to finalize on need");
384
385   s_mc_message_t answer;
386   ssize_t s = checker_side_->get_channel().receive(answer);
387   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
388   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
389   xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
390              "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
391              (int)answer.type, (int)MessageType::FINALIZE_REPLY);
392 }
393
394 } // namespace simgrid::mc