Exemple #1
0
    void
    finalize(const std::error_code& ec) {
        // Prepare the internal socket object for consequential operations by moving its contents to a
        // heap-allocated object, which in turn might be attached to an engine.
        auto ptr = std::make_unique<protocol_type::socket>(std::move(socket));

        switch(ec.value()) {
        case 0:
            COCAINE_LOG_DEBUG(parent->m_log, "accepted connection on fd {}", ptr->native_handle());

            try {
                auto base = parent->fact();
                auto session = parent->m_context.engine().attach(std::move(ptr), base);
                parent->bind(base, std::move(session));
            } catch(const std::system_error& e) {
                COCAINE_LOG_ERROR(parent->m_log, "unable to attach connection to engine: {}",
                    error::to_string(e));
                ptr = nullptr;
            }

            break;

        case asio::error::operation_aborted:
            return;

        default:
            COCAINE_LOG_ERROR(parent->m_log, "unable to accept connection: [{}] {}", ec.value(),
                ec.message());
            break;
        }

        // TODO: Find out if it's always a good idea to continue accepting connections no matter what.
        // For example, destroying a socket from outside this thread will trigger weird stuff on Linux.
        operator()();
    }
Exemple #2
0
static void handleMergeWriterError(std::error_code &Error,
                                   StringRef WhenceFile = "",
                                   StringRef WhenceFunction = "",
                                   bool ShowHint = true) {
  if (!WhenceFile.empty())
    errs() << WhenceFile << ": ";
  if (!WhenceFunction.empty())
    errs() << WhenceFunction << ": ";
  errs() << Error.message() << "\n";

  if (ShowHint) {
    StringRef Hint = "";
    if (Error.category() == instrprof_category()) {
      instrprof_error instrError = static_cast<instrprof_error>(Error.value());
      switch (instrError) {
      case instrprof_error::hash_mismatch:
      case instrprof_error::count_mismatch:
      case instrprof_error::value_site_count_mismatch:
        Hint = "Make sure that all profile data to be merged is generated "
               "from the same binary.";
        break;
      default:
        break;
      }
    }

    if (!Hint.empty())
      errs() << Hint << "\n";
  }
}
 /// The error is a connection-level protocol error.
 bool is_session_level_protocol_error() const
 {
     if (error_code.category() != realm::sync::protocol_error_category()) {
         return false;
     }
     return realm::sync::is_session_level_error(static_cast<ProtocolError>(error_code.value()));
 }
static ::testing::AssertionResult ErrorEquals(std::error_code Expected,
                                              std::error_code Found) {
  if (Expected == Found)
    return ::testing::AssertionSuccess();
  return ::testing::AssertionFailure() << "error " << Found.value()
                                       << ": " << Found.message();
}
Exemple #5
0
void AsyncSerial::readEnd(const std::error_code& error,
        size_t bytes_transferred)
{
    if(error)
    {
        #ifdef __APPLE__
        if(error.value()==45)
        {
            //Bug on OS X, it might be necessary to repeat the setup
            //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
            doRead();
            return;
        }
        #endif //__APPLE__
        //error can be true even because the serial port was closed.
        //In this case it is not a real error, so ignore
        if(isOpen())
        {
            doClose();
            setErrorStatus(true);
        }
    } else {
        if(pimpl->callback) pimpl->callback(pimpl->readBuffer,
                bytes_transferred);
        doRead();
    }
}
Exemple #6
0
    static inline
    void
    pack(msgpack::packer<Stream>& target, const std::error_code& source) {
        int category_id = error::registrar::map(source.category());
        int ec          = source.value();

        type_traits<sequence_type>::pack(target, category_id, ec);
    }
