File: test_router_stacktrace.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (598 lines) | stat: -rw-r--r-- 19,803 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*
  Copyright (c) 2022, 2025, Oracle and/or its affiliates.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 2.0,
  as published by the Free Software Foundation.

  This program is designed to work with certain software (including
  but not limited to OpenSSL) that is licensed under separate terms,
  as designated in a particular file or component or in included license
  documentation.  The authors of MySQL hereby grant you an additional
  permission to link the program and your derivative works with the
  separately licensed software that they have either included with
  the program or referenced in the documentation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <chrono>
#include <thread>

#include <gmock/gmock-matchers.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include "core_dumper.h"
#include "core_finder.h"
#include "my_config.h"  // HAVE_ASAN & HAVE_UBSAN
#include "mysql/harness/filesystem.h"
#include "mysql/harness/signal_handler.h"
#include "mysql/harness/stdx/filesystem.h"
#include "mysqlrouter/mock_server_rest_client.h"
#include "mysqlrouter/rest_client.h"
#include "process_launcher.h"
#include "rest_api_testutils.h"
#include "router_component_test.h"
#include "router_test_helpers.h"
#include "scope_guard.h"
#include "test/temp_directory.h"

namespace {
constexpr const int abrt_status{
#ifdef _WIN32
    0x00000102  // STATUS_TIMEOUT
#else
    SIGABRT
#endif
};

#if !defined(HAVE_ASAN) && !defined(HAVE_UBSAN) && !defined(HAVE_TSAN)

constexpr const int segv_status{
#ifdef _WIN32
    static_cast<int>(0xC0000005)  // STATUS_ACCESS_VIOLATION
#else
    SIGSEGV
#endif
};

#endif

}  // namespace

class RouterStacktraceTest : public RouterComponentTest {};

// TS_1_1
TEST_F(RouterStacktraceTest, help_has_core_file) {
  TempDirectory tmp_dir;

  // --core-file is added automatically by router_spawner()
  auto &r = router_spawner()
                .wait_for_sync_point(ProcessManager::Spawner::SyncPoint::NONE)
                .spawn({"--help"});

  SCOPED_TRACE("// wait for the exit");
  r.native_wait_for_exit();

  // Usage
  EXPECT_THAT(r.get_full_output(), ::testing::HasSubstr("[--core-file"));

  // Options
  EXPECT_THAT(r.get_full_output(), ::testing::HasSubstr("  --core-file"));
}

// TS_1_2
TEST_F(RouterStacktraceTest, bootstrap_with_core_file) {
  auto mock_port = port_pool_.get_next_available();

  // using a non-bootstrap script makes sure the bootstrap fails early, and
  // still checks that --core-file is accepted.
  launch_mysql_server_mock(get_data_dir().str() + "/my_port.js", mock_port,
                           EXIT_SUCCESS, false, 0, 0, get_data_dir().str());

  TempDirectory tmp_dir;
  // --core-file is added automatically by router_spawner()
  auto &r =
      router_spawner()
          .with_core_dump(false)  // avoid the automatic --core-file
          .expected_exit_code(
              ExitStatus{ExitStatus::exited_t{},
                         mysql_harness::SignalHandler::HARNESS_ABORT_EXIT})
          .wait_for_sync_point(ProcessManager::Spawner::SyncPoint::NONE)
          .output_responder([](const std::string &) { return "somepass\n"; })
          .spawn({
              "--bootstrap", "127.0.0.1:" + std::to_string(mock_port),  //
              "--directory", tmp_dir.name(),                            //
              "--core-file",                                            //
              "--report-host=dont.query.dns",                           //
          });

  SCOPED_TRACE("// wait for the exit");
  r.native_wait_for_exit();

  // as the mock-server doesn't run a bootstrap script, the SQL will fail.
  EXPECT_THAT(r.get_full_output(),
              ::testing::HasSubstr("Error executing MySQL query"));
}

