time_change_test.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <sys/time.h>
  19. #include <thread>
  20. #include <gtest/gtest.h>
  21. #include "absl/memory/memory.h"
  22. #include <grpc/grpc.h>
  23. #include <grpc/support/log.h>
  24. #include <grpc/support/time.h>
  25. #include <grpcpp/channel.h>
  26. #include <grpcpp/client_context.h>
  27. #include <grpcpp/create_channel.h>
  28. #include <grpcpp/server.h>
  29. #include <grpcpp/server_builder.h>
  30. #include <grpcpp/server_context.h>
  31. #include "src/core/lib/iomgr/timer.h"
  32. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  33. #include "test/core/util/port.h"
  34. #include "test/core/util/test_config.h"
  35. #include "test/cpp/end2end/test_service_impl.h"
  36. #include "test/cpp/util/subprocess.h"
  37. using grpc::testing::EchoRequest;
  38. using grpc::testing::EchoResponse;
  39. static std::string g_root;
  40. static gpr_mu g_mu;
  41. extern gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type);
  42. gpr_timespec (*gpr_now_impl_orig)(gpr_clock_type clock_type) = gpr_now_impl;
  43. static int g_time_shift_sec = 0;
  44. static int g_time_shift_nsec = 0;
  45. static gpr_timespec now_impl(gpr_clock_type clock) {
  46. auto ts = gpr_now_impl_orig(clock);
  47. // We only manipulate the realtime clock to simulate changes in wall-clock
  48. // time
  49. if (clock != GPR_CLOCK_REALTIME) {
  50. return ts;
  51. }
  52. GPR_ASSERT(ts.tv_nsec >= 0);
  53. GPR_ASSERT(ts.tv_nsec < GPR_NS_PER_SEC);
  54. gpr_mu_lock(&g_mu);
  55. ts.tv_sec += g_time_shift_sec;
  56. ts.tv_nsec += g_time_shift_nsec;
  57. gpr_mu_unlock(&g_mu);
  58. if (ts.tv_nsec >= GPR_NS_PER_SEC) {
  59. ts.tv_nsec -= GPR_NS_PER_SEC;
  60. ++ts.tv_sec;
  61. } else if (ts.tv_nsec < 0) {
  62. --ts.tv_sec;
  63. ts.tv_nsec = GPR_NS_PER_SEC + ts.tv_nsec;
  64. }
  65. return ts;
  66. }
  67. // offset the value returned by gpr_now(GPR_CLOCK_REALTIME) by msecs
  68. // milliseconds
  69. static void set_now_offset(int msecs) {
  70. gpr_mu_lock(&g_mu);
  71. g_time_shift_sec = msecs / 1000;
  72. g_time_shift_nsec = (msecs % 1000) * 1e6;
  73. gpr_mu_unlock(&g_mu);
  74. }
  75. // restore the original implementation of gpr_now()
  76. static void reset_now_offset() {
  77. gpr_mu_lock(&g_mu);
  78. g_time_shift_sec = 0;
  79. g_time_shift_nsec = 0;
  80. gpr_mu_unlock(&g_mu);
  81. }
  82. namespace grpc {
  83. namespace testing {
  84. namespace {
  85. // gpr_now() is called with invalid clock_type
  86. TEST(TimespecTest, GprNowInvalidClockType) {
  87. // initialize to some junk value
  88. gpr_clock_type invalid_clock_type = static_cast<gpr_clock_type>(32641);
  89. EXPECT_DEATH(gpr_now(invalid_clock_type), ".*");
  90. }
  91. // Add timespan with negative nanoseconds
  92. TEST(TimespecTest, GprTimeAddNegativeNs) {
  93. gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
  94. gpr_timespec bad_ts = {1, -1000, GPR_TIMESPAN};
  95. EXPECT_DEATH(gpr_time_add(now, bad_ts), ".*");
  96. }
  97. // Subtract timespan with negative nanoseconds
  98. TEST(TimespecTest, GprTimeSubNegativeNs) {
  99. // Nanoseconds must always be positive. Negative timestamps are represented by
  100. // (negative seconds, positive nanoseconds)
  101. gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
  102. gpr_timespec bad_ts = {1, -1000, GPR_TIMESPAN};
  103. EXPECT_DEATH(gpr_time_sub(now, bad_ts), ".*");
  104. }
  105. // Add negative milliseconds to gpr_timespec
  106. TEST(TimespecTest, GrpcNegativeMillisToTimespec) {
  107. // -1500 milliseconds converts to timespec (-2 secs, 5 * 10^8 nsec)
  108. gpr_timespec ts =
  109. grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(-1500)
  110. .as_timespec(GPR_CLOCK_MONOTONIC);
  111. GPR_ASSERT(ts.tv_sec = -2);
  112. GPR_ASSERT(ts.tv_nsec = 5e8);
  113. GPR_ASSERT(ts.clock_type == GPR_CLOCK_MONOTONIC);
  114. }
  115. class TimeChangeTest : public ::testing::Test {
  116. protected:
  117. TimeChangeTest() {}
  118. static void SetUpTestCase() {
  119. auto port = grpc_pick_unused_port_or_die();
  120. std::ostringstream addr_stream;
  121. addr_stream << "localhost:" << port;
  122. server_address_ = addr_stream.str();
  123. server_ = absl::make_unique<SubProcess>(std::vector<std::string>({
  124. g_root + "/client_crash_test_server",
  125. "--address=" + server_address_,
  126. }));
  127. GPR_ASSERT(server_);
  128. // connect to server and make sure it's reachable.
  129. auto channel =
  130. grpc::CreateChannel(server_address_, InsecureChannelCredentials());
  131. GPR_ASSERT(channel);
  132. EXPECT_TRUE(channel->WaitForConnected(
  133. grpc_timeout_milliseconds_to_deadline(30000)));
  134. }
  135. static void TearDownTestCase() { server_.reset(); }
  136. void SetUp() override {
  137. channel_ =
  138. grpc::CreateChannel(server_address_, InsecureChannelCredentials());
  139. GPR_ASSERT(channel_);
  140. stub_ = grpc::testing::EchoTestService::NewStub(channel_);
  141. }
  142. void TearDown() override { reset_now_offset(); }
  143. std::unique_ptr<grpc::testing::EchoTestService::Stub> CreateStub() {
  144. return grpc::testing::EchoTestService::NewStub(channel_);
  145. }
  146. std::shared_ptr<Channel> GetChannel() { return channel_; }
  147. // time jump offsets in milliseconds
  148. const int TIME_OFFSET1 = 20123;
  149. const int TIME_OFFSET2 = 5678;
  150. private:
  151. static std::string server_address_;
  152. static std::unique_ptr<SubProcess> server_;
  153. std::shared_ptr<Channel> channel_;
  154. std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
  155. };
  156. std::string TimeChangeTest::server_address_;
  157. std::unique_ptr<SubProcess> TimeChangeTest::server_;
  158. // Wall-clock time jumps forward on client before bidi stream is created
  159. TEST_F(TimeChangeTest, TimeJumpForwardBeforeStreamCreated) {
  160. EchoRequest request;
  161. EchoResponse response;
  162. ClientContext context;
  163. context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
  164. context.AddMetadata(kServerResponseStreamsToSend, "1");
  165. auto channel = GetChannel();
  166. GPR_ASSERT(channel);
  167. EXPECT_TRUE(
  168. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
  169. auto stub = CreateStub();
  170. // time jumps forward by TIME_OFFSET1 milliseconds
  171. set_now_offset(TIME_OFFSET1);
  172. auto stream = stub->BidiStream(&context);
  173. request.set_message("Hello");
  174. EXPECT_TRUE(stream->Write(request));
  175. EXPECT_TRUE(stream->WritesDone());
  176. EXPECT_TRUE(stream->Read(&response));
  177. auto status = stream->Finish();
  178. EXPECT_TRUE(status.ok());
  179. }
  180. // Wall-clock time jumps back on client before bidi stream is created
  181. TEST_F(TimeChangeTest, TimeJumpBackBeforeStreamCreated) {
  182. EchoRequest request;
  183. EchoResponse response;
  184. ClientContext context;
  185. context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
  186. context.AddMetadata(kServerResponseStreamsToSend, "1");
  187. auto channel = GetChannel();
  188. GPR_ASSERT(channel);
  189. EXPECT_TRUE(
  190. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
  191. auto stub = CreateStub();
  192. // time jumps back by TIME_OFFSET1 milliseconds
  193. set_now_offset(-TIME_OFFSET1);
  194. auto stream = stub->BidiStream(&context);
  195. request.set_message("Hello");
  196. EXPECT_TRUE(stream->Write(request));
  197. EXPECT_TRUE(stream->WritesDone());
  198. EXPECT_TRUE(stream->Read(&response));
  199. EXPECT_EQ(request.message(), response.message());
  200. auto status = stream->Finish();
  201. EXPECT_TRUE(status.ok());
  202. }
  203. // Wall-clock time jumps forward on client while call is in progress
  204. TEST_F(TimeChangeTest, TimeJumpForwardAfterStreamCreated) {
  205. EchoRequest request;
  206. EchoResponse response;
  207. ClientContext context;
  208. context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
  209. context.AddMetadata(kServerResponseStreamsToSend, "2");
  210. auto channel = GetChannel();
  211. GPR_ASSERT(channel);
  212. EXPECT_TRUE(
  213. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
  214. auto stub = CreateStub();
  215. auto stream = stub->BidiStream(&context);
  216. request.set_message("Hello");
  217. EXPECT_TRUE(stream->Write(request));
  218. EXPECT_TRUE(stream->Read(&response));
  219. // time jumps forward by TIME_OFFSET1 milliseconds.
  220. set_now_offset(TIME_OFFSET1);
  221. request.set_message("World");
  222. EXPECT_TRUE(stream->Write(request));
  223. EXPECT_TRUE(stream->WritesDone());
  224. EXPECT_TRUE(stream->Read(&response));
  225. auto status = stream->Finish();
  226. EXPECT_TRUE(status.ok());
  227. }
  228. // Wall-clock time jumps back on client while call is in progress
  229. TEST_F(TimeChangeTest, TimeJumpBackAfterStreamCreated) {
  230. EchoRequest request;
  231. EchoResponse response;
  232. ClientContext context;
  233. context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
  234. context.AddMetadata(kServerResponseStreamsToSend, "2");
  235. auto channel = GetChannel();
  236. GPR_ASSERT(channel);
  237. EXPECT_TRUE(
  238. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
  239. auto stub = CreateStub();
  240. auto stream = stub->BidiStream(&context);
  241. request.set_message("Hello");
  242. EXPECT_TRUE(stream->Write(request));
  243. EXPECT_TRUE(stream->Read(&response));
  244. // time jumps back TIME_OFFSET1 milliseconds.
  245. set_now_offset(-TIME_OFFSET1);
  246. request.set_message("World");
  247. EXPECT_TRUE(stream->Write(request));
  248. EXPECT_TRUE(stream->WritesDone());
  249. EXPECT_TRUE(stream->Read(&response));
  250. auto status = stream->Finish();
  251. EXPECT_TRUE(status.ok());
  252. }
  253. // Wall-clock time jumps forward and backwards during call
  254. TEST_F(TimeChangeTest, TimeJumpForwardAndBackDuringCall) {
  255. EchoRequest request;
  256. EchoResponse response;
  257. ClientContext context;
  258. context.set_deadline(grpc_timeout_milliseconds_to_deadline(5000));
  259. context.AddMetadata(kServerResponseStreamsToSend, "2");
  260. auto channel = GetChannel();
  261. GPR_ASSERT(channel);
  262. EXPECT_TRUE(
  263. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(5000)));
  264. auto stub = CreateStub();
  265. auto stream = stub->BidiStream(&context);
  266. request.set_message("Hello");
  267. EXPECT_TRUE(stream->Write(request));
  268. // time jumps back by TIME_OFFSET2 milliseconds
  269. set_now_offset(-TIME_OFFSET2);
  270. EXPECT_TRUE(stream->Read(&response));
  271. request.set_message("World");
  272. // time jumps forward by TIME_OFFSET milliseconds
  273. set_now_offset(TIME_OFFSET1);
  274. EXPECT_TRUE(stream->Write(request));
  275. // time jumps back by TIME_OFFSET2 milliseconds
  276. set_now_offset(-TIME_OFFSET2);
  277. EXPECT_TRUE(stream->WritesDone());
  278. // time jumps back by TIME_OFFSET2 milliseconds
  279. set_now_offset(-TIME_OFFSET2);
  280. EXPECT_TRUE(stream->Read(&response));
  281. // time jumps back by TIME_OFFSET2 milliseconds
  282. set_now_offset(-TIME_OFFSET2);
  283. auto status = stream->Finish();
  284. EXPECT_TRUE(status.ok());
  285. }
  286. } // namespace
  287. } // namespace testing
  288. } // namespace grpc
  289. int main(int argc, char** argv) {
  290. std::string me = argv[0];
  291. // get index of last slash in path to test binary
  292. auto lslash = me.rfind('/');
  293. // set g_root = path to directory containing test binary
  294. if (lslash != std::string::npos) {
  295. g_root = me.substr(0, lslash);
  296. } else {
  297. g_root = ".";
  298. }
  299. gpr_mu_init(&g_mu);
  300. gpr_now_impl = now_impl;
  301. grpc::testing::TestEnvironment env(argc, argv);
  302. ::testing::InitGoogleTest(&argc, argv);
  303. auto ret = RUN_ALL_TESTS();
  304. return ret;
  305. }