2 * Copyright 2015 Facebook, Inc.
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 <folly/io/async/AsyncUDPSocket.h>
18 #include <folly/io/async/AsyncUDPServerSocket.h>
19 #include <folly/io/async/AsyncTimeout.h>
20 #include <folly/io/async/EventBase.h>
21 #include <folly/SocketAddress.h>
23 #include <boost/thread/barrier.hpp>
25 #include <folly/io/IOBuf.h>
29 #include <gtest/gtest.h>
31 using folly::AsyncUDPSocket;
32 using folly::AsyncUDPServerSocket;
33 using folly::AsyncTimeout;
34 using folly::EventBase;
35 using folly::SocketAddress;
39 : public AsyncUDPServerSocket::Callback {
41 UDPAcceptor(EventBase* evb, int n): evb_(evb), n_(n) {
44 void onListenStarted() noexcept {
47 void onListenStopped() noexcept {
50 void onDataAvailable(std::shared_ptr<folly::AsyncUDPSocket> socket,
51 const folly::SocketAddress& client,
52 std::unique_ptr<folly::IOBuf> data,
53 bool truncated) noexcept {
56 lastMsg_ = data->moveToFbString().toStdString();
58 auto len = data->computeChainDataLength();
59 VLOG(4) << "Worker " << n_ << " read " << len << " bytes "
60 << "(trun:" << truncated << ") from " << client.describe()
66 void sendPong() noexcept {
68 AsyncUDPSocket socket(evb_);
69 socket.bind(folly::SocketAddress("127.0.0.1", 0));
70 socket.write(lastClient_, folly::IOBuf::copyBuffer(lastMsg_));
71 } catch (const std::exception& ex) {
72 VLOG(4) << "Failed to send PONG " << ex.what();
77 EventBase* const evb_{nullptr};
80 folly::SocketAddress lastClient_;
86 UDPServer(EventBase* evb, folly::SocketAddress addr, int n)
87 : evb_(evb), addr_(addr), evbs_(n) {
91 CHECK(evb_->isInEventBaseThread());
93 socket_ = folly::make_unique<AsyncUDPServerSocket>(
99 VLOG(4) << "Server listening on " << socket_->address().describe();
100 } catch (const std::exception& ex) {
101 LOG(FATAL) << ex.what();
104 acceptors_.reserve(evbs_.size());
105 threads_.reserve(evbs_.size());
107 // Add numWorkers thread
109 for (auto& evb: evbs_) {
110 acceptors_.emplace_back(&evb, i);
112 std::thread t([&] () {
116 auto r = std::make_shared<boost::barrier>(2);
117 evb.runInEventBaseThread([r] () {
122 socket_->addListener(&evb, &acceptors_[i]);
123 threads_.emplace_back(std::move(t));
130 folly::SocketAddress address() const {
131 return socket_->address();
135 CHECK(evb_->isInEventBaseThread());
139 for (auto& evb: evbs_) {
140 evb.terminateLoopSoon();
143 for (auto& t: threads_) {
149 EventBase* const evb_{nullptr};
150 const folly::SocketAddress addr_;
152 std::unique_ptr<AsyncUDPServerSocket> socket_;
153 std::vector<std::thread> threads_;
154 std::vector<folly::EventBase> evbs_;
155 std::vector<UDPAcceptor> acceptors_;
159 : private AsyncUDPSocket::ReadCallback,
160 private AsyncTimeout {
162 explicit UDPClient(EventBase* evb)
167 void start(const folly::SocketAddress& server, int n) {
168 CHECK(evb_->isInEventBaseThread());
171 socket_ = folly::make_unique<AsyncUDPSocket>(evb_);
174 socket_->bind(folly::SocketAddress("127.0.0.1", 0));
175 VLOG(4) << "Client bound to " << socket_->address().describe();
176 } catch (const std::exception& ex) {
177 LOG(FATAL) << ex.what();
180 socket_->resumeRead(this);
184 // Start playing ping pong
189 CHECK(evb_->isInEventBaseThread());
190 socket_->pauseRead();
193 evb_->terminateLoopSoon();
206 folly::IOBuf::copyBuffer(folly::to<std::string>("PING ", n_)));
209 void getReadBuffer(void** buf, size_t* len) noexcept {
214 void onDataAvailable(const folly::SocketAddress& client,
216 bool truncated) noexcept {
217 VLOG(4) << "Read " << len << " bytes (trun:" << truncated << ") from "
218 << client.describe() << " - " << std::string(buf_, len);
219 VLOG(4) << n_ << " left";
226 void onReadError(const folly::AsyncSocketException& ex) noexcept {
227 VLOG(4) << ex.what();
229 // Start listening for next PONG
230 socket_->resumeRead(this);
233 void onReadClosed() noexcept {
234 CHECK(false) << "We unregister reads before closing";
237 void timeoutExpired() noexcept {
238 VLOG(4) << "Timeout expired";
242 int pongRecvd() const {
247 EventBase* const evb_{nullptr};
249 folly::SocketAddress server_;
250 std::unique_ptr<AsyncUDPSocket> socket_;
258 TEST(AsyncSocketTest, PingPong) {
259 folly::EventBase sevb;
260 UDPServer server(&sevb, folly::SocketAddress("127.0.0.1", 0), 4);
261 boost::barrier barrier(2);
263 // Start event loop in a separate thread
264 auto serverThread = std::thread([&sevb] () {
268 // Wait for event loop to start
269 sevb.runInEventBaseThread([&] () { barrier.wait(); });
273 sevb.runInEventBaseThread([&] () { server.start(); barrier.wait(); });
276 folly::EventBase cevb;
277 UDPClient client(&cevb);
279 // Start event loop in a separate thread
280 auto clientThread = std::thread([&cevb] () {
284 // Wait for event loop to start
285 cevb.runInEventBaseThread([&] () { barrier.wait(); });
289 cevb.runInEventBaseThread([&] () { client.start(server.address(), 1000); });
291 // Wait for client to finish
294 // Check that some PING/PONGS were exchanged. Out of 1000 transactions
295 // at least 1 should succeed
296 CHECK_GT(client.pongRecvd(), 0);
299 sevb.runInEventBaseThread([&] () {
301 sevb.terminateLoopSoon();
304 // Wait for server thread to joib