xref: /aosp_15_r20/external/pytorch/torch/csrc/distributed/c10d/control_plane/PythonHandlers.cpp (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1 #include <torch/csrc/distributed/c10d/control_plane/Handlers.hpp>
2 
3 #include <cstdio>
4 #include <fstream>
5 #include <string>
6 
7 #include <c10/util/tempfile.h>
8 #include <torch/csrc/distributed/c10d/exception.h>
9 #include <torch/csrc/utils/pybind.h>
10 
11 namespace c10d::control_plane {
12 namespace {
13 
14 RegisterHandler tracebackHandler{
15     "dump_traceback",
__anon5027ba540202() 16     [](const Request&, Response& res) {
17       auto tmpfile = c10::make_tempfile("torch-dump_traceback");
18 
19       auto cfile = ::fopen(tmpfile.name.c_str(), "w");
20       if (!cfile) {
21         throw std::runtime_error("failed to open file for writing");
22       }
23 
24       {
25         py::gil_scoped_acquire guard{};
26 
27         auto faulthandler = py::module::import("faulthandler");
28         faulthandler.attr("dump_traceback")(fileno(cfile), true);
29       }
30 
31       ::fclose(cfile);
32 
33       std::ifstream file(tmpfile.name);
34       std::string str;
35       std::string file_contents;
36       while (std::getline(file, str)) {
37         file_contents += str;
38         file_contents.push_back('\n');
39       }
40 
41       res.setContent(std::move(file_contents), "text/plain");
42     }};
43 }
44 } // namespace c10d::control_plane
45