// TS_1_2
TEST_F(RouterStacktraceTest, crash_me_bootstrap) {
  auto mock_port = port_pool_.get_next_available();
  auto mock_http_port = port_pool_.get_next_available();

  launch_mysql_server_mock(
      get_data_dir().str() + "/bootstrap_exec_time_2_seconds.js", mock_port,
      EXIT_SUCCESS, true, mock_http_port, 0, get_data_dir().str());

  TempDirectory tmp_dir;
  // --core-file is added automatically by router_spawner()
  auto &r =
      router_spawner()
          .with_core_dump(false)  // avoid the automatic --core-file
          .expected_exit_code(
              ExitStatus{ExitStatus::terminated_t{}, abrt_status})
          .wait_for_sync_point(ProcessManager::Spawner::SyncPoint::NONE)
          .output_responder([](const std::string &) { return "somepass\n"; })
          .spawn({
              "--bootstrap", "127.0.0.1:" + std::to_string(mock_port),  //
              "--directory", tmp_dir.name(),                            //
              "--core-file",                                            //
              "--report-host=dont.query.dns",                           //
          });

  SCOPED_TRACE("// wait until mock-server is blocked for 2 seconds");
  MockServerRestClient client(mock_http_port);
  int blocked{};

  using namespace std::chrono_literals;

  using clock_type = std::chrono::steady_clock;

  auto now = clock_type::now();
  auto end_time = now + 5s;

  do {
    try {
      blocked = client.get_int_global("blocked");
      if (blocked) break;
    } catch (const std::exception &e) {
      std::cerr << e.what() << "\n";
    }

    std::this_thread::sleep_for(100ms);
  } while (clock_type::now() < end_time);

  ASSERT_TRUE(blocked);

  SCOPED_TRACE("// aborting bootstrapping router");
  r.send_shutdown_event(mysql_harness::ProcessLauncher::ShutdownEvent::ABRT);

  SCOPED_TRACE("// wait for the exit");
  r.native_wait_for_exit();

  auto core_file_name = CoreFinder(r.executable(), r.get_pid()).core_name();
  // remove the core-file if it exists at the end of the test.
  Scope_guard exit_guard([core_file_name]() {
    if (core_file_name.empty() ||
        !mysql_harness::Path(core_file_name).exists()) {
      return;
    }

    std::error_code ec;
    stdx::filesystem::remove(core_file_name, ec);
  });

  if (core_file_name.empty()) {
    GTEST_SKIP() << "CoreFinder doesn't know how to locate the core-file";
  }

  if (!mysql_harness::Path(core_file_name).exists()) {
    // MacOS has cores usually disabled.
    GTEST_SKIP() << core_file_name << " does not exist";
  }

  auto dump_res = CoreDumper(r.executable(), r.get_pid()).dump(core_file_name);
  if (!dump_res) {
    GTEST_SKIP() << "CoreDumper failed with: " << dump_res.error();
  }

  // if we get a stacktrace it should mention something with mysqlrouter.
  EXPECT_THAT(dump_res.value(), ::testing::HasSubstr("mysqlrouter"));
}

struct InvalidOptions {
  std::string name;

  std::string option;
};

class RouterStacktraceInvalidOptionTest
    : public RouterStacktraceTest,
      public ::testing::WithParamInterface<InvalidOptions> {};

// TS_1_3
TEST_P(RouterStacktraceInvalidOptionTest, core_file_invalid_value_fails) {
  TempDirectory tmp_dir;

  // --core-file is added automatically by router_spawner()
  auto &r = router_spawner()
                .with_core_dump(false)  // avoid the automatic --core-file
                .expected_exit_code(ExitStatus{
                    ExitStatus::exited_t{},
                    mysql_harness::SignalHandler::HARNESS_ABORT_EXIT})
                .wait_for_sync_point(ProcessManager::Spawner::SyncPoint::NONE)
                .spawn({"--core-file=" + GetParam().option});

  SCOPED_TRACE("// wait for the exit");
  r.native_wait_for_exit();

  EXPECT_THAT(r.get_full_output(),
              ::testing::HasSubstr("needs to be one of: ['0', '1']"));
}

static const InvalidOptions invalid_options[] = {
    {"minus_1", "-1"},
    {"2", "2"},
    {"abc", "abc"},
};

INSTANTIATE_TEST_SUITE_P(Spec, RouterStacktraceInvalidOptionTest,
                         ::testing::ValuesIn(invalid_options),
                         [](auto info) { return info.param.name; });

