Skip to content

Commit

Permalink
[cli] support default config without specifying a config file (#203)
Browse files Browse the repository at this point in the history
This commit includes two small enhancements:

1. Support starting the commissioner-cli without specifying a
   configuration file.
   a. pskc is set to all-one.
   b. log messages are printed to syslog (/var/log/syslog).
2. Add sys logger support.
  • Loading branch information
wgtdkp authored Jun 1, 2021
1 parent ae90be0 commit 79ad31d
Show file tree
Hide file tree
Showing 11 changed files with 394 additions and 71 deletions.
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ endif()
set(CMAKE_CXX_EXTENSIONS OFF)

execute_process(
COMMAND git describe --dirty --always 2>/dev/null
COMMAND git describe HEAD --always
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE OT_COMM_GIT_REVISION OUTPUT_STRIP_TRAILING_WHITESPACE
)
Expand Down
3 changes: 3 additions & 0 deletions src/app/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ add_library(commissioner-app
file_util.hpp
json.cpp
json.hpp
logger_util.hpp
sys_logger.cpp
sys_logger.hpp
)

target_link_libraries(commissioner-app
Expand Down
91 changes: 68 additions & 23 deletions src/app/cli/interpreter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

#include "app/file_util.hpp"
#include "app/json.hpp"
#include "app/sys_logger.hpp"
#include "common/error_macros.hpp"
#include "common/utils.hpp"

Expand All @@ -45,29 +46,22 @@ namespace ot {
namespace commissioner {

const std::map<std::string, Interpreter::Evaluator> &Interpreter::mEvaluatorMap = *new std::map<std::string, Evaluator>{
{"start", &Interpreter::ProcessStart},
{"stop", &Interpreter::ProcessStop},
{"active", &Interpreter::ProcessActive},
{"token", &Interpreter::ProcessToken},
{"network", &Interpreter::ProcessNetwork},
{"sessionid", &Interpreter::ProcessSessionId},
{"borderagent", &Interpreter::ProcessBorderAgent},
{"joiner", &Interpreter::ProcessJoiner},
{"commdataset", &Interpreter::ProcessCommDataset},
{"opdataset", &Interpreter::ProcessOpDataset},
{"bbrdataset", &Interpreter::ProcessBbrDataset},
{"reenroll", &Interpreter::ProcessReenroll},
{"domainreset", &Interpreter::ProcessDomainReset},
{"migrate", &Interpreter::ProcessMigrate},
{"mlr", &Interpreter::ProcessMlr},
{"announce", &Interpreter::ProcessAnnounce},
{"panid", &Interpreter::ProcessPanId},
{"energy", &Interpreter::ProcessEnergy},
{"exit", &Interpreter::ProcessExit},
{"config", &Interpreter::ProcessConfig}, {"start", &Interpreter::ProcessStart},
{"stop", &Interpreter::ProcessStop}, {"active", &Interpreter::ProcessActive},
{"token", &Interpreter::ProcessToken}, {"network", &Interpreter::ProcessNetwork},
{"sessionid", &Interpreter::ProcessSessionId}, {"borderagent", &Interpreter::ProcessBorderAgent},
{"joiner", &Interpreter::ProcessJoiner}, {"commdataset", &Interpreter::ProcessCommDataset},
{"opdataset", &Interpreter::ProcessOpDataset}, {"bbrdataset", &Interpreter::ProcessBbrDataset},
{"reenroll", &Interpreter::ProcessReenroll}, {"domainreset", &Interpreter::ProcessDomainReset},
{"migrate", &Interpreter::ProcessMigrate}, {"mlr", &Interpreter::ProcessMlr},
{"announce", &Interpreter::ProcessAnnounce}, {"panid", &Interpreter::ProcessPanId},
{"energy", &Interpreter::ProcessEnergy}, {"exit", &Interpreter::ProcessExit},
{"help", &Interpreter::ProcessHelp},
};

const std::map<std::string, std::string> &Interpreter::mUsageMap = *new std::map<std::string, std::string>{
{"config", "config get pskc\n"
"config set pskc <pskc-hex-string>"},
{"start", "start <border-agent-addr> <border-agent-port>"},
{"stop", "stop"},
{"active", "active"},
Expand Down Expand Up @@ -171,11 +165,20 @@ Error Interpreter::Init(const std::string &aConfigFile)
Error error;

std::string configJson;
Config config;

SuccessOrExit(error = ReadFile(configJson, aConfigFile));
SuccessOrExit(error = ConfigFromJson(config, configJson));
SuccessOrExit(error = CommissionerApp::Create(mCommissioner, config));
if (!aConfigFile.empty())
{
SuccessOrExit(error = ReadFile(configJson, aConfigFile));
SuccessOrExit(error = ConfigFromJson(mConfig, configJson));
}
else
{
// Default to Non-CCM mode if no configuration file is provided.
mConfig.mEnableCcm = false;
mConfig.mPSKc.assign(kMaxPSKcLength, 0xff);
mConfig.mLogger = SysLogger::Create(LogLevel::kDebug);
}
SuccessOrExit(error = CommissionerApp::Create(mCommissioner, mConfig));

exit:
return error;
Expand Down Expand Up @@ -305,6 +308,48 @@ Interpreter::Expression Interpreter::ParseExpression(const std::string &aLiteral
return expr;
}

Interpreter::Value Interpreter::ProcessConfig(const Expression &aExpr)
{
Value value;

VerifyOrExit(aExpr.size() >= 3, value = ERROR_INVALID_ARGS("two few arguments"));
VerifyOrExit(aExpr[2] == "pskc", value = ERROR_INVALID_ARGS("{} is not a valid property", aExpr[2]));
if (aExpr[1] == "get")
{
value = utils::Hex(mConfig.mPSKc);
}
else if (aExpr[1] == "set")
{
ByteArray pskc;

VerifyOrExit(aExpr.size() >= 4, value = ERROR_INVALID_ARGS("two few arguments"));
SuccessOrExit(value = utils::Hex(pskc, aExpr[3]));
SuccessOrExit(value = UpdateConfig(pskc));
}
else
{
ExitNow(value = ERROR_INVALID_COMMAND("{} is not a valid sub-command", aExpr[1]));
}

exit:
return value;
}

Error Interpreter::UpdateConfig(const ByteArray &aPSKc)
{
Error error;

VerifyOrExit(aPSKc.size() <= kMaxPSKcLength, error = ERROR_INVALID_ARGS("invalid PSKc length"));
VerifyOrExit(!mCommissioner->IsActive(),
error = ERROR_INVALID_STATE("cannot set PSKc when the commissioner is active"));

mConfig.mPSKc = aPSKc;
CommissionerApp::Create(mCommissioner, mConfig).IgnoreError();

exit:
return error;
}

Interpreter::Value Interpreter::ProcessStart(const Expression &aExpr)
{
Error error;
Expand Down
3 changes: 3 additions & 0 deletions src/app/cli/interpreter.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ class Interpreter

Expression ParseExpression(const std::string &aLiteral);

Value ProcessConfig(const Expression &aExpr);
Value ProcessStart(const Expression &aExpr);
Value ProcessStop(const Expression &aExpr);
Value ProcessActive(const Expression &aExpr);
Expand All @@ -122,6 +123,8 @@ class Interpreter
Value ProcessExit(const Expression &aExpr);
Value ProcessHelp(const Expression &aExpr);

Error UpdateConfig(const ByteArray &aPSKc);

static void BorderAgentHandler(const BorderAgent *aBorderAgent, const Error &aError);

static const std::string Usage(Expression aExpr);
Expand Down
31 changes: 19 additions & 12 deletions src/app/cli/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ static void PrintUsage(const std::string &aProgram)
{
static const std::string usage = "usage: \n"
" " +
aProgram + " <config-file>";
aProgram + " [<config-file>]";

Console::Write(usage, Console::Color::kWhite);
}
Expand All @@ -89,18 +89,25 @@ static void HandleSignalInterrupt()

int main(int argc, const char *argv[])
{
Error error;
Config config;
Error error;
std::string configFile;

if (argc < 2 || ToLower(argv[1]) == "-h" || ToLower(argv[1]) == "--help")
if (argc >= 2)
{
PrintUsage(argv[0]);
ExitNow();
}
else if (ToLower(argv[1]) == "-v" || ToLower(argv[1]) == "--version")
{
PrintVersion();
ExitNow();
if (ToLower(argv[1]) == "-h" || ToLower(argv[1]) == "--help")
{
PrintUsage(argv[0]);
ExitNow();
}
else if (ToLower(argv[1]) == "-v" || ToLower(argv[1]) == "--version")
{
PrintVersion();
ExitNow();
}
else
{
configFile = argv[1];
}
}

// Block signals in this thread and subsequently spawned threads.
Expand All @@ -112,7 +119,7 @@ int main(int argc, const char *argv[])

Console::Write(kLogo, Console::Color::kBlue);

SuccessOrExit(error = gInterpreter.Init(argv[1]));
SuccessOrExit(error = gInterpreter.Init(configFile));

gInterpreter.Run();

Expand Down
37 changes: 3 additions & 34 deletions src/app/file_logger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

/**
* @file
* This file defines file logger.
* This file implements file logger.
*
*/

Expand All @@ -38,6 +38,7 @@

#include <string.h>

#include "app/logger_util.hpp"
#include "common/error_macros.hpp"
#include "common/time.hpp"
#include "common/utils.hpp"
Expand All @@ -46,38 +47,6 @@ namespace ot {

namespace commissioner {

static std::string ToString(LogLevel aLevel)
{
std::string ret;

switch (aLevel)
{
case LogLevel::kOff:
ret = "off";
break;
case LogLevel::kCritical:
ret = "critical";
break;
case LogLevel::kError:
ret = "error";
break;
case LogLevel::kWarn:
ret = "warn";
break;
case LogLevel::kInfo:
ret = "info";
break;
case LogLevel::kDebug:
ret = "debug";
break;
default:
VerifyOrDie(false);
break;
}

return ret;
}

Error FileLogger::Create(std::shared_ptr<FileLogger> &aFileLogger, const std::string &aFilename, LogLevel aLogLevel)
{
Error error;
Expand Down Expand Up @@ -131,7 +100,7 @@ void FileLogger::Log(LogLevel aLevel, const std::string &aRegion, const std::str
VerifyOrExit(aLevel <= mLogLevel);
VerifyOrExit(mLogFile != nullptr);

logStream << "[ " << TimePointToString(Clock::now()) << " ] [ " << ToString(aLevel) << " ] [ " << aRegion << " ] "
logStream << "[ " << TimePointToString(Clock::now()) << " ] " << ToString(aLevel) << " [ " << aRegion << " ] "
<< aMsg << std::endl;
fputs(logStream.str().c_str(), mLogFile);

Expand Down
84 changes: 84 additions & 0 deletions src/app/logger_util.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2021, The OpenThread Commissioner Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

/**
* @file
* This file defines utility functions for loggers.
*
*/

#ifndef OT_COMM_APP_LOGGER_UTIL_HPP_
#define OT_COMM_APP_LOGGER_UTIL_HPP_

#include <string>

#include <commissioner/commissioner.hpp>

#include "common/utils.hpp"

namespace ot {

namespace commissioner {

static std::string ToString(LogLevel aLevel)
{
std::string ret;

switch (aLevel)
{
case LogLevel::kOff:
ret = "[ off ]";
break;
case LogLevel::kCritical:
ret = "[ crit ]";
break;
case LogLevel::kError:
ret = "[ error ]";
break;
case LogLevel::kWarn:
ret = "[ warn ]";
break;
case LogLevel::kInfo:
ret = "[ info ]";
break;
case LogLevel::kDebug:
ret = "[ debug ]";
break;
default:
VerifyOrDie(false);
break;
}

return ret;
}

} // namespace commissioner

} // namespace ot

#endif // OT_COMM_APP_LOGGER_UTIL_HPP_
Loading

0 comments on commit 79ad31d

Please sign in to comment.