diff --git a/sonic-db-cli/sonic-db-cli.cpp b/sonic-db-cli/sonic-db-cli.cpp index 3e7003b8c..f0a22cde7 100755 --- a/sonic-db-cli/sonic-db-cli.cpp +++ b/sonic-db-cli/sonic-db-cli.cpp @@ -287,8 +287,6 @@ int sonic_db_cli( } else { - // SonicDBConfig may initialized when run cli with UT - initializeConfig(); // Use the tcp connectivity if namespace is local and unixsocket cmd_option is present. isTcpConn = true; netns = ""; @@ -297,6 +295,12 @@ int sonic_db_cli( if (options.m_cmd.size() != 0) { auto commands = options.m_cmd; + + if (netns.empty()) + { + initializeConfig(); + } + return executeCommands(dbOrOperation, commands, netns, isTcpConn); } else if (dbOrOperation == "PING" @@ -307,6 +311,12 @@ int sonic_db_cli( // sonic-db-cli catch all possible exceptions and handle it as a failure case which not return 'OK' or 'PONG' try { + if (netns.empty()) + { + // When database_config.json does not exist, sonic-db-cli will ignore exception and return 1. + initializeConfig(); + } + return handleAllInstances(netns, dbOrOperation, isTcpConn); } catch (const exception& e) diff --git a/tests/cli_ut.cpp b/tests/cli_ut.cpp index 3957cdeac..6782a95cc 100755 --- a/tests/cli_ut.cpp +++ b/tests/cli_ut.cpp @@ -11,6 +11,7 @@ using namespace swss; using namespace std; +const string not_exist_config_file = "./tests/redis_multi_db_ut_config/database_config_not_exist.json"; const string config_file = "./tests/redis_multi_db_ut_config/database_config.json"; const string global_config_file = "./tests/redis_multi_db_ut_config/database_global.json"; @@ -279,6 +280,55 @@ TEST(sonic_db_cli, test_cli_ping_cmd) EXPECT_EQ("True\n", output); } +TEST(sonic_db_cli, test_cli_ping_cmd_no_config) +{ + char *args[3]; + args[0] = "sonic-db-cli"; + args[1] = "PING"; + + // data base file does not exist, will throw exception + auto initializeGlobalConfig = []() + { + SonicDBConfig::initializeGlobalConfig(not_exist_config_file); + }; + + auto initializeConfig = []() + { + SonicDBConfig::initialize(not_exist_config_file); + }; + + optind = 0; + int exit_code = sonic_db_cli( + 2, + args, + initializeGlobalConfig, + initializeConfig); + + EXPECT_EQ(1, exit_code); + + // When ping with DB name, exception will happen + args[0] = "sonic-db-cli"; + args[1] = "TEST_DB"; + args[2] = "PING"; + + bool exception_happen = false; + try + { + optind = 0; + exit_code = sonic_db_cli( + 3, + args, + initializeGlobalConfig, + initializeConfig); + } + catch (const exception& e) + { + exception_happen = true; + } + + EXPECT_EQ(true, exception_happen); +} + TEST(sonic_db_cli, test_cli_save_cmd) { char *args[2];