// we skip those when ASAN, UBSAN and TSAN is used as it marks them as failed
// seeing ABORT signal
#if !defined(HAVE_ASAN) && !defined(HAVE_UBSAN) && !defined(HAVE_TSAN)

// TS_3_1
TEST_F(RouterStacktraceTest, crash_me_via_rest_signal_abort) {
  TempDirectory tmp_dir;

  auto http_port = port_pool_.get_next_available();

  auto writer =
      config_writer(tmp_dir.name())
          .section("rest_signal", {})
          .section("http_server", {{"port", std::to_string(http_port)}});

  // --core-file is added automatically by router_spawner()
  auto &r = router_spawner()
                .expected_exit_code(
                    ExitStatus{ExitStatus::terminated_t{}, segv_status})
                .spawn({"-c", writer.write()});

  SCOPED_TRACE("// aborting router");
  {
    IOContext io_ctx;
    auto resp =
        RestClient(io_ctx, "127.0.0.1", http_port)
            .request_sync(HttpMethod::Get,
                          std::string(rest_api_basepath) + "/signal/abort");

    EXPECT_FALSE(resp);  // router should crash.
  }

  SCOPED_TRACE("// wait for the exit");
  ASSERT_NO_THROW(r.native_wait_for_exit());

  auto core_file_name = CoreFinder(r.executable(), r.get_pid()).core_name();
  // remove the core-file if it exists at the end of the test.
  Scope_guard exit_guard([core_file_name]() {
    if (core_file_name.empty() ||
        !mysql_harness::Path(core_file_name).exists()) {
      return;
    }

    std::error_code ec;
    stdx::filesystem::remove(core_file_name, ec);
  });

  if (core_file_name.empty()) {
    GTEST_SKIP() << "CoreFinder doesn't know how to locate the core-file";
  }

  if (!mysql_harness::Path(core_file_name).exists()) {
    // MacOS has cores usually disabled.
    GTEST_SKIP() << core_file_name << " does not exist";
  }

  auto dump_res = CoreDumper(r.executable(), r.get_pid()).dump(core_file_name);
  if (!dump_res) {
    GTEST_SKIP() << "CoreDumper failed with: " << dump_res.error();
  }

  EXPECT_THAT(
      dump_res.value(),
      ::testing::AnyOf(
          ::testing::HasSubstr("Access violation - code "),         // cdb
          ::testing::HasSubstr("Program terminated with signal "),  // gdb
          ::testing::HasSubstr("stop reason = signal SIG")          // lldb
          ));
}

#endif  // !defined(HAVE_ASAN) && !defined(HAVE_UBSAN)

TEST_F(RouterStacktraceTest, crash_me_via_event) {
  TempDirectory tmp_dir;

  auto writer =
      config_writer(tmp_dir.name())
          .section("routing:some",
                   {
                       {"bind_port",
                        std::to_string(port_pool_.get_next_available())},
                       {"destinations", "127.0.0.1:3306"},
                       {"routing_strategy", "round-robin"},
                   });

  // --core-file is added automatically by router_spawner()
  auto &r = router_spawner()
                .expected_exit_code(
                    ExitStatus{ExitStatus::terminated_t{}, abrt_status})
                .spawn({"-c", writer.write()});

  SCOPED_TRACE("// aborting router");
  r.send_shutdown_event(mysql_harness::ProcessLauncher::ShutdownEvent::ABRT);

  SCOPED_TRACE("// wait for the exit");
  ASSERT_NO_THROW(r.native_wait_for_exit());

  auto core_file_name = CoreFinder(r.executable(), r.get_pid()).core_name();
  // remove the core-file if it exists at the end of the test.
  Scope_guard exit_guard([core_file_name]() {
    if (core_file_name.empty() ||
        !mysql_harness::Path(core_file_name).exists()) {
      return;
    }

    std::error_code ec;
    stdx::filesystem::remove(core_file_name, ec);
  });

  if (core_file_name.empty()) {
    GTEST_SKIP() << "CoreFinder doesn't know how to locate the core-file";
  }

  if (!mysql_harness::Path(core_file_name).exists()) {
    // MacOS has cores usually disabled.
    GTEST_SKIP() << core_file_name << " does not exist";
  }

  auto dump_res = CoreDumper(r.executable(), r.get_pid()).dump(core_file_name);
  if (!dump_res) {
    GTEST_SKIP() << "CoreDumper failed with: " << dump_res.error();
  }

  EXPECT_THAT(
      dump_res.value(),
      ::testing::AnyOf(
          ::testing::HasSubstr("Access violation - code "),         // cdb
          ::testing::HasSubstr("Program terminated with signal "),  // gdb
          ::testing::HasSubstr("stop reason = signal SIG")          // lldb
          ));
}

