|
| 1 | +#include "cmd_stream_session.hpp" |
| 2 | +#include "../../util/shell.hpp" |
| 3 | + |
| 4 | +#include <boost/asio.hpp> |
| 5 | +#include <boost/asio/experimental/awaitable_operators.hpp> |
| 6 | +#include <boost/process/v2/stdio.hpp> |
| 7 | +#include <thinger/util/logger.hpp> |
| 8 | + |
| 9 | +#include <chrono> |
| 10 | +#include <utility> |
| 11 | + |
| 12 | +namespace thinger::iotmp { |
| 13 | + |
| 14 | + using namespace boost::asio::experimental::awaitable_operators; |
| 15 | + |
| 16 | + cmd_stream_session::cmd_stream_session(client& client, uint16_t stream_id, std::string session, |
| 17 | + json_t& parameters) |
| 18 | + : stream_session(client, stream_id, std::move(session)), |
| 19 | + stdin_pipe_(client.get_io_context()), |
| 20 | + stdout_pipe_(client.get_io_context()), |
| 21 | + stderr_pipe_(client.get_io_context()), |
| 22 | + timeout_timer_(client.get_io_context()) |
| 23 | + { |
| 24 | + ensure_home_env(); |
| 25 | + command_ = get_value(parameters, "cmd", empty::string); |
| 26 | + timeout_seconds_ = get_value(parameters, "timeout", 0); |
| 27 | + THINGER_LOG("cmd stream {} created: '{}' (timeout: {}s)", |
| 28 | + stream_id_, command_, timeout_seconds_); |
| 29 | + } |
| 30 | + |
| 31 | + cmd_stream_session::~cmd_stream_session() { |
| 32 | + // bp2::process destructor calls std::terminate() if ownership has not |
| 33 | + // been released. async_wait reaps the child but does not flip the |
| 34 | + // internal state to "released", so we must call detach() explicitly. |
| 35 | + if (process_) { |
| 36 | + process_->detach(); |
| 37 | + } |
| 38 | + THINGER_LOG("cmd stream {} destroyed", stream_id_); |
| 39 | + } |
| 40 | + |
| 41 | + awaitable<exec_result> cmd_stream_session::start() { |
| 42 | + if (command_.empty()) { |
| 43 | + co_return exec_result{false, "no command provided"}; |
| 44 | + } |
| 45 | + |
| 46 | + namespace bp2 = boost::process::v2; |
| 47 | + boost::system::error_code ec; |
| 48 | + std::vector<std::string> args = {"-c", command_}; |
| 49 | + process_.emplace( |
| 50 | + client_.get_io_context().get_executor(), |
| 51 | + preferred_shell(), |
| 52 | + args, |
| 53 | + bp2::process_stdio{stdin_pipe_, stdout_pipe_, stderr_pipe_}, |
| 54 | + ec |
| 55 | + ); |
| 56 | + |
| 57 | + if (ec) { |
| 58 | + THINGER_LOG_ERROR("cmd stream {} failed to launch: {}", stream_id_, ec.message()); |
| 59 | + process_.reset(); |
| 60 | + co_return exec_result{false, ec.message()}; |
| 61 | + } |
| 62 | + |
| 63 | + THINGER_LOG("cmd stream {} launched (pid {})", stream_id_, process_->id()); |
| 64 | + |
| 65 | + // Spawn the coordinator coroutine; it keeps the session alive via |
| 66 | + // shared_from_this() until stdout, stderr, and the process all complete. |
| 67 | + co_spawn(client_.get_io_context(), run(), detached); |
| 68 | + |
| 69 | + if (timeout_seconds_ > 0) { |
| 70 | + co_spawn(client_.get_io_context(), watch_timeout(), detached); |
| 71 | + } |
| 72 | + |
| 73 | + co_return true; |
| 74 | + } |
| 75 | + |
| 76 | + bool cmd_stream_session::stop(StopReason reason) { |
| 77 | + stopped_externally_ = true; |
| 78 | + |
| 79 | + if (process_ && !finished_) { |
| 80 | + boost::system::error_code ec; |
| 81 | + process_->terminate(ec); |
| 82 | + } |
| 83 | + |
| 84 | + boost::system::error_code ec; |
| 85 | + stdin_pipe_.close(ec); |
| 86 | + stdout_pipe_.close(ec); |
| 87 | + stderr_pipe_.close(ec); |
| 88 | + timeout_timer_.cancel(); |
| 89 | + |
| 90 | + return true; |
| 91 | + } |
| 92 | + |
| 93 | + void cmd_stream_session::handle_input(input& in) { |
| 94 | + if (finished_ || !stdin_pipe_.is_open()) return; |
| 95 | + |
| 96 | + // Accept either raw binary payloads or string payloads. Anything else |
| 97 | + // (objects, arrays, numbers) is ignored — the convention is that |
| 98 | + // stdin data is transported verbatim. |
| 99 | + const auto& payload = in.payload(); |
| 100 | + std::string data; |
| 101 | + if (payload.is_binary()) { |
| 102 | + const auto& bin = payload.get_binary(); |
| 103 | + data.assign(bin.begin(), bin.end()); |
| 104 | + } else if (payload.is_string()) { |
| 105 | + data = payload.get<std::string>(); |
| 106 | + } else { |
| 107 | + return; |
| 108 | + } |
| 109 | + if (data.empty()) return; |
| 110 | + |
| 111 | + increase_received(data.size()); |
| 112 | + stdin_queue_.emplace(std::move(data)); |
| 113 | + |
| 114 | + if (!stdin_writing_) { |
| 115 | + stdin_writing_ = true; |
| 116 | + co_spawn(client_.get_io_context(), stdin_write_loop(), detached); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + awaitable<void> cmd_stream_session::stdin_write_loop() { |
| 121 | + auto self = shared_from_this(); |
| 122 | + while (!stdin_queue_.empty() && stdin_pipe_.is_open()) { |
| 123 | + auto data = std::move(stdin_queue_.front()); |
| 124 | + stdin_queue_.pop(); |
| 125 | + auto [ec, bytes] = co_await boost::asio::async_write( |
| 126 | + stdin_pipe_, |
| 127 | + boost::asio::buffer(data), |
| 128 | + use_nothrow_awaitable); |
| 129 | + if (ec) { |
| 130 | + if (ec != boost::asio::error::operation_aborted) { |
| 131 | + LOG_WARNING("cmd stream {} stdin write failed: {}", |
| 132 | + stream_id_, ec.message()); |
| 133 | + } |
| 134 | + break; |
| 135 | + } |
| 136 | + } |
| 137 | + stdin_writing_ = false; |
| 138 | + } |
| 139 | + |
| 140 | + awaitable<void> cmd_stream_session::run() { |
| 141 | + auto self = shared_from_this(); |
| 142 | + |
| 143 | + // Wait until stdout, stderr, and the process have all completed. |
| 144 | + // Reads finish on EOF (process closes its end) or operation_aborted |
| 145 | + // (stop() closes the pipes); the process completes via async_wait. |
| 146 | + co_await (read_stdout() && read_stderr() && wait_process()); |
| 147 | + |
| 148 | + timeout_timer_.cancel(); |
| 149 | + |
| 150 | + // Send the final exit frame and notify the server that the stream is |
| 151 | + // over, unless the server already requested the stop itself. |
| 152 | + json_t frame; |
| 153 | + frame["exit"] = exit_code_; |
| 154 | + if (timed_out_) frame["timeout"] = true; |
| 155 | + client_.stream_resource(stream_id_, std::move(frame)); |
| 156 | + |
| 157 | + if (process_) { |
| 158 | + process_->detach(); |
| 159 | + } |
| 160 | + // Note: we do NOT call client_.stop_stream() here. The session ending |
| 161 | + // triggers the stream_manager's on_end_ listener which already sends |
| 162 | + // STOP_STREAM via client_.stop_stream() when the session is gone. |
| 163 | + // Sending it from both paths produces a duplicate STOP_STREAM. |
| 164 | + } |
| 165 | + |
| 166 | + awaitable<void> cmd_stream_session::read_stdout() { |
| 167 | + auto self = shared_from_this(); |
| 168 | + while (true) { |
| 169 | + auto [ec, bytes] = co_await stdout_pipe_.async_read_some( |
| 170 | + boost::asio::buffer(stdout_buffer_, CMD_STREAM_BUFFER_SIZE), |
| 171 | + use_nothrow_awaitable); |
| 172 | + if (ec) break; |
| 173 | + if (bytes > 0) { |
| 174 | + increase_sent(bytes); |
| 175 | + json_t frame; |
| 176 | + frame["out"] = json_t::binary({stdout_buffer_, stdout_buffer_ + bytes}); |
| 177 | + client_.stream_resource(stream_id_, std::move(frame)); |
| 178 | + } |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + awaitable<void> cmd_stream_session::read_stderr() { |
| 183 | + auto self = shared_from_this(); |
| 184 | + while (true) { |
| 185 | + auto [ec, bytes] = co_await stderr_pipe_.async_read_some( |
| 186 | + boost::asio::buffer(stderr_buffer_, CMD_STREAM_BUFFER_SIZE), |
| 187 | + use_nothrow_awaitable); |
| 188 | + if (ec) break; |
| 189 | + if (bytes > 0) { |
| 190 | + increase_sent(bytes); |
| 191 | + json_t frame; |
| 192 | + frame["err"] = json_t::binary({stderr_buffer_, stderr_buffer_ + bytes}); |
| 193 | + client_.stream_resource(stream_id_, std::move(frame)); |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + awaitable<void> cmd_stream_session::wait_process() { |
| 199 | + auto self = shared_from_this(); |
| 200 | + if (!process_) co_return; |
| 201 | + |
| 202 | + namespace bp2 = boost::process::v2; |
| 203 | + auto [ec, native_code] = co_await process_->async_wait(use_nothrow_awaitable); |
| 204 | + exit_code_ = ec ? -1 : bp2::evaluate_exit_code(native_code); |
| 205 | + finished_ = true; |
| 206 | + } |
| 207 | + |
| 208 | + awaitable<void> cmd_stream_session::watch_timeout() { |
| 209 | + auto self = shared_from_this(); |
| 210 | + timeout_timer_.expires_after(std::chrono::seconds(timeout_seconds_)); |
| 211 | + auto [ec] = co_await timeout_timer_.async_wait(use_nothrow_awaitable); |
| 212 | + if (ec) co_return; // cancelled |
| 213 | + if (process_ && !finished_) { |
| 214 | + LOG_WARNING("cmd stream {} timed out after {}s, terminating", |
| 215 | + stream_id_, timeout_seconds_); |
| 216 | + timed_out_ = true; |
| 217 | + boost::system::error_code term_ec; |
| 218 | + process_->terminate(term_ec); |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | +} |
0 commit comments