2 * Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
4 * This program is free software: you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 3, as published
6 * by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranties of
10 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 * PURPOSE. See the GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program. If not, see <http://www.gnu.org/licenses/>.
18 #include "anbox/container/client.h"
19 #include "anbox/system_configuration.h"
20 #include "anbox/container/management_api_stub.h"
21 #include "anbox/logger.h"
22 #include "anbox/network/local_socket_messenger.h"
23 #include "anbox/rpc/channel.h"
24 #include "anbox/rpc/message_processor.h"
25 #include "anbox/rpc/pending_call_cache.h"
27 namespace ba = boost::asio;
28 namespace bs = boost::system;
32 Client::Client(const std::shared_ptr<Runtime> &rt)
33 : messenger_(std::make_shared<network::LocalSocketMessenger>(
34 SystemConfiguration::instance().container_socket_path(), rt)),
35 pending_calls_(std::make_shared<rpc::PendingCallCache>()),
36 rpc_channel_(std::make_shared<rpc::Channel>(pending_calls_, messenger_)),
37 management_api_(std::make_shared<ManagementApiStub>(rpc_channel_)),
39 std::make_shared<rpc::MessageProcessor>(messenger_, pending_calls_)) {
45 void Client::start(const Configuration &configuration) {
47 management_api_->start_container(configuration);
48 } catch (const std::exception &e) {
49 ERROR("Failed to start container: %s", e.what());
50 if (terminate_callback_)
51 terminate_callback_();
56 management_api_->stop_container();
59 void Client::register_terminate_handler(const TerminateCallback &callback) {
60 terminate_callback_ = callback;
63 void Client::read_next_message() {
64 auto callback = std::bind(&Client::on_read_size, this, std::placeholders::_1,
65 std::placeholders::_2);
66 messenger_->async_receive_msg(callback, ba::buffer(buffer_));
69 void Client::on_read_size(const boost::system::error_code &error,
70 std::size_t bytes_read) {
72 if (terminate_callback_)
73 terminate_callback_();
77 std::vector<std::uint8_t> data(bytes_read);
78 std::copy(buffer_.data(), buffer_.data() + bytes_read, data.data());
80 if (processor_->process_data(data)) read_next_message();
82 } // namespace container