2 * Copyright (c) 2017 - 2021 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <aul_rpc_port.h>
22 #include <sys/socket.h>
24 #include <uuid/uuid.h>
29 #include "include/rpc-port.h"
30 #include "log-private.hh"
31 #include "message-sending-thread-internal.hh"
32 #include "port-internal.hh"
38 constexpr const int QUEUE_SIZE_MAX = 1024 * 1024 * 10;
39 constexpr const int MAX_RETRY_CNT = 10;
40 constexpr const int MAX_TIMEOUT = 1000;
41 constexpr const int MIN_TIMEOUT = 50;
45 Port::DelayMessage::DelayMessage(const char* msg, int index, int size)
46 : message_(msg, msg + size), index_(index), size_(size) {
49 void Port::DelayMessage::SetIndex(int index) {
53 int Port::DelayMessage::GetSize() {
54 return size_ - index_;
57 int Port::DelayMessage::GetOriginalSize() {
61 char* Port::DelayMessage::GetMessage() {
62 char* ptr = reinterpret_cast<char*>(message_.data());
67 Port::Port(int fd, std::string id)
68 : fd_(fd), id_(std::move(id)), instance_(""), seq_(0) {
72 uuid_unparse(u, uuid);
73 instance_ = std::string(uuid) + ":" + id_;
76 Port::Port(int fd, std::string id, std::string instance)
77 : fd_(fd), id_(std::move(id)), instance_(std::move(instance)), seq_(0) {}
80 std::lock_guard<std::recursive_mutex> lock(mutex_);
85 void Port::Disconnect() {
88 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
90 _W("Close fd(%d)", fd_);
96 int Port::SetPrivateSharing(const char* paths[], unsigned int size) {
97 int ret = aul_rpc_port_set_private_sharing(id_.c_str(), paths, size);
99 return RPC_PORT_ERROR_IO_ERROR;
100 return RPC_PORT_ERROR_NONE;
103 int Port::SetPrivateSharing(const char* path) {
104 const char* file_list[1] = {path};
105 int ret = aul_rpc_port_set_private_sharing(id_.c_str(), file_list, 1);
107 return RPC_PORT_ERROR_IO_ERROR;
108 return RPC_PORT_ERROR_NONE;
111 int Port::UnsetPrivateSharing() {
112 int ret = aul_rpc_port_unset_private_sharing(id_.c_str());
114 return RPC_PORT_ERROR_IO_ERROR;
115 return RPC_PORT_ERROR_NONE;
118 int Port::Read(void* buf, unsigned int size) {
119 unsigned int left = size;
122 char* buffer = static_cast<char*>(buf);
123 int max_timeout = MAX_TIMEOUT * MAX_RETRY_CNT;
124 int timeout = MIN_TIMEOUT;
128 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
132 if (fd < 0 || fd >= sysconf(_SC_OPEN_MAX)) {
133 _E("Invalid fd(%d)", fd);
134 return RPC_PORT_ERROR_IO_ERROR;
139 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
140 nb = read(fd_, buffer, left);
144 _E("read_socket: ...read EOF, socket closed %d: nb %zd\n", fd, nb);
145 return RPC_PORT_ERROR_IO_ERROR;
146 } else if (nb == -1) {
147 if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
148 bool can_read = false;
149 while (!can_read && max_timeout > 0) {
150 auto start = std::chrono::steady_clock::now();
151 can_read = CanRead(timeout);
152 auto end = std::chrono::steady_clock::now();
154 std::chrono::duration_cast<std::chrono::milliseconds>(
157 max_timeout -= elapsed_time.count();
160 if (timeout > MAX_TIMEOUT)
161 timeout = MAX_TIMEOUT;
165 _E("read_socket: ...timed out fd %d: errno %d", fd, errno);
166 return RPC_PORT_ERROR_IO_ERROR;
172 _E("read_socket: ...error fd %d: errno %d\n", fd, errno);
173 return RPC_PORT_ERROR_IO_ERROR;
179 timeout = MIN_TIMEOUT;
182 return RPC_PORT_ERROR_NONE;
185 bool Port::CanRead(int timeout) {
186 struct pollfd fds[1];
188 fds[0].events = POLLIN;
190 int ret = poll(fds, 1, timeout);
192 _W("poll() is failed. fd(%d), error(%s)",
193 fd_, ret == 0 ? "timed out" : std::to_string(-errno).c_str());
200 bool Port::CanWrite() {
201 struct pollfd fds[1];
203 fds[0].events = POLLOUT;
205 int ret = poll(fds, 1, 100);
207 _W("poll() is failed. fd(%d), error(%s)",
208 fd_, ret == 0 ? "timed out" : std::to_string(-errno).c_str());
215 int Port::Write(const void* buf, unsigned int size) {
218 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
220 if (queue_.empty()) {
221 ret = Write(buf, size, &sent_bytes);
222 if (ret == PORT_STATUS_ERROR_NONE)
223 return RPC_PORT_ERROR_NONE;
224 else if (ret == PORT_STATUS_ERROR_IO_ERROR)
225 return RPC_PORT_ERROR_IO_ERROR;
228 if (delayed_message_size_ > QUEUE_SIZE_MAX) {
229 _E("cache fail : delayed_message_size (%d), count(%zu)",
230 delayed_message_size_, queue_.size());
231 return RPC_PORT_ERROR_IO_ERROR;
234 ret = PushDelayedMessage(
235 std::make_shared<DelayMessage>(static_cast<const char*>(buf),
239 while (!queue_.empty()) {
240 int port_status = PopDelayedMessage();
241 if (port_status != PORT_STATUS_ERROR_NONE) {
242 if (port_status == PORT_STATUS_ERROR_IO_ERROR)
243 return RPC_PORT_ERROR_IO_ERROR;
253 int Port::Write(const void* buf, unsigned int size, int* sent_bytes) {
254 unsigned int left = size;
257 const char* buffer = static_cast<const char*>(buf);
259 if (fd_ < 0 || fd_ >= sysconf(_SC_OPEN_MAX)) {
260 _E("Invalid fd(%d)", fd_);
261 return PORT_STATUS_ERROR_IO_ERROR;
264 while (left && (retry_cnt < MAX_RETRY_CNT)) {
265 nb = send(fd_, buffer, left, MSG_NOSIGNAL);
267 if (errno == EINTR) {
268 LOGI("write_socket: EINTR continue ...");
273 if (errno == EAGAIN || errno == EWOULDBLOCK)
274 return PORT_STATUS_ERROR_RESOURCE_UNAVAILABLE;
276 _E("write_socket: ...error fd %d: errno %d\n", fd_, errno);
277 return PORT_STATUS_ERROR_IO_ERROR;
286 _E("error fd %d: retry_cnt %d", fd_, retry_cnt);
287 return PORT_STATUS_ERROR_IO_ERROR;
290 return PORT_STATUS_ERROR_NONE;
293 gboolean Port::OnEventReceived(GIOChannel* io, GIOCondition condition,
295 auto* ptr = static_cast<std::weak_ptr<Port>*>(data);
296 auto port = ptr->lock();
297 if (port == nullptr) {
298 _E("port is destructed");
299 return G_SOURCE_REMOVE;
302 std::lock_guard<std::recursive_mutex> lock(port->rw_mutex_);
303 if (port->source_id_ == 0) {
304 _E("GSource is destroyed");
305 return G_SOURCE_REMOVE;
308 if (port->queue_.empty()) {
309 port->IgnoreIOEvent();
310 return G_SOURCE_CONTINUE;
313 port->PopDelayedMessage();
314 return G_SOURCE_CONTINUE;
317 void Port::ClearQueue() {
318 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
320 while (queue_.empty() == false)
324 delayed_message_size_ = 0;
327 void Port::IgnoreIOEvent() {
328 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
329 if (source_id_ != 0) {
330 GSource* source = g_main_context_find_source_by_id(
331 MessageSendingThread::GetInst().GetContext(), source_id_);
332 if (source != nullptr && !g_source_is_destroyed(source))
333 g_source_destroy(source);
338 if (channel_ != nullptr) {
339 g_io_channel_unref(channel_);
344 int Port::ListenIOEvent() {
345 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
346 channel_ = g_io_channel_unix_new(fd_);
347 if (channel_ == nullptr) {
348 _E("Failed to create GIOChannel");
349 return RPC_PORT_ERROR_OUT_OF_MEMORY;
352 GSource* source = g_io_create_watch(channel_,
353 static_cast<GIOCondition>(G_IO_OUT));
354 if (source == nullptr) {
355 _E("Failed to create GSource");
357 return RPC_PORT_ERROR_OUT_OF_MEMORY;
360 auto* ptr = new (std::nothrow) std::weak_ptr<Port>(shared_from_this());
361 g_source_set_callback(source, reinterpret_cast<GSourceFunc>(OnEventReceived),
362 static_cast<gpointer>(ptr), [](gpointer ptr) {
363 auto* port = static_cast<std::weak_ptr<Port>*>(ptr);
366 g_source_set_priority(source, G_PRIORITY_DEFAULT);
367 source_id_ = g_source_attach(source,
368 MessageSendingThread::GetInst().GetContext());
369 g_source_unref(source);
371 return RPC_PORT_ERROR_NONE;
374 int Port::PopDelayedMessage() {
376 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
377 auto dm = queue_.front();
379 int ret = Write(dm->GetMessage(), dm->GetSize(), &sent_bytes);
380 if (ret == PORT_STATUS_ERROR_RESOURCE_UNAVAILABLE) {
381 dm->SetIndex(sent_bytes);
382 } else if (ret == PORT_STATUS_ERROR_IO_ERROR) {
385 delayed_message_size_ -= dm->GetOriginalSize();
389 _W("cache : count(%zu), delayed_message_size(%d), ret(%d), sent_bytes(%d)",
390 queue_.size(), delayed_message_size_, ret, sent_bytes);
394 int Port::PushDelayedMessage(std::shared_ptr<DelayMessage> dm) {
395 std::lock_guard<std::recursive_mutex> lock(rw_mutex_);
396 if (queue_.empty()) {
397 int ret = ListenIOEvent();
398 if (ret != RPC_PORT_ERROR_NONE)
402 delayed_message_size_ += dm->GetOriginalSize();
405 _W("cache : count(%zu), delayed_message_size(%d)",
406 queue_.size(), delayed_message_size_);
407 return RPC_PORT_ERROR_NONE;
410 } // namespace internal
411 } // namespace rpc_port