Exemple #7
0
void
multicast_t::on_receive(const std::error_code& ec, size_t bytes_received,
                        const std::shared_ptr<announce_t>& ptr)
{
    if(ec) {
        if(ec != asio::error::operation_aborted) {
            COCAINE_LOG_ERROR(m_log, "unexpected error in multicast_t::on_receive(): [%d] %s",
                ec.value(), ec.message()
            );
        }

        return;
    }

    msgpack::unpacked unpacked;

    try {
        msgpack::unpack(&unpacked, ptr->buffer.data(), bytes_received);
    } catch(const msgpack::unpack_error& e) {
        COCAINE_LOG_ERROR(m_log, "unable to unpack announce: %s", e.what());
        return;
    }

    std::string uuid;
    std::vector<tcp::endpoint> endpoints;

    try {
        type_traits<announce_t::tuple_type>::unpack(unpacked.get(), std::tie(uuid, endpoints));
    } catch(const msgpack::type_error& e) {
        COCAINE_LOG_ERROR(m_log, "unable to decode announce: %s", e.what());
        return;
    }

    if(uuid != m_locator.uuid()) {
        COCAINE_LOG_DEBUG(m_log, "received %d endpoint(s) from %s", endpoints.size(), ptr->endpoint)(
            "uuid", uuid
        );

        auto& expiration = m_expirations[uuid];

        if(!expiration) {
            expiration = std::make_unique<deadline_timer>(m_locator.asio());

            // Link a new node only when seen for the first time.
            m_locator.link_node(uuid, endpoints);
        }

        expiration->expires_from_now(m_cfg.interval * 3);
        expiration->async_wait(std::bind(&multicast_t::on_expired, this, ph::_1, uuid));
    }

    const auto announce = std::make_shared<announce_t>();

    m_socket.async_receive_from(buffer(announce->buffer.data(), announce->buffer.size()),
        announce->endpoint,
        std::bind(&multicast_t::on_receive, this, ph::_1, ph::_2, announce)
    );
}
Exemple #8
0
 uintmax_t hard_link_count(struct stat st, std::error_code& ec)
 {
   if (ec.value() == 0) {
     ec.clear();
   } else {
     return 0;
   }
   return st.st_nlink;
 }
Exemple #9
0
 uintmax_t file_size(struct stat st, std::error_code& ec)
 {
   if (ec.value() == 0) {
     ec.clear();
   } else {
     return 0;
   }
   return st.st_size;
 }
Exemple #10
0
	std::string FormatError(std::error_code err)
	{
#if BOOST_OS_WINDOWS
		if (err.category() == std::system_category())
			err.assign(err.value(), ext::system_utf8_category());
#endif

		return FormatErrorImpl(err);
	}
void NetworkInterfaceASIO::_networkErrorCallback(AsyncOp* op, const std::error_code& ec) {
    if (ec.category() == mongoErrorCategory()) {
        // If we get a Mongo error code, we can preserve it.
        _completeOperation(op, Status(ErrorCodes::fromInt(ec.value()), ec.message()));
    } else {
        // If we get an asio or system error, we just convert it to a network error.
        _completeOperation(op, Status(ErrorCodes::HostUnreachable, ec.message()));
    }
}
static mb::optional<int> extract_errno(std::error_code ec)
{
    if (ec.category() == std::generic_category()
            || ec.category() == std::system_category()) {
        return ec.value();
    }

    return {};
}
Exemple #13
0
 file_type to_file_type(struct stat st, std::error_code& ec)
 {
   if (ec != std::error_code()) {
     switch (ec.value()) {
     case ENOENT: return file_type::not_found;
     default: return file_type::none;
     }
   }
   return to_file_type(st.st_mode);
 }
void WalletUserTransactionsCache::updateTransactionSendingState(TransactionId transactionId, std::error_code ec) {
  auto& txInfo = m_transactions.at(transactionId);
  if (ec) {
    txInfo.state = ec.value() == error::TX_CANCELLED ? WalletLegacyTransactionState::Cancelled : WalletLegacyTransactionState::Failed;
    m_unconfirmedTransactions.erase(txInfo.hash);
  } else {
    txInfo.sentTime = time(nullptr); // update sending time
    txInfo.state = WalletLegacyTransactionState::Active;
  }
}
static void exitWithErrorCode(const std::error_code &Error, StringRef Whence = "") {
  if (Error.category() == instrprof_category()) {
    instrprof_error instrError = static_cast<instrprof_error>(Error.value());
    if (instrError == instrprof_error::unrecognized_format) {
      // Hint for common error of forgetting -sample for sample profiles.
      exitWithError(Error.message(), Whence,
                    "Perhaps you forgot to use the -sample option?");
    }
  }
  exitWithError(Error.message(), Whence);
}
 virtual void do_error(std::error_code ec,
                       const parsing_context& context) throw(json_parse_exception)
 {
     if (ec.category() == json_error_category())
     {
         if (ec.value() != value_)
         {
             default_parse_error_handler::instance().error(ec,context);
         }
     }
 }
 virtual void do_error(std::error_code ec,
                       const parsing_context& context) throw(parse_exception)
 {
     if (ec.category() == json_error_category())
     {
         if (ec.value() != jsoncons::json_parser_errc::extra_comma && (context.current_char() == ']' || context.current_char() == '}'))
         {
             default_parse_error_handler::instance().error(ec,context);
         }
     }
 }
    void on_error(Exec&, const std::error_code & ec)
    {
#if defined(BOOST_POSIX_API)
        errored = true;
#endif
        auto & h = init.handler;
        ios.post(
                [h, ec]() mutable
                {
                    h(boost::system::error_code(ec.value(), boost::system::system_category()), -1);
                });
    }