#if !defined(HAVE_ASAN) && !defined(HAVE_UBSAN) && !defined(HAVE_TSAN)

// TS_3_1
TEST_F(RouterStacktraceTest, crash_me_core_file_1) {
  TempDirectory tmp_dir;

  auto http_port = port_pool_.get_next_available();
  auto writer =
      config_writer(tmp_dir.name())
          .section("rest_signal", {})
          .section("http_server", {{"port", std::to_string(http_port)}});

  auto &r = router_spawner()
                .with_core_dump(false)  // avoid the automatic --core-file
                .expected_exit_code(
                    ExitStatus{ExitStatus::terminated_t{}, segv_status})
                .spawn({"-c", writer.write(), "--core-file", "1"});

  SCOPED_TRACE("// aborting router");
  {
    IOContext io_ctx;
    auto resp =
        RestClient(io_ctx, "127.0.0.1", http_port)
            .request_sync(HttpMethod::Get,
                          std::string(rest_api_basepath) + "/signal/abort");

    EXPECT_FALSE(resp);  // router should crash.
  }

  SCOPED_TRACE("// wait for the exit");
  ASSERT_NO_THROW(r.native_wait_for_exit());

  auto core_file_name = CoreFinder(r.executable(), r.get_pid()).core_name();
  // remove the core-file if it exists at the end of the test.
  Scope_guard exit_guard([core_file_name]() {
    if (core_file_name.empty()) return;

    std::error_code ec;
    stdx::filesystem::remove(core_file_name, ec);
  });

  if (core_file_name.empty()) {
    GTEST_SKIP() << "CoreFinder doesn't know how to locate the core-file";
  }

  if (!mysql_harness::Path(core_file_name).exists()) {
    // MacOS has cores usually disabled.
    GTEST_SKIP() << core_file_name << " does not exist";
  }

  auto dump_res = CoreDumper(r.executable(), r.get_pid()).dump(core_file_name);
  if (!dump_res) {
    GTEST_SKIP() << "CoreDumper failed with: " << dump_res.error();
  }

  EXPECT_THAT(
      dump_res.value(),
      ::testing::AnyOf(
          ::testing::HasSubstr("Access violation - code "),         // cdb
          ::testing::HasSubstr("Program terminated with signal "),  // gdb
          ::testing::HasSubstr("stop reason = signal SIG")          // lldb
          ));
}

