int sonic_db_cli()

in sonic-db-cli/sonic-db-cli.cpp [247:341]


int sonic_db_cli(
    int argc,
    char** argv,
    function<void()> initializeGlobalConfig,
    function<void()> initializeConfig)
{
    Options options;
    try
    {
        parseCliArguments(argc, argv, options);
    }
    catch (invalid_argument const& e)
    {
        cerr << "Command Line Error: " << e.what() << endl;
        printUsage();
        return -1;
    }
    catch (logic_error const& e)
    {
        // getopt_long throw logic_error when found a unknown option without value.
        cerr << "Unknown option without value: "  << e.what() << endl;
        printUsage();
        return -1;
    }

    if (options.m_help)
    {
        printUsage();
        return 0;
    }

    if (!options.m_db_or_op.empty())
    {
        auto dbOrOperation = options.m_db_or_op;
        auto netns = options.m_namespace;
        bool useUnixSocket = options.m_unixsocket;
        // Load the database config for the namespace
        if (!netns.empty())
        {
            initializeGlobalConfig();

            // Use the unix domain connectivity if namespace not empty.
            useUnixSocket = true;
        }

        if (options.m_cmd.size() != 0)
        {
            auto commands = options.m_cmd;

            if (netns.empty())
            {
                initializeConfig();
            }

            return executeCommands(dbOrOperation, commands, netns, useUnixSocket);
        }
        else if (dbOrOperation == "PING"
                || dbOrOperation == "SAVE"
                || dbOrOperation == "FLUSHALL")
        {
            // redis-cli doesn't depend on database_config.json which could raise some exceptions
            // 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, useUnixSocket);
            }
            catch (const exception& e)
            {
                cerr << "An exception of type " << e.what() << " occurred. Arguments:" << endl;
                for (int idx = 0; idx < argc; idx++)
                {
                    cerr << argv[idx]  << " ";
                }
                cerr << endl;
                return 1;
            }
        }
        else
        {
            printUsage();
        }
    }
    else
    {
        printUsage();
    }

    return 0;
}