Exemple #19
0
void
engine_t::on_disconnect(int fd, const std::error_code& ec) {
    COCAINE_LOG_INFO(
        m_log,
        "slave has disconnected during the handshake on fd %d - [%d] %s",
        fd,
        ec.value(),
        ec.message()
    );

    m_backlog.erase(fd);
}
Exemple #20
0
void
control_service_t::on_config_void_result(deferred<command_result<void>> promise,
                                         const std::error_code& ec)
{
    if(ec) {
        promise.write(
            command_result<void>(static_cast<raft_errc>(ec.value()), m_config_actor->leader_id())
        );
    } else {
        promise.write(command_result<void>());
    }
}
Exemple #21
0
any
rpc::make_error( std::error_code err )
{
	any reply;

	if ( err.category() == rpc::error_category() )
	{
		reply[ "error" ][ "code" ]		= err.value();
		reply[ "error" ][ "message" ]	= err.message();
	}
	else if ( is_user_defined_error( err.value() ) )
	{
		reply[ "error" ][ "code" ]		= err.value();
		reply[ "error" ][ "message" ]	= err.message();
	}
	else
	{
		reply[ "error" ][ "code" ]		= errc::internal_error;
		reply[ "error" ][ "message" ]	= "unknown";
	}

	return reply;
}
Exemple #22
0
bool ProxySession::WriteOutputTo(FileDesc& dest, std::error_code &ec)
{
    while(!ec && !this->m_output_vec.empty())
    {
        RSlice slice = m_output_vec.front();
        m_output_vec.pop_front();

        WriteAll(dest, slice, ec);
    }

    // in case of write failure, just clear the vec
    m_output_vec.clear();

    return ec.value();
}
Exemple #23
0
void
control_service_t::on_config_change_error(const std::string& machine,
                                          uint64_t operation_id,
                                          deferred<command_result<cluster_change_result>> promise,
                                          const std::error_code& ec)
{
    if(ec) {
        m_config_actor->machine().pop_operation(machine, operation_id);

        auto errc = static_cast<raft_errc>(ec.value());
        promise.write(
            command_result<cluster_change_result>(errc, m_config_actor->leader_id())
        );
    }
}
Exemple #24
0
bool ProxySession::Transfer(FileDesc& src, FileDesc& dest, IParser& parser, std::error_code &ec)
{
    // until we're using an actual plugin, just read and write to a local buffer
    auto inBuff = parser.GetWriteSlice();
    auto numRead = read(src, inBuff, inBuff.Size());

    if(numRead < 0) {
            ec = std::error_code(errno, std::system_category());
            return false;
    }

    if(numRead == 0) {
            ec = Error::END_OF_FILE;
            return false;
    }


    if(m_config.observeOnly)
    {
        // in observe only mode we just write the data we read immediately
        // there is no guarantee that the parser doesn't modify the buffer

        this->WriteAll(dest, RSlice(inBuff, numRead), ec);

        // regardless of if there is any error or not, we feed the parser
        // but ignore whatever it outputs
        parser.Parse(numRead);
    }
    else
    {
        // now notify the parser that we wrote some data into its input buffer
        if(parser.Parse(numRead))
        {
            // if the parser didn't reject it, pass output anything the parser kicked back
            this->WriteOutputTo(dest, ec);
        }
        else
        {
            ec = Error::PARSER_REJECT;
        }
    }

    // always clear any unwritten slices due to error or explicit parser rejection
    this->m_output_vec.clear();

    return ec.value();
}
Exemple #25
0
    file_time_type last_write_time(struct stat st, std::error_code& ec)
    {
      if (ec.value() == 0) {
        ec.clear();
      } else {
        return {};
      }
#if __APPLE__
      return file_time_type() +
             std::chrono::duration_cast<file_time_type::duration>(
               std::chrono::nanoseconds(st.st_mtimespec.tv_nsec));
#else
      return file_time_type() +
             std::chrono::duration_cast<file_time_type::duration>(
               std::chrono::nanoseconds(st.st_mtim.tv_nsec));
#endif
    }