// TS_2_2
TEST_F(RouterStacktraceTest, no_core_file) {
  RecordProperty("Description",
                 "check that if no --core-file option is present, no core-file "
                 "is created on crash, but a stacktrace on stderr.");
  TempDirectory tmp_dir;

  auto http_port = port_pool_.get_next_available();
  auto writer =
      config_writer(tmp_dir.name())
          .section("rest_signal", {})
          .section("http_server", {{"port", std::to_string(http_port)}});

  auto &r = router_spawner()
                .with_core_dump(false)
#ifdef _WIN32
                .expected_exit_code(
                    ExitStatus{ExitStatus::terminated_t{}, segv_status})
#else
                .expected_exit_code(ExitStatus{
                    ExitStatus::exited_t{},
                    mysql_harness::SignalHandler::HARNESS_FAILURE_EXIT})
#endif
                .spawn({"-c", writer.write()});

  auto core_file_name = CoreFinder(r.executable(), r.get_pid()).core_name();

  // check if the core-file exists before the abort, like from another test or
  // so.
  const bool core_file_exists_already =
      core_file_name.empty() ? false
                             : mysql_harness::Path(core_file_name).exists();

  SCOPED_TRACE("// aborting router");
  {
    IOContext io_ctx;
    auto resp =
        RestClient(io_ctx, "127.0.0.1", http_port)
            .request_sync(HttpMethod::Get,
                          std::string(rest_api_basepath) + "/signal/abort");

    EXPECT_FALSE(resp);  // router should crash.
  }

  SCOPED_TRACE("// wait for the exit");
  ASSERT_NO_THROW(r.native_wait_for_exit());

  if (!core_file_name.empty() && !core_file_exists_already) {
    // remove the core-file if it exists at the end of the test.
    Scope_guard exit_guard([core_file_name]() {
      if (core_file_name.empty() ||
          !mysql_harness::Path(core_file_name).exists()) {
        return;
      }

      std::error_code ec;
      stdx::filesystem::remove(core_file_name, ec);
    });

    SCOPED_TRACE("// expect no core-file");
    EXPECT_FALSE(mysql_harness::Path(core_file_name).exists())
        << core_file_name;
  }

  SCOPED_TRACE("// console output has stacktrace");
#ifdef HAVE_EXT_BACKTRACE
  EXPECT_THAT(r.get_full_output(), ::testing::HasSubstr("signal_handler.cc"));
#else
  EXPECT_THAT(r.get_full_output(), ::testing::HasSubstr("my_print_stacktrace"));
#endif
}

// TS_2_2
TEST_F(RouterStacktraceTest, core_file_0) {
  RecordProperty("Description",
                 "check that '--core-file=0' creates no core-file, but a "
                 "stacktrace on stderr.");
  TempDirectory tmp_dir;

  auto http_port = port_pool_.get_next_available();
  auto writer =
      config_writer(tmp_dir.name())
          .section("rest_signal", {})
          .section("http_server", {{"port", std::to_string(http_port)}});

  auto &r = router_spawner()
                .with_core_dump(false)
#ifdef _WIN32
                .expected_exit_code(
                    ExitStatus{ExitStatus::terminated_t{}, segv_status})
#else
                .expected_exit_code(ExitStatus{
                    ExitStatus::exited_t{},
                    mysql_harness::SignalHandler::HARNESS_FAILURE_EXIT})
#endif
                .spawn({"-c", writer.write(), "--core-file", "0"});

  auto core_file_name = CoreFinder(r.executable(), r.get_pid()).core_name();

  // check if the core-file exists before the abort, like from another test or
  // so.
  const bool core_file_exists_already =
      core_file_name.empty() ? false
                             : mysql_harness::Path(core_file_name).exists();

  SCOPED_TRACE("// aborting router");
  {
    IOContext io_ctx;
    auto resp =
        RestClient(io_ctx, "127.0.0.1", http_port)
            .request_sync(HttpMethod::Get,
                          std::string(rest_api_basepath) + "/signal/abort");

    EXPECT_FALSE(resp);  // router should crash.
  }

  SCOPED_TRACE("// wait for the exit");
  ASSERT_NO_THROW(r.native_wait_for_exit());

  if (!core_file_name.empty() && !core_file_exists_already) {
    // remove the core-file if it exists at the end of the test.
    Scope_guard exit_guard([core_file_name]() {
      if (core_file_name.empty() ||
          !mysql_harness::Path(core_file_name).exists()) {
        return;
      }

      std::error_code ec;
      stdx::filesystem::remove(core_file_name, ec);
    });

    SCOPED_TRACE("// expect no core-file");
    EXPECT_FALSE(mysql_harness::Path(core_file_name).exists())
        << core_file_name;
  }

  SCOPED_TRACE("// console output has stacktrace");
#ifdef HAVE_EXT_BACKTRACE
  EXPECT_THAT(r.get_full_output(), ::testing::HasSubstr("signal_handler.cc"));
#else
  EXPECT_THAT(r.get_full_output(), ::testing::HasSubstr("my_print_stacktrace"));
#endif
}

#endif  // !defined(HAVE_ASAN) && !defined(HAVE_UBSAN)

int main(int argc, char *argv[]) {
  init_windows_sockets();
  ProcessManager::set_origin(Path(argv[0]).dirname());
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}