2 * Copyright 2014 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(const folly::SocketAddress& client,
51 std::unique_ptr<folly::IOBuf> data,
52 bool truncated) noexcept {
55 lastMsg_ = data->moveToFbString().toStdString();
57 auto len = data->computeChainDataLength();
58 VLOG(4) << "Worker " << n_ << " read " << len << " bytes "
59 << "(trun:" << truncated << ") from " << client.describe()
65 void sendPong() noexcept {
67 AsyncUDPSocket socket(evb_);
68 socket.bind(folly::SocketAddress("127.0.0.1", 0));
69 socket.write(lastClient_, folly::IOBuf::copyBuffer(lastMsg_));
70 } catch (const std::exception& ex) {
71 VLOG(4) << "Failed to send PONG " << ex.what();
76 EventBase* const evb_{nullptr};
79 folly::SocketAddress lastClient_;
85 UDPServer(EventBase* evb, folly::SocketAddress addr, int n)
86 : evb_(evb), addr_(addr), evbs_(n) {
90 CHECK(evb_->isInEventBaseThread());
92 socket_ = folly::make_unique<AsyncUDPServerSocket>(
98 VLOG(4) << "Server listening on " << socket_->address().describe();
99 } catch (const std::exception& ex) {
100 LOG(FATAL) << ex.what();
103 acceptors_.reserve(evbs_.size());
104 threads_.reserve(evbs_.size());
106 // Add numWorkers thread
108 for (auto& evb: evbs_) {
109 acceptors_.emplace_back(&evb, i);
111 std::thread t([&] () {
115 auto r = std::make_shared<boost::barrier>(2);
116 evb.runInEventBaseThread([r] () {
121 socket_->addListener(&evb, &acceptors_[i]);
122 threads_.emplace_back(std::move(t));
129 folly::SocketAddress address() const {
130 return socket_->address();
134 CHECK(evb_->isInEventBaseThread());
138 for (auto& evb: evbs_) {
139 evb.terminateLoopSoon();
142 for (auto& t: threads_) {
148 EventBase* const evb_{nullptr};
149 const folly::SocketAddress addr_;
151 std::unique_ptr<AsyncUDPServerSocket> socket_;
152 std::vector<std::thread> threads_;
153 std::vector<folly::EventBase> evbs_;
154 std::vector<UDPAcceptor> acceptors_;
158 : private AsyncUDPSocket::ReadCallback,
159 private AsyncTimeout {
161 explicit UDPClient(EventBase* evb)
166 void start(const folly::SocketAddress& server, int n) {
167 CHECK(evb_->isInEventBaseThread());
170 socket_ = folly::make_unique<AsyncUDPSocket>(evb_);
173 socket_->bind(folly::SocketAddress("127.0.0.1", 0));
174 VLOG(4) << "Client bound to " << socket_->address().describe();
175 } catch (const std::exception& ex) {
176 LOG(FATAL) << ex.what();
179 socket_->resumeRead(this);
183 // Start playing ping pong
188 CHECK(evb_->isInEventBaseThread());
189 socket_->pauseRead();
192 evb_->terminateLoopSoon();
205 folly::IOBuf::copyBuffer(folly::to<std::string>("PING ", n_)));
208 void getReadBuffer(void** buf, size_t* len) noexcept {
213 void onDataAvailable(const folly::SocketAddress& client,
215 bool truncated) noexcept {
216 VLOG(4) << "Read " << len << " bytes (trun:" << truncated << ") from "
217 << client.describe() << " - " << std::string(buf_, len);
218 VLOG(4) << n_ << " left";
225 void onReadError(const folly::AsyncSocketException& ex) noexcept {
226 VLOG(4) << ex.what();
228 // Start listening for next PONG
229 socket_->resumeRead(this);
232 void onReadClosed() noexcept {
233 CHECK(false) << "We unregister reads before closing";
236 void timeoutExpired() noexcept {
237 VLOG(4) << "Timeout expired";
241 int pongRecvd() const {
246 EventBase* const evb_{nullptr};
248 folly::SocketAddress server_;
249 std::unique_ptr<AsyncUDPSocket> socket_;
257 TEST(AsyncSocketTest, PingPong) {
258 folly::EventBase sevb;
259 UDPServer server(&sevb, folly::SocketAddress("127.0.0.1", 0), 4);
260 boost::barrier barrier(2);
262 // Start event loop in a separate thread
263 auto serverThread = std::thread([&sevb] () {
267 // Wait for event loop to start
268 sevb.runInEventBaseThread([&] () { barrier.wait(); });
272 sevb.runInEventBaseThread([&] () { server.start(); barrier.wait(); });
275 folly::EventBase cevb;
276 UDPClient client(&cevb);
278 // Start event loop in a separate thread
279 auto clientThread = std::thread([&cevb] () {
283 // Wait for event loop to start
284 cevb.runInEventBaseThread([&] () { barrier.wait(); });
288 cevb.runInEventBaseThread([&] () { client.start(server.address(), 1000); });
290 // Wait for client to finish
293 // Check that some PING/PONGS were exchanged. Out of 1000 transactions
294 // at least 1 should succeed
295 CHECK_GT(client.pongRecvd(), 0);
298 sevb.runInEventBaseThread([&] () {
300 sevb.terminateLoopSoon();
303 // Wait for server thread to joib