Exemple #26
0
    void
    on_spool(const std::error_code& ec, const std::string& what) {
        if (ec) {
            const auto reason = what.empty() ? ec.message() : what;

            COCAINE_LOG_ERROR(log, "unable to spool app - [%d] %s", ec.value(), reason);

            loop->dispatch(std::bind(&app_state_t::cancel, shared_from_this(), reason));

            // Attempt to finish node service's request.
            try {
                deferred.abort(ec, reason);
            } catch (const std::exception&) {
                // Ignore if the client has been disconnected.
            }
        } else {
            // Dispatch the completion handler to be sure it will be called in a I/O thread to
            // avoid possible deadlocks (which ones?).
            loop->dispatch(std::bind(&app_state_t::publish, shared_from_this()));
        }
    }
Exemple #27
0
inline void TCPServerSession::handle_recv_len(std::error_code ec, std::size_t bytes)
{
	if (ec)
	{
		switch (ec.value())
		{
		case asio::error::eof:
			// 远端正常关闭socket
			break;
		case asio::error::connection_reset:
			// 远端暴力关闭socket
			break;
		case asio::error::operation_aborted:
			// 正在async_receive()异步任务等待时,本端关闭套接字
			break;
		case asio::error::bad_descriptor:
			// 在一个已经关闭了的套接字上执行async_receive()
			break;
		default:
			break;
		}
		mCore.Close(GetConnID());
		return;
	}

	try
	{
		// 包总长 + 包类型(单包/多包)
		uint16 length = (uint16)(uint8)mBuffer[0] | ((uint16)(uint8)mBuffer[1] << 8);
		if (mBuffer.size() < size_t(length + 2))
			mBuffer.resize(length + 2);

		auto handler = std::bind(&TCPServerSession::handle_recv_body, shared_from_this(), _1, _2);
		asio::async_read(mSocket, asio::buffer(&mBuffer[0], length + 2), handler);
	}
	catch (...)
	{
	}
}
Exemple #28
0
inline void TCPServerSession::handle_recv_body(std::error_code ec, std::size_t bytes)
{
	if (ec)
	{
		switch (ec.value())
		{
		case asio::error::eof:
			// 远端正常关闭socket
			break;
		case asio::error::connection_reset:
			// 远端暴力关闭socket
			break;
		case asio::error::operation_aborted:
			// 正在async_receive()异步任务等待时,本端关闭套接字
			break;
		case asio::error::bad_descriptor:
			// 在一个已经关闭了的套接字上执行async_receive()
			break;
		default:
			break;
		}
		mCore.Close(GetConnID());
		return;
	}

	try
	{
		char* packet = new char[bytes];
		memcpy(packet, &mBuffer[0], bytes);
		mCore.serial.Post(std::bind(&TCPServerSession::packet_handler, shared_from_this(), packet, bytes));
	}
	catch (...)
	{
	}
	recv_len();
}
static ::testing::AssertionResult NoError(std::error_code EC) {
  if (!EC)
    return ::testing::AssertionSuccess();
  return ::testing::AssertionFailure() << "error " << EC.value()
                                       << ": " << EC.message();
}
void NetworkInterfaceASIO::_networkErrorCallback(AsyncOp* op, const std::error_code& ec) {
    ErrorCodes::Error errorCode = (ec.category() == mongoErrorCategory())
        ? ErrorCodes::fromInt(ec.value())
        : ErrorCodes::HostUnreachable;
    _completeOperation(op, {errorCode, ec.message(), Milliseconds(now() - op->_start)});
}