xref: /aosp_15_r20/external/grpc-grpc/test/cpp/common/time_jump_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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 
19 #include <spawn.h>
20 
21 #include <sstream>
22 #include <string>
23 #include <thread>
24 #include <vector>
25 
26 #include <gtest/gtest.h>
27 
28 #include "absl/time/time.h"
29 
30 #include <grpc/grpc.h>
31 #include <grpc/support/log.h>
32 
33 #include "src/core/lib/gprpp/crash.h"
34 #include "src/core/lib/gprpp/sync.h"
35 #include "src/core/lib/iomgr/closure.h"
36 #include "src/core/lib/iomgr/error.h"
37 #include "src/core/lib/iomgr/exec_ctx.h"
38 #include "src/core/lib/iomgr/timer.h"
39 #include "src/core/lib/iomgr/timer_manager.h"
40 #include "test/core/util/test_config.h"
41 
42 extern char** environ;
43 
44 #ifdef GPR_ANDROID
45 // Android doesn't have posix_spawn. Use std::system instead
run_cmd(const char * cmd)46 void run_cmd(const char* cmd) { std::system(cmd); }
47 #else
run_cmd(const char * cmd)48 void run_cmd(const char* cmd) {
49   pid_t pid;
50   const char* argv[] = {const_cast<const char*>("sh"),
51                         const_cast<const char*>("-c"), cmd, nullptr};
52   int status;
53 
54   status = posix_spawn(&pid, const_cast<const char*>("/bin/sh"), nullptr,
55                        nullptr, const_cast<char**>(argv), environ);
56   if (status == 0) {
57     if (waitpid(pid, &status, 0) == -1) {
58       perror("waitpid");
59     }
60   }
61 }
62 #endif
63 
64 class TimeJumpTest : public ::testing::TestWithParam<std::string> {
65  protected:
SetUp()66   void SetUp() override {
67     // Skip test if slowdown factor > 1
68     if (grpc_test_slowdown_factor() != 1) {
69       GTEST_SKIP();
70     } else {
71       grpc_init();
72     }
73   }
TearDown()74   void TearDown() override {
75     // Skip test if slowdown factor > 1
76     if (grpc_test_slowdown_factor() == 1) {
77       run_cmd("sudo sntp -sS pool.ntp.org");
78       grpc_shutdown();
79     }
80   }
81 
82   const int kWaitTimeMs = 1500;
83 };
84 
CreateTestScenarios()85 std::vector<std::string> CreateTestScenarios() {
86   return {"-1M", "+1M", "-1H", "+1H", "-1d", "+1d", "-1y", "+1y"};
87 }
88 INSTANTIATE_TEST_SUITE_P(TimeJump, TimeJumpTest,
89                          ::testing::ValuesIn(CreateTestScenarios()));
90 
TEST_P(TimeJumpTest,TimerRunning)91 TEST_P(TimeJumpTest, TimerRunning) {
92   grpc_core::ExecCtx exec_ctx;
93   grpc_timer timer;
94   grpc_timer_init(&timer,
95                   grpc_core::Timestamp::Now() + grpc_core::Duration::Seconds(3),
96                   GRPC_CLOSURE_CREATE(
97                       [](void*, grpc_error_handle error) {
98                         GPR_ASSERT(error == absl::CancelledError());
99                       },
100                       nullptr, grpc_schedule_on_exec_ctx));
101   gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(100));
102   std::ostringstream cmd;
103   cmd << "sudo date `date -v" << GetParam() << " \"+%m%d%H%M%y\"`";
104   run_cmd(cmd.str().c_str());
105   gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(kWaitTimeMs));
106   // We expect 1 wakeup/sec when there are not timer expiries
107   int64_t wakeups = grpc_timer_manager_get_wakeups_testonly();
108   gpr_log(GPR_DEBUG, "wakeups: %" PRId64 "", wakeups);
109   GPR_ASSERT(wakeups <= 3);
110   grpc_timer_cancel(&timer);
111 }
112 
TEST_P(TimeJumpTest,TimedWait)113 TEST_P(TimeJumpTest, TimedWait) {
114   grpc_core::CondVar cond;
115   grpc_core::Mutex mu;
116   {
117     grpc_core::MutexLock lock(&mu);
118     std::thread thd = std::thread([]() {
119       gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(100));
120       std::ostringstream cmd;
121       cmd << "sudo date `date -v" << GetParam() << " \"+%m%d%H%M%y\"`";
122       run_cmd(cmd.str().c_str());
123     });
124     gpr_timespec before = gpr_now(GPR_CLOCK_MONOTONIC);
125     bool timedout = cond.WaitWithTimeout(&mu, absl::Milliseconds(kWaitTimeMs));
126     gpr_timespec after = gpr_now(GPR_CLOCK_MONOTONIC);
127     int32_t elapsed_ms = gpr_time_to_millis(gpr_time_sub(after, before));
128     gpr_log(GPR_DEBUG, "After wait, timedout = %d elapsed_ms = %d", timedout,
129             elapsed_ms);
130     GPR_ASSERT(1 == timedout);
131     GPR_ASSERT(1 ==
132                gpr_time_similar(gpr_time_sub(after, before),
133                                 gpr_time_from_millis(kWaitTimeMs, GPR_TIMESPAN),
134                                 gpr_time_from_millis(50, GPR_TIMESPAN)));
135 
136     thd.join();
137   }
138   // We expect 1 wakeup/sec when there are not timer expiries
139   int64_t wakeups = grpc_timer_manager_get_wakeups_testonly();
140   gpr_log(GPR_DEBUG, "wakeups: %" PRId64 "", wakeups);
141   GPR_ASSERT(wakeups <= 3);
142 }
143 
main(int argc,char ** argv)144 int main(int argc, char** argv) {
145   grpc::testing::TestEnvironment env(&argc, argv);
146   ::testing::InitGoogleTest(&argc, argv);
147   return RUN_ALL_TESTS();
148 }
149