From 5d02b80e9cde00280cbac5c17cc3843806ec9436 Mon Sep 17 00:00:00 2001 From: Jake Farrell Date: Tue, 7 Jan 2014 21:42:01 -0500 Subject: [PATCH] Thrift-2029:Port C++ tests to Windows Client: cpp Patch: Ben Craig Updates cpp tests to work with windows and c++11 --- lib/cpp/test/AllProtocolTests.tcc | 30 +-- lib/cpp/test/DebugProtoTest.cpp | 1 + lib/cpp/test/JSONProtoTest.cpp | 1 + lib/cpp/test/OptionalRequiredTest.cpp | 2 +- lib/cpp/test/SpecializationTest.cpp | 3 +- lib/cpp/test/TBufferBaseTest.cpp | 6 +- lib/cpp/test/TMemoryBufferTest.cpp | 8 +- lib/cpp/test/TransportTest.cpp | 330 +++++++++++-------------- lib/cpp/test/ZlibTest.cpp | 74 +----- test/cpp/src/StressTest.cpp | 48 +++- test/cpp/src/StressTestNonBlocking.cpp | 27 +- test/cpp/src/TestClient.cpp | 47 ++-- test/cpp/src/TestServer.cpp | 103 ++++---- test/threads/ThreadsClient.cpp | 6 + test/threads/ThreadsServer.cpp | 9 +- 15 files changed, 343 insertions(+), 352 deletions(-) diff --git a/lib/cpp/test/AllProtocolTests.tcc b/lib/cpp/test/AllProtocolTests.tcc index 9155da88..7ccaef5b 100644 --- a/lib/cpp/test/AllProtocolTests.tcc +++ b/lib/cpp/test/AllProtocolTests.tcc @@ -45,7 +45,7 @@ void testNaked(Val val) { Val out; GenericIO::read(protocol, out); if (out != val) { - snprintf(errorMessage, ERR_LEN, "Invalid naked test (type: %s)", ClassNames::getName()); + THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid naked test (type: %s)", ClassNames::getName()); throw TException(errorMessage); } } @@ -71,11 +71,11 @@ void testField(const Val val) { protocol->readFieldBegin(name, fieldType, fieldId); if (fieldId != 15) { - snprintf(errorMessage, ERR_LEN, "Invalid ID (type: %s)", typeid(val).name()); + THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid ID (type: %s)", typeid(val).name()); throw TException(errorMessage); } if (fieldType != type) { - snprintf(errorMessage, ERR_LEN, "Invalid Field Type (type: %s)", typeid(val).name()); + THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid Field Type (type: %s)", typeid(val).name()); throw TException(errorMessage); } @@ -83,7 +83,7 @@ void testField(const Val val) { GenericIO::read(protocol, out); if (out != val) { - snprintf(errorMessage, ERR_LEN, "Invalid value read (type: %s)", typeid(val).name()); + THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid value read (type: %s)", typeid(val).name()); throw TException(errorMessage); } @@ -143,8 +143,8 @@ void testProtocol(const char* protoname) { testNaked((int16_t)-1); testNaked((int16_t)-15000); testNaked((int16_t)-0x7fff); - testNaked(std::numeric_limits::min()); - testNaked(std::numeric_limits::max()); + testNaked((std::numeric_limits::min)()); + testNaked((std::numeric_limits::max)()); testField((int16_t)0); testField((int16_t)1); @@ -165,8 +165,8 @@ void testProtocol(const char* protoname) { testNaked(-1); testNaked(-15000); testNaked(-0xffff); - testNaked(std::numeric_limits::min()); - testNaked(std::numeric_limits::max()); + testNaked((std::numeric_limits::min)()); + testNaked((std::numeric_limits::max)()); testField(0); testField(1); @@ -182,12 +182,12 @@ void testProtocol(const char* protoname) { testField(-15000); testField(-0xffff); testField(-0xffffff); - testNaked(std::numeric_limits::min()); - testNaked(std::numeric_limits::max()); - testNaked(std::numeric_limits::min() + 10); - testNaked(std::numeric_limits::max() - 16); - testNaked(std::numeric_limits::min()); - testNaked(std::numeric_limits::max()); + testNaked((std::numeric_limits::min)()); + testNaked((std::numeric_limits::max)()); + testNaked((std::numeric_limits::min)() + 10); + testNaked((std::numeric_limits::max)() - 16); + testNaked((std::numeric_limits::min)()); + testNaked((std::numeric_limits::max)()); testNaked(0); @@ -219,7 +219,7 @@ void testProtocol(const char* protoname) { printf("%s => OK\n", protoname); } catch (TException e) { - snprintf(errorMessage, ERR_LEN, "%s => Test FAILED: %s", protoname, e.what()); + THRIFT_SNPRINTF(errorMessage, ERR_LEN, "%s => Test FAILED: %s", protoname, e.what()); throw TException(errorMessage); } } diff --git a/lib/cpp/test/DebugProtoTest.cpp b/lib/cpp/test/DebugProtoTest.cpp index 26cc1ea6..5649e18f 100644 --- a/lib/cpp/test/DebugProtoTest.cpp +++ b/lib/cpp/test/DebugProtoTest.cpp @@ -17,6 +17,7 @@ * under the License. */ +#define _USE_MATH_DEFINES #include #include #include "gen-cpp/DebugProtoTest_types.h" diff --git a/lib/cpp/test/JSONProtoTest.cpp b/lib/cpp/test/JSONProtoTest.cpp index dcb34d17..be8f4265 100644 --- a/lib/cpp/test/JSONProtoTest.cpp +++ b/lib/cpp/test/JSONProtoTest.cpp @@ -17,6 +17,7 @@ * under the License. */ +#define _USE_MATH_DEFINES #include #include #include diff --git a/lib/cpp/test/OptionalRequiredTest.cpp b/lib/cpp/test/OptionalRequiredTest.cpp index ddafa81d..44b68859 100644 --- a/lib/cpp/test/OptionalRequiredTest.cpp +++ b/lib/cpp/test/OptionalRequiredTest.cpp @@ -157,7 +157,7 @@ int main() { write_to_read(t2, t3); abort(); } - catch (TProtocolException& ex) {} + catch (const TProtocolException&) {} write_to_read(t3, t2); assert(t2.__isset.im_optional); diff --git a/lib/cpp/test/SpecializationTest.cpp b/lib/cpp/test/SpecializationTest.cpp index 7a3d347e..0bef12ad 100644 --- a/lib/cpp/test/SpecializationTest.cpp +++ b/lib/cpp/test/SpecializationTest.cpp @@ -1,3 +1,4 @@ +#define _USE_MATH_DEFINES #include #include #include @@ -32,7 +33,7 @@ int main() { n.my_ooe.integer16 = 16; n.my_ooe.integer32 = 32; n.my_ooe.integer64 = 64; - n.my_ooe.double_precision = (std::sqrt(5)+1)/2; + n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2; n.my_ooe.some_characters = ":R (me going \"rrrr\")"; n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20" "\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e" diff --git a/lib/cpp/test/TBufferBaseTest.cpp b/lib/cpp/test/TBufferBaseTest.cpp index f88a019e..5d0bf456 100644 --- a/lib/cpp/test/TBufferBaseTest.cpp +++ b/lib/cpp/test/TBufferBaseTest.cpp @@ -349,7 +349,7 @@ BOOST_AUTO_TEST_CASE( test_MemoryBuffer_Write_Read_Incomplete ) { int write_index = 0; unsigned int to_write = (1<<14)-42; while (to_write > 0) { - int write_amt = std::min(dist[d1][write_index], to_write); + int write_amt = (std::min)(dist[d1][write_index], to_write); buffer.write(&data[write_offset], write_amt); write_offset += write_amt; write_index++; @@ -360,7 +360,7 @@ BOOST_AUTO_TEST_CASE( test_MemoryBuffer_Write_Read_Incomplete ) { int read_index = 0; unsigned int to_read = (1<<13)-42; while (to_read > 0) { - int read_amt = std::min(dist[d2][read_index], to_read); + int read_amt = (std::min)(dist[d2][read_index], to_read); int got = buffer.read(&data_out[read_offset], read_amt); BOOST_CHECK_EQUAL(got, read_amt); read_offset += read_amt; @@ -374,7 +374,7 @@ BOOST_AUTO_TEST_CASE( test_MemoryBuffer_Write_Read_Incomplete ) { int second_index = write_index-1; unsigned int to_second = (1<<14)+42; while (to_second > 0) { - int second_amt = std::min(dist[d1][second_index], to_second); + int second_amt = (std::min)(dist[d1][second_index], to_second); //printf("%d\n", second_amt); buffer.write(&data[second_offset], second_amt); second_offset += second_amt; diff --git a/lib/cpp/test/TMemoryBufferTest.cpp b/lib/cpp/test/TMemoryBufferTest.cpp index 10b53f43..b81a6676 100644 --- a/lib/cpp/test/TMemoryBufferTest.cpp +++ b/lib/cpp/test/TMemoryBufferTest.cpp @@ -46,7 +46,7 @@ BOOST_AUTO_TEST_CASE( test_roundtrip ) { shared_ptr strBuffer2(new TMemoryBuffer()); shared_ptr binaryProtcol2(new TBinaryProtocol(strBuffer2)); - strBuffer2->resetBuffer((uint8_t*)serialized.data(), serialized.length()); + strBuffer2->resetBuffer((uint8_t*)serialized.data(), static_cast(serialized.length())); thrift::test::Xtruct a2; a2.read(binaryProtcol2.get()); @@ -62,7 +62,7 @@ BOOST_AUTO_TEST_CASE( test_copy ) string* str1 = new string("abcd1234"); const char* data1 = str1->data(); - TMemoryBuffer buf((uint8_t*)str1->data(), str1->length(), TMemoryBuffer::COPY); + TMemoryBuffer buf((uint8_t*)str1->data(), static_cast(str1->length()), TMemoryBuffer::COPY); delete str1; string* str2 = new string("plsreuse"); bool obj_reuse = (str1 == str2); @@ -94,12 +94,12 @@ BOOST_AUTO_TEST_CASE( test_exceptions ) try { buf1.write((const uint8_t*)"foo", 3); assert(false); - } catch (TTransportException& ex) {} + } catch (TTransportException&) {} TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY); try { buf2.write((const uint8_t*)"bar", 3); - } catch (TTransportException& ex) { + } catch (TTransportException&) { assert(false); } } diff --git a/lib/cpp/test/TransportTest.cpp b/lib/cpp/test/TransportTest.cpp index 4233e6e2..78c27647 100755 --- a/lib/cpp/test/TransportTest.cpp +++ b/lib/cpp/test/TransportTest.cpp @@ -16,17 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -#ifndef _GNU_SOURCE -#define _GNU_SOURCE // needed for getopt_long -#endif - #include #include -#include -#include -#include #include -#include +#include +#include #include #include @@ -40,10 +34,15 @@ #include #include +#include +#if _WIN32 + #include +#endif + + using namespace apache::thrift::transport; static boost::mt19937 rng; -static const char* tmp_dir = "/tmp"; void initrand(unsigned int seed) { rng.seed(seed); @@ -83,8 +82,8 @@ class RandomSizeGenerator : public SizeGenerator { return desc.str(); } - uint32_t getMin() const { return generator_.distribution().min(); } - uint32_t getMax() const { return generator_.distribution().max(); } + uint32_t getMin() const { return (generator_.distribution().min)(); } + uint32_t getMax() const { return (generator_.distribution().max)(); } private: boost::variate_generator< boost::mt19937&, boost::uniform_int > @@ -206,6 +205,8 @@ class CoupledZlibTransportsT : typedef CoupledZlibTransportsT CoupledZlibTransports; +#ifndef _WIN32 +// FD transport doesn't make much sense on Windows. /** * Coupled TFDTransports. */ @@ -222,6 +223,7 @@ class CoupledFDTransports : public CoupledTransports { out.reset(new TFDTransport(pipes[1], TFDTransport::CLOSE_ON_DESTROY)); } }; +#endif /** * Coupled TSockets @@ -229,8 +231,8 @@ class CoupledFDTransports : public CoupledTransports { class CoupledSocketTransports : public CoupledTransports { public: CoupledSocketTransports() { - int sockets[2]; - if (socketpair(PF_UNIX, SOCK_STREAM, 0, sockets) != 0) { + THRIFT_SOCKET sockets[2] = {0}; + if (THRIFT_SOCKETPAIR(PF_UNIX, SOCK_STREAM, 0, sockets) != 0) { return; } @@ -240,20 +242,30 @@ class CoupledSocketTransports : public CoupledTransports { } }; +//These could be made to work on Windows, but I don't care enough to make it happen +#ifndef _WIN32 /** * Coupled TFileTransports */ class CoupledFileTransports : public CoupledTransports { public: CoupledFileTransports() { +#ifndef _WIN32 + const char* tmp_dir = "/tmp"; + #define FILENAME_SUFFIX "/thrift.transport_test" +#else + const char* tmp_dir = getenv("TMP"); + #define FILENAME_SUFFIX "\\thrift.transport_test" +#endif + // Create a temporary file to use - size_t filename_len = strlen(tmp_dir) + 32; - filename = new char[filename_len]; - snprintf(filename, filename_len, - "%s/thrift.transport_test.XXXXXX", tmp_dir); - fd = mkstemp(filename); - if (fd < 0) { - return; + filename.resize(strlen(tmp_dir) + strlen(FILENAME_SUFFIX)); + THRIFT_SNPRINTF(&filename[0], filename.size(), + "%s" FILENAME_SUFFIX, tmp_dir); + #undef FILENAME_SUFFIX + + { + std::ofstream dummy_creation(filename.c_str(), std::ofstream::trunc); } in.reset(new TFileTransport(filename, true)); @@ -261,16 +273,12 @@ class CoupledFileTransports : public CoupledTransports { } ~CoupledFileTransports() { - if (fd >= 0) { - close(fd); - unlink(filename); - } - delete[] filename; + remove(filename.c_str()); } - char* filename; - int fd; + std::string filename; }; +#endif /** * Wrapper around another CoupledTransports implementation that exposes the @@ -337,31 +345,33 @@ struct TriggerInfo { TriggerInfo* next; }; -TriggerInfo* triggerInfo; -unsigned int numTriggersFired; - -void set_alarm(); - -void alarm_handler(int signum) { - (void) signum; - // The alarm timed out, which almost certainly means we're stuck - // on a transport that is incorrectly blocked. - ++numTriggersFired; +apache::thrift::concurrency::Monitor g_alarm_monitor; +TriggerInfo* g_triggerInfo; +unsigned int g_numTriggersFired; +bool g_teardown = false; + +void alarm_handler() { + TriggerInfo *info = NULL; + { + apache::thrift::concurrency::Synchronized s(g_alarm_monitor); + // The alarm timed out, which almost certainly means we're stuck + // on a transport that is incorrectly blocked. + ++g_numTriggersFired; + + // Note: we print messages to stdout instead of stderr, since + // tools/test/runner only records stdout messages in the failure messages for + // boost tests. (boost prints its test info to stdout.) + printf("Timeout alarm expired; attempting to unblock transport\n"); + if (g_triggerInfo == NULL) { + printf(" trigger stack is empty!\n"); + } - // Note: we print messages to stdout instead of stderr, since - // tools/test/runner only records stdout messages in the failure messages for - // boost tests. (boost prints its test info to stdout.) - printf("Timeout alarm expired; attempting to unblock transport\n"); - if (triggerInfo == NULL) { - printf(" trigger stack is empty!\n"); + // Pop off the first TriggerInfo. + // If there is another one, schedule an alarm for it. + info = g_triggerInfo; + g_triggerInfo = info->next; } - // Pop off the first TriggerInfo. - // If there is another one, schedule an alarm for it. - TriggerInfo* info = triggerInfo; - triggerInfo = info->next; - set_alarm(); - // Write some data to the transport to hopefully unblock it. uint8_t* buf = new uint8_t[info->writeLength]; memset(buf, 'b', info->writeLength); @@ -372,21 +382,28 @@ void alarm_handler(int signum) { delete info; } -void set_alarm() { - if (triggerInfo == NULL) { - // clear any alarm - alarm(0); - return; - } - - struct sigaction action; - memset(&action, 0, sizeof(action)); - action.sa_handler = alarm_handler; - action.sa_flags = SA_RESETHAND; - sigemptyset(&action.sa_mask); - sigaction(SIGALRM, &action, NULL); +void alarm_handler_wrapper() { + int64_t timeout = 0; //timeout of 0 means wait forever + while(true) { + bool fireHandler = false; + { + apache::thrift::concurrency::Synchronized s(g_alarm_monitor); + if(g_teardown) + return; + //calculate timeout + if (g_triggerInfo == NULL) { + timeout = 0; + } else { + timeout = g_triggerInfo->timeoutSeconds * 1000; + } - alarm(triggerInfo->timeoutSeconds); + int waitResult = g_alarm_monitor.waitForTimeRelative(timeout); + if(waitResult == THRIFT_ETIMEDOUT) + fireHandler = true; + } + if(fireHandler) + alarm_handler(); //calling outside the lock + } } /** @@ -401,28 +418,34 @@ void add_trigger(unsigned int seconds, const boost::shared_ptr &transport, uint32_t write_len) { TriggerInfo* info = new TriggerInfo(seconds, transport, write_len); - - if (triggerInfo == NULL) { - // This is the first trigger. - // Set triggerInfo, and schedule the alarm - triggerInfo = info; - set_alarm(); - } else { - // Add this trigger to the end of the list - TriggerInfo* prev = triggerInfo; - while (prev->next) { - prev = prev->next; + { + apache::thrift::concurrency::Synchronized s(g_alarm_monitor); + if (g_triggerInfo == NULL) { + // This is the first trigger. + // Set g_triggerInfo, and schedule the alarm + g_triggerInfo = info; + g_alarm_monitor.notify(); + } else { + // Add this trigger to the end of the list + TriggerInfo* prev = g_triggerInfo; + while (prev->next) { + prev = prev->next; + } + prev->next = info; } - - prev->next = info; } } void clear_triggers() { - TriggerInfo *info = triggerInfo; - alarm(0); - triggerInfo = NULL; - numTriggersFired = 0; + TriggerInfo *info = NULL; + + { + apache::thrift::concurrency::Synchronized s(g_alarm_monitor); + info = g_triggerInfo; + g_triggerInfo = NULL; + g_numTriggersFired = 0; + g_alarm_monitor.notify(); + } while (info != NULL) { TriggerInfo* next = info->next; @@ -586,7 +609,7 @@ void test_read_part_available() { transports.out->flush(); set_trigger(3, transports.out, 1); uint32_t bytes_read = transports.in->read(read_buf, 10); - BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0); + BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0); BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 9); clear_triggers(); @@ -608,13 +631,13 @@ void test_read_part_available_in_chunks() { // Read 1 byte, to force the transport to read the frame uint32_t bytes_read = transports.in->read(read_buf, 1); - BOOST_CHECK_EQUAL(bytes_read, 1); + BOOST_CHECK_EQUAL(bytes_read, 1u); // Read more than what is remaining and verify the transport does not block set_trigger(3, transports.out, 1); bytes_read = transports.in->read(read_buf, 10); - BOOST_CHECK_EQUAL(numTriggersFired, 0); - BOOST_CHECK_EQUAL(bytes_read, 9); + BOOST_CHECK_EQUAL(g_numTriggersFired, 0u); + BOOST_CHECK_EQUAL(bytes_read, 9u); clear_triggers(); } @@ -666,7 +689,7 @@ void test_read_partial_midframe() { while (total_read < 9) { set_trigger(3, transports.out, 1); bytes_read = transports.in->read(read_buf, 10); - BOOST_REQUIRE_EQUAL(numTriggersFired, (unsigned int) 0); + BOOST_REQUIRE_EQUAL(g_numTriggersFired, (unsigned int) 0); BOOST_REQUIRE_GT(bytes_read, (uint32_t) 0); total_read += bytes_read; BOOST_REQUIRE_LE(total_read, (uint32_t) 9); @@ -694,7 +717,7 @@ void test_borrow_part_available() { set_trigger(3, transports.out, 1); uint32_t borrow_len = 10; const uint8_t* borrowed_buf = transports.in->borrow(read_buf, &borrow_len); - BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0); + BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0); BOOST_CHECK(borrowed_buf == NULL); clear_triggers(); @@ -720,10 +743,10 @@ void test_read_none_available() { add_trigger(1, transports.out, 8); uint32_t bytes_read = transports.in->read(read_buf, 10); if (bytes_read == 0) { - BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0); + BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0); clear_triggers(); } else { - BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 1); + BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 1); BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 2); } @@ -744,7 +767,7 @@ void test_borrow_none_available() { uint32_t borrow_len = 10; const uint8_t* borrowed_buf = transports.in->borrow(NULL, &borrow_len); BOOST_CHECK(borrowed_buf == NULL); - BOOST_CHECK_EQUAL(numTriggersFired, (unsigned int) 0); + BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0); clear_triggers(); } @@ -828,6 +851,7 @@ class TransportTestGen { TEST_BLOCKING_BEHAVIOR(CoupledMemoryBuffers); +#ifndef _WIN32 // TFDTransport tests // Since CoupledFDTransports tests with a pipe, writes will block // if there is too much outstanding unread data in the pipe. @@ -851,6 +875,7 @@ class TransportTestGen { rand4k, rand4k, fd_max_outstanding); TEST_BLOCKING_BEHAVIOR(CoupledFDTransports); +#endif //_WIN32 // TSocket tests uint32_t socket_max_outstanding = 4096; @@ -876,6 +901,8 @@ class TransportTestGen { TEST_BLOCKING_BEHAVIOR(CoupledSocketTransports); +//These could be made to work on Windows, but I don't care enough to make it happen +#ifndef _WIN32 // TFileTransport tests // We use smaller buffer sizes here, since TFileTransport is fairly slow. // @@ -893,6 +920,7 @@ class TransportTestGen { TEST_RW(CoupledFileTransports, 1024*2, 1, 1, rand4k, rand4k); TEST_BLOCKING_BEHAVIOR(CoupledFileTransports); +#endif // Add some tests that access TBufferedTransport and TFramedTransport // via TTransport pointers and TBufferBase pointers. @@ -928,7 +956,7 @@ class TransportTestGen { maxOutstanding << ")"; boost::unit_test::callback0<> test_func = - std::tr1::bind(test_rw, totalSize, + apache::thrift::stdcxx::bind(test_rw, totalSize, wSizeGen, rSizeGen, wChunkSizeGen, rChunkSizeGen, maxOutstanding); boost::unit_test::test_case* tc = @@ -942,37 +970,37 @@ class TransportTestGen { char name[1024]; boost::unit_test::test_case* tc; - snprintf(name, sizeof(name), "%s::test_read_part_available()", + THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available()", transportName); tc = boost::unit_test::make_test_case( test_read_part_available, name); suite_->add(tc, expectedFailures); - snprintf(name, sizeof(name), "%s::test_read_part_available_in_chunks()", + THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available_in_chunks()", transportName); tc = boost::unit_test::make_test_case( test_read_part_available_in_chunks, name); suite_->add(tc, expectedFailures); - snprintf(name, sizeof(name), "%s::test_read_partial_midframe()", + THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_partial_midframe()", transportName); tc = boost::unit_test::make_test_case( test_read_partial_midframe, name); suite_->add(tc, expectedFailures); - snprintf(name, sizeof(name), "%s::test_read_none_available()", + THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_none_available()", transportName); tc = boost::unit_test::make_test_case( test_read_none_available, name); suite_->add(tc, expectedFailures); - snprintf(name, sizeof(name), "%s::test_borrow_part_available()", + THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_part_available()", transportName); tc = boost::unit_test::make_test_case( test_borrow_part_available, name); suite_->add(tc, expectedFailures); - snprintf(name, sizeof(name), "%s::test_borrow_none_available()", + THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_none_available()", transportName); tc = boost::unit_test::make_test_case( test_borrow_none_available, name); @@ -991,103 +1019,43 @@ class TransportTestGen { * General Initialization **************************************************************************/ -void print_usage(FILE* f, const char* argv0) { - fprintf(f, "Usage: %s [boost_options] [options]\n", argv0); - fprintf(f, "Options:\n"); - fprintf(f, " --seed=, -s \n"); - fprintf(f, " --tmp-dir=DIR, -t DIR\n"); - fprintf(f, " --help\n"); -} +struct global_fixture { + boost::shared_ptr alarmThread_; + global_fixture() { + #if _WIN32 + apache::thrift::transport::TWinsockSingleton::create(); + #endif -struct Options { - int seed; - bool haveSeed; - float sizeMultiplier; -}; + apache::thrift::concurrency::PlatformThreadFactory factory; + factory.setDetached(false); -void parse_args(int argc, char* argv[], Options* options) { - bool have_seed = false; - options->sizeMultiplier = 1; - - struct option long_opts[] = { - { "help", false, NULL, 'h' }, - { "seed", true, NULL, 's' }, - { "tmp-dir", true, NULL, 't' }, - { "size-multiplier", true, NULL, 'x' }, - { NULL, 0, NULL, 0 } - }; - - while (true) { - optopt = 1; - int optchar = getopt_long(argc, argv, "hs:t:x:", long_opts, NULL); - if (optchar == -1) { - break; - } - - switch (optchar) { - case 't': - tmp_dir = optarg; - break; - case 's': { - char *endptr; - options->seed = strtol(optarg, &endptr, 0); - if (endptr == optarg || *endptr != '\0') { - fprintf(stderr, "invalid seed value \"%s\": must be an integer\n", - optarg); - exit(1); - } - have_seed = true; - break; - } - case 'h': - print_usage(stdout, argv[0]); - exit(0); - case 'x': { - char *endptr; - options->sizeMultiplier = strtof(optarg, &endptr); - if (endptr == optarg || *endptr != '\0') { - fprintf(stderr, "invalid size multiplier \"%s\": must be a number\n", - optarg); - exit(1); - } - if (options->sizeMultiplier < 0) { - fprintf(stderr, "invalid size multiplier \"%s\": " - "must be non-negative\n", optarg); - exit(1); - } - break; - } - case '?': - exit(1); - default: - // Only happens if someone adds another option to the optarg string, - // but doesn't update the switch statement to handle it. - fprintf(stderr, "unknown option \"-%c\"\n", optchar); - exit(1); + alarmThread_ = factory.newThread( + apache::thrift::concurrency::FunctionRunner::create(alarm_handler_wrapper)); + alarmThread_->start(); + } + ~global_fixture() { + { + apache::thrift::concurrency::Synchronized s(g_alarm_monitor); + g_teardown = true; + g_alarm_monitor.notify(); } + alarmThread_->join(); } +}; - if (!have_seed) { - // choose a seed now if the user didn't specify one - struct timeval tv; - struct timezone tz; - gettimeofday(&tv, &tz); - options->seed = tv.tv_sec ^ tv.tv_usec; - } -} +BOOST_GLOBAL_FIXTURE(global_fixture) boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { - // Parse arguments - Options options; - parse_args(argc, argv, &options); + struct timeval tv; + THRIFT_GETTIMEOFDAY(&tv, NULL); + int seed = tv.tv_sec ^ tv.tv_usec; - initrand(options.seed); + initrand(seed); boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite(); suite->p_name.value = "TransportTest"; - TransportTestGen transport_test_generator(suite, options.sizeMultiplier); + TransportTestGen transport_test_generator(suite, 1); transport_test_generator.generate(); - return NULL; } diff --git a/lib/cpp/test/ZlibTest.cpp b/lib/cpp/test/ZlibTest.cpp index 4d7966ee..1e8b6467 100644 --- a/lib/cpp/test/ZlibTest.cpp +++ b/lib/cpp/test/ZlibTest.cpp @@ -26,11 +26,10 @@ #include #include -#include #include #include #include -#include +#include #include #include @@ -40,7 +39,6 @@ #include using namespace std; -using namespace boost; using namespace apache::thrift::transport; boost::mt19937 rng; @@ -69,7 +67,7 @@ class ConstantSizeGenerator : public SizeGenerator { class LogNormalSizeGenerator : public SizeGenerator { public: LogNormalSizeGenerator(double mean, double std_dev) : - gen_(rng, lognormal_distribution(mean, std_dev)) {} + gen_(rng, boost::lognormal_distribution(mean, std_dev)) {} virtual unsigned int getSize() { // Loop until we get a size of 1 or more @@ -82,7 +80,7 @@ class LogNormalSizeGenerator : public SizeGenerator { } private: - variate_generator< mt19937, lognormal_distribution > gen_; + boost::variate_generator< boost::mt19937, boost::lognormal_distribution > gen_; }; uint8_t* gen_uniform_buffer(uint32_t buf_len, uint8_t c) { @@ -169,7 +167,7 @@ void test_separate_checksum(const uint8_t* buf, uint32_t buf_len) { membuf->appendBufferToString(tmp_buf); zlib_trans.reset(new TZlibTransport(membuf, TZlibTransport::DEFAULT_URBUF_SIZE, - tmp_buf.length()-1)); + static_cast(tmp_buf.length()-1))); boost::shared_array mirror(new uint8_t[buf_len]); uint32_t got = zlib_trans->readAll(mirror.get(), buf_len); @@ -190,7 +188,7 @@ void test_incomplete_checksum(const uint8_t* buf, uint32_t buf_len) { tmp_buf.erase(tmp_buf.length() - 1); membuf->resetBuffer(const_cast( reinterpret_cast(tmp_buf.data())), - tmp_buf.length()); + static_cast(tmp_buf.length())); boost::shared_array mirror(new uint8_t[buf_len]); uint32_t got = zlib_trans->readAll(mirror.get(), buf_len); @@ -264,11 +262,11 @@ void test_invalid_checksum(const uint8_t* buf, uint32_t buf_len) { // (When this occurs, verifyChecksum() throws an exception indicating // that the end of the data hasn't been reached.) I haven't seen this // error when only modifying checksum bytes. - int index = tmp_buf.size() - 1; + int index = static_cast(tmp_buf.size() - 1); tmp_buf[index]++; membuf->resetBuffer(const_cast( reinterpret_cast(tmp_buf.data())), - tmp_buf.length()); + static_cast(tmp_buf.length())); boost::shared_array mirror(new uint8_t[buf_len]); try { @@ -337,12 +335,12 @@ void test_no_write() { ::std::ostringstream name_ss; \ name_ss << name << "-" << BOOST_STRINGIZE(function); \ ::boost::unit_test::test_case* tc = ::boost::unit_test::make_test_case( \ - ::std::tr1::bind(function, ## __VA_ARGS__), \ + ::apache::thrift::stdcxx::bind(function, ## __VA_ARGS__), \ name_ss.str()); \ (suite)->add(tc); \ } while (0) -void add_tests(unit_test::test_suite* suite, +void add_tests(boost::unit_test::test_suite* suite, const uint8_t* buf, uint32_t buf_len, const char* name) { @@ -387,60 +385,12 @@ void print_usage(FILE* f, const char* argv0) { fprintf(f, " --help\n"); } -void parse_args(int argc, char* argv[]) { - uint32_t seed = 0; - bool has_seed = false; - - struct option long_opts[] = { - { "help", false, NULL, 'h' }, - { "seed", true, NULL, 's' }, - { NULL, 0, NULL, 0 } - }; - - while (true) { - optopt = 1; - int optchar = getopt_long(argc, argv, "hs:", long_opts, NULL); - if (optchar == -1) { - break; - } - - switch (optchar) { - case 's': { - char *endptr; - seed = strtol(optarg, &endptr, 0); - if (endptr == optarg || *endptr != '\0') { - fprintf(stderr, "invalid seed value \"%s\": must be a positive " - "integer\n", optarg); - exit(1); - } - has_seed = true; - break; - } - case 'h': - print_usage(stdout, argv[0]); - exit(0); - case '?': - exit(1); - default: - // Only happens if someone adds another option to the optarg string, - // but doesn't update the switch statement to handle it. - fprintf(stderr, "unknown option \"-%c\"\n", optchar); - exit(1); - } - } - - if (!has_seed) { - seed = time(NULL); - } - +boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { + uint32_t seed = static_cast(time(NULL)); printf("seed: %" PRIu32 "\n", seed); rng.seed(seed); -} - -unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { - parse_args(argc, argv); - unit_test::test_suite* suite = + boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite(); suite->p_name.value = "ZlibTest"; diff --git a/test/cpp/src/StressTest.cpp b/test/cpp/src/StressTest.cpp index 7da3db06..dfe83507 100644 --- a/test/cpp/src/StressTest.cpp +++ b/test/cpp/src/StressTest.cpp @@ -39,9 +39,11 @@ #include #include #include +#if _WIN32 + #include +#endif using namespace std; -using namespace boost; using namespace apache::thrift; using namespace apache::thrift::protocol; @@ -169,6 +171,7 @@ public: int8_t arg = 1; int8_t result; result =_client->echoByte(arg); + (void)result; assert(result == arg); } } @@ -178,6 +181,7 @@ public: int32_t arg = 1; int32_t result; result =_client->echoI32(arg); + (void)result; assert(result == arg); } } @@ -187,6 +191,7 @@ public: int64_t arg = 1; int64_t result; result =_client->echoI64(arg); + (void)result; assert(result == arg); } } @@ -212,8 +217,31 @@ public: Monitor _sleep; }; +class TStartObserver : public apache::thrift::server::TServerEventHandler +{ +public: + TStartObserver() : awake_(false) {} + virtual void preServe() + { + apache::thrift::concurrency::Synchronized s(m_); + awake_ = true; + m_.notifyAll(); + } + void waitForService() + { + apache::thrift::concurrency::Synchronized s(m_); + while(!awake_) + m_.waitForever(); + } + private: + apache::thrift::concurrency::Monitor m_; + bool awake_; +}; int main(int argc, char **argv) { +#if _WIN32 + transport::TWinsockSingleton::create(); +#endif int port = 9091; string serverType = "thread-pool"; @@ -323,7 +351,7 @@ int main(int argc, char **argv) { } catch(std::exception& e) { cerr << e.what() << endl; - cerr << usage; + cerr << usage.str(); } boost::shared_ptr threadFactory = boost::shared_ptr(new PlatformThreadFactory()); @@ -376,15 +404,15 @@ int main(int argc, char **argv) { boost::shared_ptr(new TPipedTransportFactory(fileTransport)); } - boost::shared_ptr serverThread; + boost::shared_ptr server; if (serverType == "simple") { - serverThread = threadFactory->newThread(boost::shared_ptr(new TSimpleServer(serviceProcessor, serverSocket, transportFactory, protocolFactory))); + server.reset(new TSimpleServer(serviceProcessor, serverSocket, transportFactory, protocolFactory)); } else if (serverType == "threaded") { - serverThread = threadFactory->newThread(boost::shared_ptr(new TThreadedServer(serviceProcessor, serverSocket, transportFactory, protocolFactory))); + server.reset(new TThreadedServer(serviceProcessor, serverSocket, transportFactory, protocolFactory)); } else if (serverType == "thread-pool") { @@ -392,15 +420,19 @@ int main(int argc, char **argv) { threadManager->threadFactory(threadFactory); threadManager->start(); - serverThread = threadFactory->newThread(boost::shared_ptr(new TThreadPoolServer(serviceProcessor, serverSocket, transportFactory, protocolFactory, threadManager))); + server.reset(new TThreadPoolServer(serviceProcessor, serverSocket, transportFactory, protocolFactory, threadManager)); } + boost::shared_ptr observer(new TStartObserver); + server->setServerEventHandler(observer); + boost::shared_ptr serverThread = threadFactory->newThread(server); + cerr << "Starting the server on port " << port << endl; serverThread->start(); + observer->waitForService(); // If we aren't running clients, just wait forever for external clients - if (clientCount == 0) { serverThread->join(); } @@ -463,7 +495,7 @@ int main(int argc, char **argv) { for (set >::iterator ix = clientThreads.begin(); ix != clientThreads.end(); ix++) { - boost::shared_ptr client = dynamic_pointer_cast((*ix)->runnable()); + boost::shared_ptr client = boost::dynamic_pointer_cast((*ix)->runnable()); int64_t delta = client->_endTime - client->_startTime; diff --git a/test/cpp/src/StressTestNonBlocking.cpp b/test/cpp/src/StressTestNonBlocking.cpp index c230c842..20320c7d 100644 --- a/test/cpp/src/StressTestNonBlocking.cpp +++ b/test/cpp/src/StressTestNonBlocking.cpp @@ -35,7 +35,6 @@ #include "Service.h" -#include #include #include @@ -43,9 +42,11 @@ #include #include #include +#if _WIN32 + #include +#endif using namespace std; -using namespace boost; using namespace apache::thrift; using namespace apache::thrift::protocol; @@ -84,7 +85,7 @@ class Server : public ServiceIf { void echoVoid() { count("echoVoid"); // Sleep to simulate work - usleep(5000); + THRIFT_SLEEP_USEC(1); return; } @@ -175,6 +176,7 @@ public: int8_t arg = 1; int8_t result; result =_client->echoByte(arg); + (void)result; assert(result == arg); } } @@ -184,6 +186,7 @@ public: int32_t arg = 1; int32_t result; result =_client->echoI32(arg); + (void)result; assert(result == arg); } } @@ -193,6 +196,7 @@ public: int64_t arg = 1; int64_t result; result =_client->echoI64(arg); + (void)result; assert(result == arg); } } @@ -220,13 +224,16 @@ public: int main(int argc, char **argv) { +#if _WIN32 + transport::TWinsockSingleton::create(); +#endif int port = 9091; string serverType = "simple"; string protocolType = "binary"; - size_t workerCount = 4; - size_t clientCount = 20; - size_t loopCount = 50000; + uint32_t workerCount = 4; + uint32_t clientCount = 20; + uint32_t loopCount = 1000; TType loopType = T_VOID; string callName = "echoVoid"; bool runServer = true; @@ -318,7 +325,7 @@ int main(int argc, char **argv) { } catch(std::exception& e) { cerr << e.what() << endl; - cerr << usage; + cerr << usage.str(); } boost::shared_ptr threadFactory = boost::shared_ptr(new PlatformThreadFactory()); @@ -397,7 +404,7 @@ int main(int argc, char **argv) { serverThread2->join(); } } - sleep(1); + THRIFT_SLEEP_SEC(1); if (clientCount > 0) { @@ -414,7 +421,7 @@ int main(int argc, char **argv) { else if (callName == "echoString") { loopType = T_STRING;} else {throw invalid_argument("Unknown service call "+callName);} - for (size_t ix = 0; ix < clientCount; ix++) { + for (uint32_t ix = 0; ix < clientCount; ix++) { boost::shared_ptr socket(new TSocket("127.0.0.1", port + (ix % 2))); boost::shared_ptr framedSocket(new TFramedTransport(socket)); @@ -456,7 +463,7 @@ int main(int argc, char **argv) { for (set >::iterator ix = clientThreads.begin(); ix != clientThreads.end(); ix++) { - boost::shared_ptr client = dynamic_pointer_cast((*ix)->runnable()); + boost::shared_ptr client = boost::dynamic_pointer_cast((*ix)->runnable()); int64_t delta = client->_endTime - client->_startTime; diff --git a/test/cpp/src/TestClient.cpp b/test/cpp/src/TestClient.cpp index fbf04f0b..cd78505b 100644 --- a/test/cpp/src/TestClient.cpp +++ b/test/cpp/src/TestClient.cpp @@ -21,8 +21,6 @@ #include #include -#include -#include #include #include #include @@ -34,11 +32,13 @@ #include #include -#include +#include +#if _WIN32 + #include +#endif #include "ThriftTest.h" -using namespace boost; using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; @@ -54,7 +54,7 @@ uint64_t now() int64_t ret; struct timeval tv; - gettimeofday(&tv, NULL); + THRIFT_GETTIMEOFDAY(&tv, NULL); ret = tv.tv_sec; ret = ret*1000*1000 + tv.tv_usec; return ret; @@ -69,7 +69,7 @@ static void testString_clientReturn(const char* host, int port, event_base *base client->recv_testString(s); cout << "testString: " << s << endl; } catch (TException& exn) { - cout << "Error: " << exn.what() << endl; + cout << "Error: " << exn.what() << endl; } event_base_loopbreak(base); // end test @@ -86,11 +86,14 @@ static void testVoid_clientReturn(const char* host, int port, event_base *base, client = new ThriftTestCobClient(channel, protocolFactory); client->testString(tr1::bind(testString_clientReturn, host, port, base, protocolFactory, std::tr1::placeholders::_1), "Test"); } catch (TException& exn) { - cout << "Error: " << exn.what() << endl; + cout << "Error: " << exn.what() << endl; } } int main(int argc, char** argv) { +#if _WIN32 + transport::TWinsockSingleton::create(); +#endif string host = "localhost"; int port = 9090; int numTests = 1; @@ -99,28 +102,28 @@ int main(int argc, char** argv) { string protocol_type = "binary"; string domain_socket = ""; - program_options::options_description desc("Allowed options"); + boost::program_options::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") - ("host", program_options::value(&host)->default_value(host), "Host to connect") - ("port", program_options::value(&port)->default_value(port), "Port number to connect") - ("domain-socket", program_options::value(&domain_socket)->default_value(domain_socket), "Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port") - ("transport", program_options::value(&transport_type)->default_value(transport_type), "Transport: buffered, framed, http, evhttp") - ("protocol", program_options::value(&protocol_type)->default_value(protocol_type), "Protocol: binary, json") + ("host", boost::program_options::value(&host)->default_value(host), "Host to connect") + ("port", boost::program_options::value(&port)->default_value(port), "Port number to connect") + ("domain-socket", boost::program_options::value(&domain_socket)->default_value(domain_socket), "Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port") + ("transport", boost::program_options::value(&transport_type)->default_value(transport_type), "Transport: buffered, framed, http, evhttp") + ("protocol", boost::program_options::value(&protocol_type)->default_value(protocol_type), "Protocol: binary, json") ("ssl", "Encrypted Transport using SSL") - ("testloops,n", program_options::value(&numTests)->default_value(numTests), "Number of Tests") + ("testloops,n", boost::program_options::value(&numTests)->default_value(numTests), "Number of Tests") ; - program_options::variables_map vm; - program_options::store(program_options::parse_command_line(argc, argv, desc), vm); - program_options::notify(vm); + boost::program_options::variables_map vm; + boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); + boost::program_options::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } - try { + try { if (!protocol_type.empty()) { if (protocol_type == "binary") { } else if (protocol_type == "json") { @@ -210,7 +213,7 @@ int main(int argc, char** argv) { boost::shared_ptr channel(new TEvhttpClientChannel(host.c_str(), "/", host.c_str(), port, base)); ThriftTestCobClient* client = new ThriftTestCobClient(channel, protocolFactory.get()); client->testVoid(tr1::bind(testVoid_clientReturn, host.c_str(), port, base, protocolFactory.get(), std::tr1::placeholders::_1)); - + event_base_loop(base, 0); return 0; } @@ -574,7 +577,7 @@ int main(int argc, char** argv) { printf(" void\nFAILURE\n"); failCount++; - } catch(TException& e) { + } catch(const TException&) { printf(" Caught TException\n"); } @@ -622,9 +625,9 @@ int main(int argc, char** argv) { /* test oneway void */ { - printf("testClient.testOneway(3) =>"); + printf("testClient.testOneway(1) =>"); uint64_t startOneway = now(); - testClient.testOneway(3); + testClient.testOneway(1); uint64_t elapsed = now() - startOneway; if (elapsed > 200 * 1000) { // 0.2 seconds printf(" FAILURE - took %.2f ms\n", (double)elapsed/1000.0); diff --git a/test/cpp/src/TestServer.cpp b/test/cpp/src/TestServer.cpp index c99fbac0..adb8fd1f 100644 --- a/test/cpp/src/TestServer.cpp +++ b/test/cpp/src/TestServer.cpp @@ -46,9 +46,11 @@ #include #include +#if _WIN32 + #include +#endif using namespace std; -using namespace boost; using namespace apache::thrift; using namespace apache::thrift::concurrency; @@ -266,7 +268,7 @@ class TestHandler : public ThriftTestIf { (void) arg3; (void) arg4; (void) arg5; - + printf("testMulti()\n"); hello.string_thing = "Hello2"; @@ -314,9 +316,9 @@ class TestHandler : public ThriftTestIf { } } - void testOneway(int sleepFor) { + void testOneway(const int32_t sleepFor) { printf("testOneway(%d): Sleeping...\n", sleepFor); - sleep(sleepFor); + THRIFT_SLEEP_SEC(sleepFor); printf("testOneway(%d): done sleeping!\n", sleepFor); } }; @@ -447,7 +449,7 @@ public: } virtual void testInsanity(std::tr1::function > const& _return)> cob, const Insanity& argument) { - std::map > res; + std::map > res; _delegate->testInsanity(res, argument); cob(res); } @@ -490,6 +492,9 @@ protected: int main(int argc, char **argv) { +#if _WIN32 + transport::TWinsockSingleton::create(); +#endif int port = 9090; bool ssl = false; string transport_type = "buffered"; @@ -498,34 +503,34 @@ int main(int argc, char **argv) { string domain_socket = ""; size_t workers = 4; - - program_options::options_description desc("Allowed options"); + + boost::program_options::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") - ("port", program_options::value(&port)->default_value(port), "Port number to listen") - ("domain-socket", program_options::value(&domain_socket)->default_value(domain_socket), + ("port", boost::program_options::value(&port)->default_value(port), "Port number to listen") + ("domain-socket", boost::program_options::value(&domain_socket)->default_value(domain_socket), "Unix Domain Socket (e.g. /tmp/ThriftTest.thrift)") - ("server-type", program_options::value(&server_type)->default_value(server_type), + ("server-type", boost::program_options::value(&server_type)->default_value(server_type), "type of server, \"simple\", \"thread-pool\", \"threaded\", or \"nonblocking\"") - ("transport", program_options::value(&transport_type)->default_value(transport_type), + ("transport", boost::program_options::value(&transport_type)->default_value(transport_type), "transport: buffered, framed, http") - ("protocol", program_options::value(&protocol_type)->default_value(protocol_type), + ("protocol", boost::program_options::value(&protocol_type)->default_value(protocol_type), "protocol: binary, json") ("ssl", "Encrypted Transport using SSL") ("processor-events", "processor-events") - ("workers,n", program_options::value(&workers)->default_value(workers), + ("workers,n", boost::program_options::value(&workers)->default_value(workers), "Number of thread pools workers. Only valid for thread-pool server type") ; - program_options::variables_map vm; - program_options::store(program_options::parse_command_line(argc, argv, desc), vm); - program_options::notify(vm); + boost::program_options::variables_map vm; + boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); + boost::program_options::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } - + try { if (!server_type.empty()) { if (server_type == "simple") { @@ -536,7 +541,7 @@ int main(int argc, char **argv) { throw invalid_argument("Unknown server type "+server_type); } } - + if (!protocol_type.empty()) { if (protocol_type == "binary") { } else if (protocol_type == "json") { @@ -562,7 +567,6 @@ int main(int argc, char **argv) { if (vm.count("ssl")) { ssl = true; - signal(SIGPIPE, SIG_IGN); } // Dispatcher @@ -578,12 +582,12 @@ int main(int argc, char **argv) { // Processor boost::shared_ptr testHandler(new TestHandler()); boost::shared_ptr testProcessor(new ThriftTestProcessor(testHandler)); - + if (vm.count("processor-events")) { testProcessor->setEventHandler(boost::shared_ptr( new TestProcessorEventHandler())); } - + // Transport boost::shared_ptr sslSocketFactory; boost::shared_ptr serverSocket; @@ -607,15 +611,15 @@ int main(int argc, char **argv) { // Factory boost::shared_ptr transportFactory; - + if (transport_type == "http" && server_type != "nonblocking") { - boost::shared_ptr httpTransportFactory(new THttpServerTransportFactory()); + boost::shared_ptr httpTransportFactory(new THttpServerTransportFactory()); transportFactory = httpTransportFactory; } else if (transport_type == "framed") { - boost::shared_ptr framedTransportFactory(new TFramedTransportFactory()); + boost::shared_ptr framedTransportFactory(new TFramedTransportFactory()); transportFactory = framedTransportFactory; } else { - boost::shared_ptr bufferedTransportFactory(new TBufferedTransportFactory()); + boost::shared_ptr bufferedTransportFactory(new TBufferedTransportFactory()); transportFactory = bufferedTransportFactory; } @@ -628,14 +632,13 @@ int main(int argc, char **argv) { cout << endl; // Server + boost::shared_ptr server; + if (server_type == "simple") { - TSimpleServer simpleServer(testProcessor, + server.reset(new TSimpleServer(testProcessor, serverSocket, transportFactory, - protocolFactory); - - simpleServer.serve(); - + protocolFactory)); } else if (server_type == "thread-pool") { boost::shared_ptr threadManager = @@ -648,37 +651,49 @@ int main(int argc, char **argv) { threadManager->start(); - TThreadPoolServer threadPoolServer(testProcessor, + server.reset(new TThreadPoolServer(testProcessor, serverSocket, transportFactory, protocolFactory, - threadManager); - - threadPoolServer.serve(); - + threadManager)); } else if (server_type == "threaded") { - TThreadedServer threadedServer(testProcessor, + server.reset(new TThreadedServer(testProcessor, serverSocket, transportFactory, - protocolFactory); - - threadedServer.serve(); - + protocolFactory)); } else if (server_type == "nonblocking") { if(transport_type == "http") { boost::shared_ptr testHandlerAsync(new TestHandlerAsync(testHandler)); boost::shared_ptr testProcessorAsync(new ThriftTestAsyncProcessor(testHandlerAsync)); boost::shared_ptr testBufferProcessor(new TAsyncProtocolProcessor(testProcessorAsync, protocolFactory)); - + + // not loading nonblockingServer into "server" because + // TEvhttpServer doesn't inherit from TServer, and doesn't + // provide a stop method. TEvhttpServer nonblockingServer(testBufferProcessor, port); nonblockingServer.serve(); -} else { - TNonblockingServer nonblockingServer(testProcessor, port); - nonblockingServer.serve(); + } else { + server.reset(new TNonblockingServer(testProcessor, port)); } } + if(server.get() != NULL) + { + apache::thrift::concurrency::PlatformThreadFactory factory; + factory.setDetached(false); + boost::shared_ptr serverThreadRunner(server); + boost::shared_ptr thread = factory.newThread(serverThreadRunner); + thread->start(); + + cout<<"Press enter to stop the server."<stop(); + thread->join(); + server.reset(); + } + cout << "done." << endl; return 0; } diff --git a/test/threads/ThreadsClient.cpp b/test/threads/ThreadsClient.cpp index 70b08ad8..9306a3f2 100644 --- a/test/threads/ThreadsClient.cpp +++ b/test/threads/ThreadsClient.cpp @@ -28,6 +28,9 @@ #include #include #include +#if _WIN32 + #include +#endif using boost::shared_ptr; using namespace apache::thrift; @@ -37,6 +40,9 @@ using namespace apache::thrift::server; using namespace apache::thrift::concurrency; int main(int argc, char **argv) { +#if _WIN32 + transport::TWinsockSingleton::create(); +#endif int port = 9090; std::string host = "localhost"; diff --git a/test/threads/ThreadsServer.cpp b/test/threads/ThreadsServer.cpp index 9c1a7d97..a267c3b9 100644 --- a/test/threads/ThreadsServer.cpp +++ b/test/threads/ThreadsServer.cpp @@ -29,6 +29,9 @@ #include #include #include +#if _WIN32 + #include +#endif using boost::shared_ptr; using namespace apache::thrift; @@ -85,11 +88,12 @@ class ThreadsTestHandler : virtual public ThreadsTestIf { protected: void go2sleep(int thread, int seconds) { Monitor m; + Synchronized s(m); for (int i = 0; i < seconds; ++i) { fprintf(stderr, "Thread %d: sleep %d\n", thread, i); try { m.wait(1000); - } catch(TimedOutException& e) { + } catch(const TimedOutException&) { } } fprintf(stderr, "THREAD %d DONE\n", thread); @@ -101,6 +105,9 @@ private: }; int main(int argc, char **argv) { +#if _WIN32 + transport::TWinsockSingleton::create(); +#endif int port = 9090; shared_ptr handler(new ThreadsTestHandler()); shared_ptr processor(new ThreadsTestProcessor(handler)); -- 2.17.1