add .clang-format
Change-Id: I6d9ec8401dcd46781ea258bf8998faa2507fa91d
Signed-off-by: Patrick Venture <venture@google.com>
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..ea71ad6
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,99 @@
+---
+Language: Cpp
+# BasedOnStyle: LLVM
+AccessModifierOffset: -2
+AlignAfterOpenBracket: Align
+AlignConsecutiveAssignments: false
+AlignConsecutiveDeclarations: false
+AlignEscapedNewlinesLeft: false
+AlignOperands: true
+AlignTrailingComments: true
+AllowAllParametersOfDeclarationOnNextLine: true
+AllowShortBlocksOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: None
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AlwaysBreakAfterDefinitionReturnType: None
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: false
+AlwaysBreakTemplateDeclarations: true
+BinPackArguments: true
+BinPackParameters: true
+BraceWrapping:
+ AfterClass: true
+ AfterControlStatement: true
+ AfterEnum: true
+ AfterFunction: true
+ AfterNamespace: true
+ AfterObjCDeclaration: true
+ AfterStruct: true
+ AfterUnion: true
+ BeforeCatch: true
+ BeforeElse: true
+ IndentBraces: false
+BreakBeforeBinaryOperators: None
+BreakBeforeBraces: Custom
+BreakBeforeTernaryOperators: true
+BreakConstructorInitializers: AfterColon
+ColumnLimit: 80
+CommentPragmas: '^ IWYU pragma:'
+ConstructorInitializerAllOnOneLineOrOnePerLine: false
+ConstructorInitializerIndentWidth: 4
+ContinuationIndentWidth: 4
+Cpp11BracedListStyle: true
+DerivePointerAlignment: false
+PointerAlignment: Left
+DisableFormat: false
+ExperimentalAutoDetectBinPacking: false
+FixNamespaceComments: true
+ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
+IncludeBlocks: Regroup
+IncludeCategories:
+ - Regex: '^[<"](gtest|gmock)'
+ Priority: 5
+ - Regex: '^"config.h"'
+ Priority: -1
+ - Regex: '^".*\.hpp"'
+ Priority: 1
+ - Regex: '^<.*\.h>'
+ Priority: 2
+ - Regex: '^<.*'
+ Priority: 3
+ - Regex: '.*'
+ Priority: 4
+IndentCaseLabels: true
+IndentWidth: 4
+IndentWrappedFunctionNames: true
+KeepEmptyLinesAtTheStartOfBlocks: true
+MacroBlockBegin: ''
+MacroBlockEnd: ''
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: None
+ObjCBlockIndentWidth: 2
+ObjCSpaceAfterProperty: false
+ObjCSpaceBeforeProtocolList: true
+PenaltyBreakBeforeFirstCallParameter: 19
+PenaltyBreakComment: 300
+PenaltyBreakFirstLessLess: 120
+PenaltyBreakString: 1000
+PenaltyExcessCharacter: 1000000
+PenaltyReturnTypeOnItsOwnLine: 60
+ReflowComments: true
+SortIncludes: true
+SortUsingDeclarations: true
+SpaceAfterCStyleCast: false
+SpaceBeforeAssignmentOperators: true
+SpaceBeforeParens: ControlStatements
+SpaceInEmptyParentheses: false
+SpacesBeforeTrailingComments: 1
+SpacesInAngles: false
+SpacesInContainerLiterals: true
+SpacesInCStyleCastParentheses: false
+SpacesInParentheses: false
+SpacesInSquareBrackets: false
+Standard: Cpp11
+TabWidth: 4
+UseTab: Never
+...
+
diff --git a/argument.cpp b/argument.cpp
index 770db87..fa0d4bc 100644
--- a/argument.cpp
+++ b/argument.cpp
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-#include <iostream>
-#include <cassert>
#include "argument.hpp"
+#include <cassert>
+#include <iostream>
+
namespace phosphor
{
namespace watchdog
@@ -29,6 +30,7 @@
const std::string ArgumentParser::trueString = "true"s;
const char* ArgumentParser::optionStr = "p:s:t:a:f:i:ech";
+// clang-format off
const option ArgumentParser::options[] =
{
{ "path", required_argument, nullptr, 'p' },
@@ -42,8 +44,9 @@
{ "help", no_argument, nullptr, 'h' },
{ 0, 0, 0, 0},
};
+// clang-format on
-ArgumentParser::ArgumentParser(int argc, char * const argv[])
+ArgumentParser::ArgumentParser(int argc, char* const argv[])
{
int option;
int opt_idx = 0;
@@ -54,7 +57,8 @@
// already process instructions, optind may not be initialized to point to
// the beginning of our argv.
optind = 0;
- while (-1 != (option = getopt_long(argc, argv, optionStr, options, &opt_idx)))
+ while (-1 !=
+ (option = getopt_long(argc, argv, optionStr, options, &opt_idx)))
{
if (option == '?' || option == 'h')
{
@@ -77,7 +81,8 @@
}
}
-const std::vector<std::string>& ArgumentParser::operator[](const std::string& opt)
+const std::vector<std::string>& ArgumentParser::
+ operator[](const std::string& opt)
{
auto i = arguments.find(opt);
if (i == arguments.end())
@@ -90,33 +95,33 @@
}
}
-void ArgumentParser::usage(char * const argv[])
+void ArgumentParser::usage(char* const argv[])
{
std::cerr << "Usage: " << argv[0] << " options\n";
std::cerr << "Options:\n";
std::cerr << " --help Print this menu\n";
std::cerr << " --path=<Dbus Object path> Dbus Object path. "
- "Ex: /xyz/openbmc_project/state/watchdog/host0\n";
+ "Ex: /xyz/openbmc_project/state/watchdog/host0\n";
std::cerr << " --service=<Dbus Service name> Dbus Service "
- "name. Ex: xyz.openbmc_project.State.Watchdog.Host\n";
+ "name. Ex: xyz.openbmc_project.State.Watchdog.Host\n";
std::cerr << " [--target=<systemd unit>] Systemd unit to "
- "be called on timeout for all actions but NONE. "
- "Deprecated, use --action_target instead.\n";
+ "be called on timeout for all actions but NONE. "
+ "Deprecated, use --action_target instead.\n";
std::cerr << " [--action_target=<action>=<systemd unit>] Map of action to "
- "systemd unit to be called on timeout if that action is "
- "set for ExpireAction when the timer expires.\n";
+ "systemd unit to be called on timeout if that action is "
+ "set for ExpireAction when the timer expires.\n";
std::cerr << " [--fallback_action=<action>] Enables the "
- "watchdog even when disabled via the dbus interface. "
- "Perform this action when the fallback expires.\n";
+ "watchdog even when disabled via the dbus interface. "
+ "Perform this action when the fallback expires.\n";
std::cerr << " [--fallback_interval=<interval in ms>] Enables the "
- "watchdog even when disabled via the dbus interface. "
- "Waits for this interval before performing the fallback "
- "action.\n";
+ "watchdog even when disabled via the dbus interface. "
+ "Waits for this interval before performing the fallback "
+ "action.\n";
std::cerr << " [--fallback_always] Enables the "
- "watchdog even when disabled by the dbus interface. "
- "This option is only valid with a fallback specified.\n";
+ "watchdog even when disabled by the dbus interface. "
+ "This option is only valid with a fallback specified.\n";
std::cerr << " [--continue] Continue daemon "
- "after watchdog timeout.\n";
+ "after watchdog timeout.\n";
}
} // namespace watchdog
} // namespace phosphor
diff --git a/argument.hpp b/argument.hpp
index 8a25aea..df61de1 100644
--- a/argument.hpp
+++ b/argument.hpp
@@ -1,6 +1,7 @@
#pragma once
#include <getopt.h>
+
#include <map>
#include <string>
#include <vector>
@@ -14,48 +15,48 @@
*/
class ArgumentParser
{
- public:
- ArgumentParser() = delete;
- ~ArgumentParser() = default;
- ArgumentParser(const ArgumentParser&) = delete;
- ArgumentParser& operator=(const ArgumentParser&) = delete;
- ArgumentParser(ArgumentParser&&) = default;
- ArgumentParser& operator=(ArgumentParser&&) = default;
+ public:
+ ArgumentParser() = delete;
+ ~ArgumentParser() = default;
+ ArgumentParser(const ArgumentParser&) = delete;
+ ArgumentParser& operator=(const ArgumentParser&) = delete;
+ ArgumentParser(ArgumentParser&&) = default;
+ ArgumentParser& operator=(ArgumentParser&&) = default;
- /** @brief Constructs ArgumentParser object
- *
- * @param argc - the main function's argc passed as is
- * @param argv - the main function's argv passed as is
- * @return Object constructed
- */
- ArgumentParser(int argc, char * const argv[]);
+ /** @brief Constructs ArgumentParser object
+ *
+ * @param argc - the main function's argc passed as is
+ * @param argv - the main function's argv passed as is
+ * @return Object constructed
+ */
+ ArgumentParser(int argc, char* const argv[]);
- /** @brief Given an option, returns its argument(optarg)
- *
- * @param opt - command line option string
- *
- * @return argument which is a standard optarg
- */
- const std::vector<std::string>& operator[](const std::string& opt);
+ /** @brief Given an option, returns its argument(optarg)
+ *
+ * @param opt - command line option string
+ *
+ * @return argument which is a standard optarg
+ */
+ const std::vector<std::string>& operator[](const std::string& opt);
- /** @brief Displays usage
- *
- * @param argv - the main function's argv passed as is
- */
- static void usage(char * const argv[]);
+ /** @brief Displays usage
+ *
+ * @param argv - the main function's argv passed as is
+ */
+ static void usage(char* const argv[]);
- /** @brief Set to 'true' when an option is passed */
- static const std::string trueString;
+ /** @brief Set to 'true' when an option is passed */
+ static const std::string trueString;
- private:
- /** @brief Option to argument mapping */
- std::map<const std::string, std::vector<std::string> > arguments;
+ private:
+ /** @brief Option to argument mapping */
+ std::map<const std::string, std::vector<std::string>> arguments;
- /** @brief Array of struct options as needed by getopt_long */
- static const option options[];
+ /** @brief Array of struct options as needed by getopt_long */
+ static const option options[];
- /** @brief optstring as needed by getopt_long */
- static const char* optionStr;
+ /** @brief optstring as needed by getopt_long */
+ static const char* optionStr;
};
} // namespace watchdog
diff --git a/mainapp.cpp b/mainapp.cpp
index de09ba3..889e241 100644
--- a/mainapp.cpp
+++ b/mainapp.cpp
@@ -14,16 +14,17 @@
* limitations under the License.
*/
-#include <iostream>
-#include <experimental/optional>
-#include <phosphor-logging/log.hpp>
-#include <phosphor-logging/elog.hpp>
-#include <phosphor-logging/elog-errors.hpp>
-#include <string>
-#include <xyz/openbmc_project/Common/error.hpp>
#include "argument.hpp"
#include "watchdog.hpp"
+#include <experimental/optional>
+#include <iostream>
+#include <phosphor-logging/elog-errors.hpp>
+#include <phosphor-logging/elog.hpp>
+#include <phosphor-logging/log.hpp>
+#include <string>
+#include <xyz/openbmc_project/Common/error.hpp>
+
using phosphor::watchdog::ArgumentParser;
using phosphor::watchdog::Watchdog;
using sdbusplus::xyz::openbmc_project::State::server::convertForMessage;
@@ -36,13 +37,13 @@
}
void printActionTargets(
- const std::map<Watchdog::Action, std::string>& actionTargets)
+ const std::map<Watchdog::Action, std::string>& actionTargets)
{
std::cerr << "Action Targets:\n";
for (const auto& actionTarget : actionTargets)
{
- std::cerr << " " << convertForMessage(actionTarget.first) << " -> " <<
- actionTarget.second << "\n";
+ std::cerr << " " << convertForMessage(actionTarget.first) << " -> "
+ << actionTarget.second << "\n";
}
std::cerr << std::flush;
}
@@ -50,8 +51,8 @@
int main(int argc, char** argv)
{
using namespace phosphor::logging;
- using InternalFailure = sdbusplus::xyz::openbmc_project::Common::
- Error::InternalFailure;
+ using InternalFailure =
+ sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
// Read arguments.
auto options = ArgumentParser(argc, argv);
@@ -97,7 +98,8 @@
exitWithError("Multiple targets specified.", argv);
}
std::map<Watchdog::Action, Watchdog::TargetName> actionTargets;
- if (!targetParam.empty()) {
+ if (!targetParam.empty())
+ {
auto target = targetParam.back();
actionTargets[Watchdog::Action::HardReset] = target;
actionTargets[Watchdog::Action::PowerOff] = target;
@@ -112,12 +114,12 @@
if (keyValueSplit == std::string::npos)
{
exitWithError(
- "Invalid action_target format, expect <action>=<target>.",
- argv);
+ "Invalid action_target format, expect <action>=<target>.",
+ argv);
}
std::string key = actionTarget.substr(0, keyValueSplit);
- std::string value = actionTarget.substr(keyValueSplit+1);
+ std::string value = actionTarget.substr(keyValueSplit + 1);
// Convert an action from a fully namespaced value
Watchdog::Action action;
@@ -125,7 +127,7 @@
{
action = Watchdog::convertActionFromString(key);
}
- catch (const sdbusplus::exception::InvalidEnumString &)
+ catch (const sdbusplus::exception::InvalidEnumString&)
{
exitWithError("Bad action specified.", argv);
}
@@ -153,10 +155,10 @@
Watchdog::Action action;
try
{
- action = Watchdog::convertActionFromString(
- fallbackActionParam.back());
+ action =
+ Watchdog::convertActionFromString(fallbackActionParam.back());
}
- catch (const sdbusplus::exception::InvalidEnumString &)
+ catch (const sdbusplus::exception::InvalidEnumString&)
{
exitWithError("Bad action specified.", argv);
}
@@ -165,9 +167,10 @@
{
interval = std::stoull(fallbackIntervalParam.back());
}
- catch (const std::logic_error &)
+ catch (const std::logic_error&)
{
- exitWithError("Failed to convert fallback interval to integer.", argv);
+ exitWithError("Failed to convert fallback interval to integer.",
+ argv);
}
fallback = Watchdog::Fallback{
.action = action,
@@ -182,7 +185,8 @@
if (!fallback)
{
exitWithError("Specified the fallback should always be enabled but "
- "no fallback provided.", argv);
+ "no fallback provided.",
+ argv);
}
fallback->always = true;
}
@@ -210,7 +214,7 @@
{
// Create a watchdog object
Watchdog watchdog(bus, path.c_str(), eventP, std::move(actionTargets),
- std::move(fallback));
+ std::move(fallback));
// Claim the bus
bus.request_name(service.c_str());
@@ -227,7 +231,7 @@
}
}
}
- catch(InternalFailure& e)
+ catch (InternalFailure& e)
{
phosphor::logging::commit<InternalFailure>();
diff --git a/test/argument_test.cpp b/test/argument_test.cpp
index e293e99..3cb5dc9 100644
--- a/test/argument_test.cpp
+++ b/test/argument_test.cpp
@@ -1,8 +1,9 @@
-#include <string>
-#include <vector>
+#include "argument_test.hpp"
#include "argument.hpp"
-#include "argument_test.hpp"
+
+#include <string>
+#include <vector>
static const std::string expected_path1 = "/arg1-test-path";
static const std::string expected_target1 = "t1.target";
@@ -10,7 +11,7 @@
// Allow for a single unrecognized option then the Usage printout
static const std::string invalid_arg_regex =
- "^[^\n]*unrecognized option[^\n]*\nUsage: ";
+ "^[^\n]*unrecognized option[^\n]*\nUsage: ";
static const std::string clean_usage_regex = "^Usage: ";
@@ -27,10 +28,8 @@
/** @brief ArgumentParser should return no values if given no options */
TEST_F(ArgumentTest, NoOptions)
{
- char * const args[] = {
- &arg0[0], nullptr
- };
- ArgumentParser ap(sizeof(args)/sizeof(char *) - 1, args);
+ char* const args[] = {&arg0[0], nullptr};
+ ArgumentParser ap(sizeof(args) / sizeof(char*) - 1, args);
EXPECT_EQ(std::vector<std::string>({}), ap["path"]);
EXPECT_EQ(std::vector<std::string>({}), ap["continue"]);
EXPECT_EQ(std::vector<std::string>({}), ap["arbitrary_unknown"]);
@@ -44,13 +43,11 @@
{
std::string arg_continue = "--continue";
std::string arg_extra = "not-a-bool";
- char * const args[] = {
- &arg0[0], &arg_continue[0], &arg_extra[0], nullptr
- };
- ArgumentParser ap(sizeof(args)/sizeof(char *) - 1, args);
+ char* const args[] = {&arg0[0], &arg_continue[0], &arg_extra[0], nullptr};
+ ArgumentParser ap(sizeof(args) / sizeof(char*) - 1, args);
EXPECT_EQ(std::vector<std::string>({}), ap["path"]);
EXPECT_EQ(std::vector<std::string>({ArgumentParser::trueString}),
- ap["continue"]);
+ ap["continue"]);
}
/** @brief ArgumentParser should return a string for long options that
@@ -61,10 +58,9 @@
std::string arg_path = "--path";
std::string arg_path_val = expected_path1;
std::string arg_extra = "/unused-path";
- char * const args[] = {
- &arg0[0], &arg_path[0], &arg_path_val[0], &arg_extra[0], nullptr
- };
- ArgumentParser ap(sizeof(args)/sizeof(char *) - 1, args);
+ char* const args[] = {&arg0[0], &arg_path[0], &arg_path_val[0],
+ &arg_extra[0], nullptr};
+ ArgumentParser ap(sizeof(args) / sizeof(char*) - 1, args);
EXPECT_EQ(std::vector<std::string>({expected_path1}), ap["path"]);
}
@@ -75,10 +71,8 @@
{
std::string arg_path = "--path=" + expected_path1;
std::string arg_extra = "/unused-path";
- char * const args[] = {
- &arg0[0], &arg_path[0], &arg_extra[0], nullptr
- };
- ArgumentParser ap(sizeof(args)/sizeof(char *) - 1, args);
+ char* const args[] = {&arg0[0], &arg_path[0], &arg_extra[0], nullptr};
+ ArgumentParser ap(sizeof(args) / sizeof(char*) - 1, args);
EXPECT_EQ(std::vector<std::string>({expected_path1}), ap["path"]);
}
@@ -90,10 +84,9 @@
std::string arg_path = "-p";
std::string arg_path_val = expected_path1;
std::string arg_extra = "/unused-path";
- char * const args[] = {
- &arg0[0], &arg_path[0], &arg_path_val[0], &arg_extra[0], nullptr
- };
- ArgumentParser ap(sizeof(args)/sizeof(char *) - 1, args);
+ char* const args[] = {&arg0[0], &arg_path[0], &arg_path_val[0],
+ &arg_extra[0], nullptr};
+ ArgumentParser ap(sizeof(args) / sizeof(char*) - 1, args);
EXPECT_EQ(std::vector<std::string>({expected_path1}), ap["path"]);
}
@@ -109,17 +102,17 @@
std::string arg_target = "--target=" + expected_target2;
std::string arg_target_short = "-t";
std::string arg_target_val = expected_target1;
- char * const args[] = {
- &arg0[0], &arg_continue_short[0], &arg_path[0], &arg_continue_long[0],
- &arg_target[0], &arg_target_short[0], &arg_target_val[0], nullptr
- };
- ArgumentParser ap(sizeof(args)/sizeof(char *) - 1, args);
+ char* const args[] = {&arg0[0], &arg_continue_short[0],
+ &arg_path[0], &arg_continue_long[0],
+ &arg_target[0], &arg_target_short[0],
+ &arg_target_val[0], nullptr};
+ ArgumentParser ap(sizeof(args) / sizeof(char*) - 1, args);
EXPECT_EQ(std::vector<std::string>({expected_path1}), ap["path"]);
- EXPECT_EQ(std::vector<std::string>({
- ArgumentParser::trueString, ArgumentParser::trueString}),
- ap["continue"]);
+ EXPECT_EQ(std::vector<std::string>(
+ {ArgumentParser::trueString, ArgumentParser::trueString}),
+ ap["continue"]);
EXPECT_EQ(std::vector<std::string>({expected_target2, expected_target1}),
- ap["target"]);
+ ap["target"]);
}
/** @brief ArgumentParser should print usage information when given a help
@@ -129,11 +122,9 @@
{
std::string arg_extra = "extra";
std::string arg_help = "-h";
- char * const args[] = {
- &arg0[0], &arg_extra[0], &arg_help[0], nullptr
- };
- EXPECT_EXIT(ArgumentParser(sizeof(args)/sizeof(char *) - 1, args),
- ::testing::ExitedWithCode(255), clean_usage_regex);
+ char* const args[] = {&arg0[0], &arg_extra[0], &arg_help[0], nullptr};
+ EXPECT_EXIT(ArgumentParser(sizeof(args) / sizeof(char*) - 1, args),
+ ::testing::ExitedWithCode(255), clean_usage_regex);
}
/** @brief ArgumentParser should print usage information when given a help
@@ -143,11 +134,9 @@
{
std::string arg_help = "--help";
std::string arg_extra = "extra";
- char * const args[] = {
- &arg0[0], &arg_help[0], &arg_extra[0], nullptr
- };
- EXPECT_EXIT(ArgumentParser(sizeof(args)/sizeof(char *) - 1, args),
- ::testing::ExitedWithCode(255), clean_usage_regex);
+ char* const args[] = {&arg0[0], &arg_help[0], &arg_extra[0], nullptr};
+ EXPECT_EXIT(ArgumentParser(sizeof(args) / sizeof(char*) - 1, args),
+ ::testing::ExitedWithCode(255), clean_usage_regex);
}
/** @brief ArgumentParser should print an invalid argument error and
@@ -159,12 +148,11 @@
std::string arg_continue = "--continue";
std::string arg_bad = "--bad_arg";
std::string arg_target = "--target=/unused-path";
- char * const args[] = {
- &arg0[0], &arg_continue[0], &arg_bad[0], &arg_target[0], nullptr
- };
- EXPECT_EXIT(ArgumentParser(sizeof(args)/sizeof(char *) - 1, args),
- ::testing::ExitedWithCode(255), invalid_arg_regex);
+ char* const args[] = {&arg0[0], &arg_continue[0], &arg_bad[0],
+ &arg_target[0], nullptr};
+ EXPECT_EXIT(ArgumentParser(sizeof(args) / sizeof(char*) - 1, args),
+ ::testing::ExitedWithCode(255), invalid_arg_regex);
}
-} // namespace watchdog
-} // namespace phosphor
+} // namespace watchdog
+} // namespace phosphor
diff --git a/test/argument_test.hpp b/test/argument_test.hpp
index 9e8c565..46e8762 100644
--- a/test/argument_test.hpp
+++ b/test/argument_test.hpp
@@ -11,11 +11,11 @@
class ArgumentTest : public testing::Test
{
- protected:
- void SetUp() override;
+ protected:
+ void SetUp() override;
- std::string arg0;
+ std::string arg0;
};
-} // namespace watchdog
-} // namespace phosphor
+} // namespace watchdog
+} // namespace phosphor
diff --git a/test/timer_test.cpp b/test/timer_test.cpp
index 3deef08..ea00228 100644
--- a/test/timer_test.cpp
+++ b/test/timer_test.cpp
@@ -21,11 +21,11 @@
// Waiting 2 seconds to expect expiration
int count = 0;
- while(count < expireTime.count() && !timer.expired())
+ while (count < expireTime.count() && !timer.expired())
{
// Returns -0- on timeout and positive number on dispatch
auto sleepTime = duration_cast<microseconds>(seconds(1));
- if(!sd_event_run(eventP.get(), sleepTime.count()))
+ if (!sd_event_run(eventP.get(), sleepTime.count()))
{
count++;
}
@@ -46,8 +46,8 @@
// Expect timer to expire in 2 seconds
auto expireTime = seconds(2s);
- phosphor::watchdog::Timer timer(eventP,
- std::bind(&TimerTest::timeOutHandler, this));
+ phosphor::watchdog::Timer timer(
+ eventP, std::bind(&TimerTest::timeOutHandler, this));
// Set the expiration and enable the timer
timer.start(duration_cast<milliseconds>(expireTime));
@@ -55,11 +55,11 @@
// Waiting 2 seconds to expect expiration
int count = 0;
- while(count < expireTime.count() && !timer.expired())
+ while (count < expireTime.count() && !timer.expired())
{
// Returns -0- on timeout and positive number on dispatch
auto sleepTime = duration_cast<microseconds>(seconds(1));
- if(!sd_event_run(eventP.get(), sleepTime.count()))
+ if (!sd_event_run(eventP.get(), sleepTime.count()))
{
count++;
}
diff --git a/test/timer_test.hpp b/test/timer_test.hpp
index 3f6ffea..cab9086 100644
--- a/test/timer_test.hpp
+++ b/test/timer_test.hpp
@@ -1,40 +1,39 @@
#include <iostream>
-#include <gtest/gtest.h>
#include <timer.hpp>
+#include <gtest/gtest.h>
+
// Base class for testing Timer
class TimerTest : public testing::Test
{
- public:
- // systemd event handler
- sd_event* events;
+ public:
+ // systemd event handler
+ sd_event* events;
- // Need this so that events can be initialized.
- int rc;
+ // Need this so that events can be initialized.
+ int rc;
- // Tells if the watchdog timer expired.
- bool expired = false;
+ // Tells if the watchdog timer expired.
+ bool expired = false;
- // Gets called as part of each TEST_F construction
- TimerTest()
- : rc(sd_event_default(&events)),
- eventP(events)
- {
- // Check for successful creation of
- // event handler and bus handler
- EXPECT_GE(rc, 0);
+ // Gets called as part of each TEST_F construction
+ TimerTest() : rc(sd_event_default(&events)), eventP(events)
+ {
+ // Check for successful creation of
+ // event handler and bus handler
+ EXPECT_GE(rc, 0);
- // Its already wrapped in eventP
- events = nullptr;
- }
+ // Its already wrapped in eventP
+ events = nullptr;
+ }
- // unique_ptr for sd_event
- phosphor::watchdog::EventPtr eventP;
+ // unique_ptr for sd_event
+ phosphor::watchdog::EventPtr eventP;
- // Handler called by timer expiration
- inline void timeOutHandler()
- {
- std::cout << "Time out handler called" << std::endl;
- expired = true;
- }
+ // Handler called by timer expiration
+ inline void timeOutHandler()
+ {
+ std::cout << "Time out handler called" << std::endl;
+ expired = true;
+ }
};
diff --git a/test/watchdog_test.cpp b/test/watchdog_test.cpp
index 34d1d24..f24d45e 100644
--- a/test/watchdog_test.cpp
+++ b/test/watchdog_test.cpp
@@ -1,24 +1,23 @@
+#include "watchdog_test.hpp"
+
#include <chrono>
#include <memory>
#include <utility>
-#include "watchdog_test.hpp"
-
using namespace phosphor::watchdog;
seconds WdogTest::waitForWatchdog(seconds timeLimit)
{
auto previousTimeRemaining = wdog->timeRemaining();
auto ret = 0s;
- while (ret < timeLimit &&
- previousTimeRemaining >= wdog->timeRemaining() &&
+ while (ret < timeLimit && previousTimeRemaining >= wdog->timeRemaining() &&
wdog->timerEnabled())
{
previousTimeRemaining = wdog->timeRemaining();
// Returns -0- on timeout and positive number on dispatch
auto sleepTime = 1s;
- if(!sd_event_run(eventP.get(), microseconds(sleepTime).count()))
+ if (!sd_event_run(eventP.get(), microseconds(sleepTime).count()))
{
ret += sleepTime;
}
@@ -194,7 +193,8 @@
};
std::map<Watchdog::Action, Watchdog::TargetName> emptyActionTargets;
wdog = std::make_unique<Watchdog>(bus, TEST_PATH, eventP,
- std::move(emptyActionTargets), std::move(fallback));
+ std::move(emptyActionTargets),
+ std::move(fallback));
EXPECT_EQ(primaryInterval, milliseconds(wdog->interval(primaryIntervalMs)));
EXPECT_FALSE(wdog->enabled());
EXPECT_EQ(0, wdog->timeRemaining());
@@ -218,7 +218,7 @@
auto newIntervalMs = milliseconds(newInterval).count();
EXPECT_EQ(newInterval, milliseconds(wdog->interval(newIntervalMs)));
EXPECT_EQ(Watchdog::Action::None,
- wdog->expireAction(Watchdog::Action::None));
+ wdog->expireAction(Watchdog::Action::None));
EXPECT_FALSE(wdog->enabled());
EXPECT_GE(remaining, milliseconds(wdog->timeRemaining()));
@@ -277,7 +277,8 @@
};
std::map<Watchdog::Action, Watchdog::TargetName> emptyActionTargets;
wdog = std::make_unique<Watchdog>(bus, TEST_PATH, eventP,
- std::move(emptyActionTargets), std::move(fallback));
+ std::move(emptyActionTargets),
+ std::move(fallback));
EXPECT_EQ(primaryInterval, milliseconds(wdog->interval(primaryIntervalMs)));
EXPECT_FALSE(wdog->enabled());
EXPECT_EQ(0, wdog->timeRemaining());
@@ -331,7 +332,8 @@
};
std::map<Watchdog::Action, Watchdog::TargetName> emptyActionTargets;
wdog = std::make_unique<Watchdog>(bus, TEST_PATH, eventP,
- std::move(emptyActionTargets), std::move(fallback));
+ std::move(emptyActionTargets),
+ std::move(fallback));
EXPECT_EQ(primaryInterval, milliseconds(wdog->interval(primaryIntervalMs)));
EXPECT_FALSE(wdog->enabled());
auto remaining = milliseconds(wdog->timeRemaining());
diff --git a/test/watchdog_test.hpp b/test/watchdog_test.hpp
index 87c64e9..50fa8f1 100644
--- a/test/watchdog_test.hpp
+++ b/test/watchdog_test.hpp
@@ -1,6 +1,6 @@
-#include <timer_test.hpp>
#include <chrono>
#include <memory>
+#include <timer_test.hpp>
#include <watchdog.hpp>
using namespace std::chrono;
@@ -9,44 +9,43 @@
// Test Watchdog functionality
class WdogTest : public TimerTest
{
- public:
- // Gets called as part of each TEST_F construction
- WdogTest()
- : bus(sdbusplus::bus::new_default()),
- wdog(std::make_unique<phosphor::watchdog::Watchdog>(
- bus, TEST_PATH, eventP)),
- defaultInterval(milliseconds(wdog->interval())),
- defaultDrift(30)
- {
- // Check for successful creation of
- // event handler and bus handler
- EXPECT_GE(rc, 0);
+ public:
+ // Gets called as part of each TEST_F construction
+ WdogTest() :
+ bus(sdbusplus::bus::new_default()),
+ wdog(std::make_unique<phosphor::watchdog::Watchdog>(bus, TEST_PATH,
+ eventP)),
+ defaultInterval(milliseconds(wdog->interval())), defaultDrift(30)
+ {
+ // Check for successful creation of
+ // event handler and bus handler
+ EXPECT_GE(rc, 0);
- // Initially the watchdog would be disabled
- EXPECT_FALSE(wdog->enabled());
- }
+ // Initially the watchdog would be disabled
+ EXPECT_FALSE(wdog->enabled());
+ }
- //sdbusplus handle
- sdbusplus::bus::bus bus;
+ // sdbusplus handle
+ sdbusplus::bus::bus bus;
- // Watchdog object
- std::unique_ptr<phosphor::watchdog::Watchdog> wdog;
+ // Watchdog object
+ std::unique_ptr<phosphor::watchdog::Watchdog> wdog;
- // This is the default interval as given in Interface definition
- milliseconds defaultInterval;
+ // This is the default interval as given in Interface definition
+ milliseconds defaultInterval;
- // Acceptable drift when we compare the interval to timeRemaining.
- // This is needed since it depends on when do we get scheduled and it
- // has happened that remaining time was off by few msecs.
- milliseconds defaultDrift;
+ // Acceptable drift when we compare the interval to timeRemaining.
+ // This is needed since it depends on when do we get scheduled and it
+ // has happened that remaining time was off by few msecs.
+ milliseconds defaultDrift;
- protected:
- // Dummy name for object path
- // This is just to satisfy the constructor. Does not have
- // a need to check if the objects paths have been created.
- static constexpr auto TEST_PATH = "/test/path";
+ protected:
+ // Dummy name for object path
+ // This is just to satisfy the constructor. Does not have
+ // a need to check if the objects paths have been created.
+ static constexpr auto TEST_PATH = "/test/path";
- // Returns how long it took for the current watchdog timer to be
- // disabled or have its timeRemaining reset.
- seconds waitForWatchdog(seconds timeLimit);
+ // Returns how long it took for the current watchdog timer to be
+ // disabled or have its timeRemaining reset.
+ seconds waitForWatchdog(seconds timeLimit);
};
diff --git a/timer.cpp b/timer.cpp
index f4bf725..3dfe560 100644
--- a/timer.cpp
+++ b/timer.cpp
@@ -1,10 +1,12 @@
-#include <chrono>
-#include <systemd/sd-event.h>
-#include <phosphor-logging/log.hpp>
-#include <phosphor-logging/elog.hpp>
-#include <phosphor-logging/elog-errors.hpp>
-#include <xyz/openbmc_project/Common/error.hpp>
#include "timer.hpp"
+
+#include <systemd/sd-event.h>
+
+#include <chrono>
+#include <phosphor-logging/elog-errors.hpp>
+#include <phosphor-logging/elog.hpp>
+#include <phosphor-logging/log.hpp>
+#include <xyz/openbmc_project/Common/error.hpp>
namespace phosphor
{
namespace watchdog
@@ -12,8 +14,8 @@
// For throwing exception
using namespace phosphor::logging;
-using InternalFailure = sdbusplus::xyz::openbmc_project::Common::
- Error::InternalFailure;
+using InternalFailure =
+ sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
// Initializes the timer object
void Timer::initialize()
@@ -27,8 +29,7 @@
// Add infinite expiration time
decltype(eventSource.get()) sourcePtr = nullptr;
- auto r = sd_event_add_time(event.get(),
- &sourcePtr,
+ auto r = sd_event_add_time(event.get(), &sourcePtr,
CLOCK_MONOTONIC, // Time base
UINT64_MAX, // Expire time - way long time
0, // Use default event accuracy
@@ -47,8 +48,8 @@
}
// callback handler on timeout
-int Timer::timeoutHandler(sd_event_source* eventSource,
- uint64_t usec, void* userData)
+int Timer::timeoutHandler(sd_event_source* eventSource, uint64_t usec,
+ void* userData)
{
using namespace phosphor::logging;
@@ -58,7 +59,7 @@
timer->expire = true;
// Call an optional callback function
- if(timer->userCallBack)
+ if (timer->userCallBack)
{
timer->userCallBack();
}
@@ -82,12 +83,12 @@
auto expireTime = getCurrentTime() + usec;
// Set the time
- auto r = sd_event_source_set_time(eventSource.get(),
- expireTime.count());
+ auto r = sd_event_source_set_time(eventSource.get(), expireTime.count());
if (r < 0)
{
- log<level::ERR>("Error setting the expiration time",
- entry("MSEC=%llu",duration_cast<milliseconds>(usec).count()));
+ log<level::ERR>(
+ "Error setting the expiration time",
+ entry("MSEC=%llu", duration_cast<milliseconds>(usec).count()));
elog<InternalFailure>();
}
}
@@ -111,8 +112,7 @@
auto r = sd_event_source_set_enabled(eventSource.get(), type);
if (r < 0)
{
- log<level::ERR>("Error setting the timer type",
- entry("TYPE=%d",type));
+ log<level::ERR>("Error setting the timer type", entry("TYPE=%d", type));
elog<InternalFailure>();
}
}
diff --git a/timer.hpp b/timer.hpp
index 058740e..28222a2 100644
--- a/timer.hpp
+++ b/timer.hpp
@@ -1,9 +1,10 @@
#pragma once
+#include <systemd/sd-event.h>
+
+#include <chrono>
#include <functional>
#include <memory>
-#include <chrono>
-#include <systemd/sd-event.h>
namespace phosphor
{
namespace watchdog
@@ -34,113 +35,112 @@
*/
class Timer
{
- public:
- Timer() = delete;
- ~Timer() = default;
- Timer(const Timer&) = delete;
- Timer& operator=(const Timer&) = delete;
- Timer(Timer&&) = delete;
- Timer& operator=(Timer&&) = delete;
+ public:
+ Timer() = delete;
+ ~Timer() = default;
+ Timer(const Timer&) = delete;
+ Timer& operator=(const Timer&) = delete;
+ Timer(Timer&&) = delete;
+ Timer& operator=(Timer&&) = delete;
- /** @brief Constructs timer object
- *
- * @param[in] event - sd_event unique pointer
- * @param[in] userCallBack - Optional function callback
- * for timer expiration
- */
- Timer(EventPtr& event,
- std::function<void()> userCallBack = nullptr)
- : event(event),
- userCallBack(userCallBack)
- {
- // Initialize the timer
- initialize();
- }
+ /** @brief Constructs timer object
+ *
+ * @param[in] event - sd_event unique pointer
+ * @param[in] userCallBack - Optional function callback
+ * for timer expiration
+ */
+ Timer(EventPtr& event, std::function<void()> userCallBack = nullptr) :
+ event(event), userCallBack(userCallBack)
+ {
+ // Initialize the timer
+ initialize();
+ }
- void clearExpired(void)
- {
- expire = false;
- }
+ void clearExpired(void)
+ {
+ expire = false;
+ }
- /** @brief Tells whether the timer is expired or not */
- inline auto expired() const
- {
- return expire;
- }
+ /** @brief Tells whether the timer is expired or not */
+ inline auto expired() const
+ {
+ return expire;
+ }
- /** @brief Returns the current Timer enablement type */
- int getEnabled() const;
+ /** @brief Returns the current Timer enablement type */
+ int getEnabled() const;
- /** @brief Enables / disables the timer.
- * <T> is an integral constant boolean
- */
- template <typename T> void setEnabled()
- {
- constexpr auto type = T::value ? SD_EVENT_ONESHOT : SD_EVENT_OFF;
- return setEnabled(type);
- }
+ /** @brief Enables / disables the timer.
+ * <T> is an integral constant boolean
+ */
+ template <typename T>
+ void setEnabled()
+ {
+ constexpr auto type = T::value ? SD_EVENT_ONESHOT : SD_EVENT_OFF;
+ return setEnabled(type);
+ }
- /** @brief Returns time remaining in usec before expiration
- * which is an offset to current steady clock
- */
- std::chrono::microseconds getRemaining() const;
+ /** @brief Returns time remaining in usec before expiration
+ * which is an offset to current steady clock
+ */
+ std::chrono::microseconds getRemaining() const;
- /** @brief Starts the timer with specified expiration value.
- * std::steady_clock is used for base time.
- *
- * @param[in] usec - Microseconds from the current time
- * before expiration.
- *
- * @return None.
- *
- * @error Throws exception
- */
- void start(std::chrono::microseconds usec);
+ /** @brief Starts the timer with specified expiration value.
+ * std::steady_clock is used for base time.
+ *
+ * @param[in] usec - Microseconds from the current time
+ * before expiration.
+ *
+ * @return None.
+ *
+ * @error Throws exception
+ */
+ void start(std::chrono::microseconds usec);
- /** @brief Gets the current time from steady clock */
- static std::chrono::microseconds getCurrentTime();
+ /** @brief Gets the current time from steady clock */
+ static std::chrono::microseconds getCurrentTime();
- private:
- /** @brief Reference to sd_event unique pointer */
- EventPtr& event;
+ private:
+ /** @brief Reference to sd_event unique pointer */
+ EventPtr& event;
- /** @brief event source */
- EventSourcePtr eventSource;
+ /** @brief event source */
+ EventSourcePtr eventSource;
- /** @brief Set to true when the timeoutHandler is called into */
- bool expire = false;
+ /** @brief Set to true when the timeoutHandler is called into */
+ bool expire = false;
- /** @brief Optional function to call on timer expiration
- * This is called from timeout handler.
- */
- std::function<void()> userCallBack;
+ /** @brief Optional function to call on timer expiration
+ * This is called from timeout handler.
+ */
+ std::function<void()> userCallBack;
- /** @brief Initializes the timer object with infinite
- * expiration time and sets up the callback handler
- *
- * @return None.
- *
- * @error Throws exception
- */
- void initialize();
+ /** @brief Initializes the timer object with infinite
+ * expiration time and sets up the callback handler
+ *
+ * @return None.
+ *
+ * @error Throws exception
+ */
+ void initialize();
- /** @brief Callback function when timer goes off
- *
- * @param[in] eventSource - Source of the event
- * @param[in] usec - time in microseconds
- * @param[in] userData - User data pointer
- *
- */
- static int timeoutHandler(sd_event_source* eventSource,
- uint64_t usec, void* userData);
+ /** @brief Callback function when timer goes off
+ *
+ * @param[in] eventSource - Source of the event
+ * @param[in] usec - time in microseconds
+ * @param[in] userData - User data pointer
+ *
+ */
+ static int timeoutHandler(sd_event_source* eventSource, uint64_t usec,
+ void* userData);
- /** @brief Enables / disables the timer
- *
- * @param[in] type - Timer type.
- * This implementation uses only SD_EVENT_OFF
- * and SD_EVENT_ONESHOT
- */
- void setEnabled(int type);
+ /** @brief Enables / disables the timer
+ *
+ * @param[in] type - Timer type.
+ * This implementation uses only SD_EVENT_OFF
+ * and SD_EVENT_ONESHOT
+ */
+ void setEnabled(int type);
};
} // namespace watchdog
diff --git a/watchdog.cpp b/watchdog.cpp
index 5ba0836..9e7ec23 100644
--- a/watchdog.cpp
+++ b/watchdog.cpp
@@ -1,6 +1,7 @@
+#include "watchdog.hpp"
+
#include <chrono>
#include <phosphor-logging/log.hpp>
-#include "watchdog.hpp"
namespace phosphor
{
namespace watchdog
@@ -10,9 +11,9 @@
using namespace phosphor::logging;
// systemd service to kick start a target.
-constexpr auto SYSTEMD_SERVICE = "org.freedesktop.systemd1";
-constexpr auto SYSTEMD_ROOT = "/org/freedesktop/systemd1";
-constexpr auto SYSTEMD_INTERFACE = "org.freedesktop.systemd1.Manager";
+constexpr auto SYSTEMD_SERVICE = "org.freedesktop.systemd1";
+constexpr auto SYSTEMD_ROOT = "/org/freedesktop/systemd1";
+constexpr auto SYSTEMD_INTERFACE = "org.freedesktop.systemd1.Manager";
void Watchdog::resetTimeRemaining(bool enableWatchdog)
{
@@ -40,8 +41,7 @@
else if (!this->enabled())
{
// Start ONESHOT timer. Timer handles all in usec
- auto usec = duration_cast<microseconds>(
- milliseconds(this->interval()));
+ auto usec = duration_cast<microseconds>(milliseconds(this->interval()));
// Update new expiration
timer.clearExpired();
@@ -51,7 +51,7 @@
timer.setEnabled<std::true_type>();
log<level::INFO>("watchdog: enabled and started",
- entry("INTERVAL=%llu", this->interval()));
+ entry("INTERVAL=%llu", this->interval()));
}
return WatchdogInherits::enabled(value);
@@ -67,17 +67,14 @@
if (timerEnabled())
{
// the one-shot timer does not expire yet
- auto expiry = duration_cast<milliseconds>(
- timer.getRemaining());
+ auto expiry = duration_cast<milliseconds>(timer.getRemaining());
// convert to msec per interface expectation.
- auto timeNow = duration_cast<milliseconds>(
- Timer::getCurrentTime());
+ auto timeNow = duration_cast<milliseconds>(Timer::getCurrentTime());
// Its possible that timer may have expired by now.
// So need to cross verify.
- timeRemain = (expiry > timeNow) ?
- (expiry - timeNow).count() : 0;
+ timeRemain = (expiry > timeNow) ? (expiry - timeNow).count() : 0;
}
return timeRemain;
}
@@ -119,20 +116,18 @@
if (target == actionTargets.end())
{
log<level::INFO>("watchdog: Timed out with no target",
- entry("ACTION=%s", convertForMessage(action).c_str()));
+ entry("ACTION=%s", convertForMessage(action).c_str()));
}
else
{
- auto method = bus.new_method_call(SYSTEMD_SERVICE,
- SYSTEMD_ROOT,
- SYSTEMD_INTERFACE,
- "StartUnit");
+ auto method = bus.new_method_call(SYSTEMD_SERVICE, SYSTEMD_ROOT,
+ SYSTEMD_INTERFACE, "StartUnit");
method.append(target->second);
method.append("replace");
log<level::INFO>("watchdog: Timed out",
- entry("ACTION=%s", convertForMessage(action).c_str()),
- entry("TARGET=%s", target->second.c_str()));
+ entry("ACTION=%s", convertForMessage(action).c_str()),
+ entry("TARGET=%s", target->second.c_str()));
bus.call_noreply(method);
}
@@ -146,14 +141,15 @@
if (fallback && (fallback->always || this->enabled()))
{
auto interval_ms = fallback->interval;
- auto interval_us = duration_cast<microseconds>(milliseconds(interval_ms));
+ auto interval_us =
+ duration_cast<microseconds>(milliseconds(interval_ms));
timer.clearExpired();
timer.start(interval_us);
timer.setEnabled<std::true_type>();
log<level::INFO>("watchdog: falling back",
- entry("INTERVAL=%llu", interval_ms));
+ entry("INTERVAL=%llu", interval_ms));
}
else if (timerEnabled())
{
@@ -168,4 +164,4 @@
}
} // namespace watchdog
-} // namepsace phosphor
+} // namespace phosphor
diff --git a/watchdog.hpp b/watchdog.hpp
index e28a751..ea419e7 100644
--- a/watchdog.hpp
+++ b/watchdog.hpp
@@ -1,11 +1,13 @@
#pragma once
+#include "timer.hpp"
+
#include <systemd/sd-event.h>
+
#include <experimental/optional>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/object.hpp>
#include <xyz/openbmc_project/State/Watchdog/server.hpp>
-#include "timer.hpp"
namespace phosphor
{
namespace watchdog
@@ -20,125 +22,123 @@
*/
class Watchdog : public WatchdogInherits
{
- public:
- Watchdog() = delete;
- ~Watchdog() = default;
- Watchdog(const Watchdog&) = delete;
- Watchdog& operator=(const Watchdog&) = delete;
- Watchdog(Watchdog&&) = delete;
- Watchdog& operator=(Watchdog &&) = delete;
+ public:
+ Watchdog() = delete;
+ ~Watchdog() = default;
+ Watchdog(const Watchdog&) = delete;
+ Watchdog& operator=(const Watchdog&) = delete;
+ Watchdog(Watchdog&&) = delete;
+ Watchdog& operator=(Watchdog&&) = delete;
- /** @brief Type used to hold the name of a systemd target.
- */
- using TargetName = std::string;
+ /** @brief Type used to hold the name of a systemd target.
+ */
+ using TargetName = std::string;
- /** @brief Type used to specify the parameters of a fallback watchdog
- */
- struct Fallback {
- Action action;
- uint64_t interval;
- bool always;
- };
+ /** @brief Type used to specify the parameters of a fallback watchdog
+ */
+ struct Fallback
+ {
+ Action action;
+ uint64_t interval;
+ bool always;
+ };
- /** @brief Constructs the Watchdog object
- *
- * @param[in] bus - DBus bus to attach to.
- * @param[in] objPath - Object path to attach to.
- * @param[in] event - reference to sd_event unique pointer
- * @param[in] actionTargets - map of systemd targets called on timeout
- * @param[in] fallback
- */
- Watchdog(sdbusplus::bus::bus& bus,
- const char* objPath,
- EventPtr& event,
- std::map<Action, TargetName>&& actionTargets =
- std::map<Action, TargetName>(),
- std::experimental::optional<Fallback>&&
- fallback = std::experimental::nullopt) :
- WatchdogInherits(bus, objPath),
- bus(bus),
- actionTargets(std::move(actionTargets)),
- fallback(std::move(fallback)),
- timer(event, std::bind(&Watchdog::timeOutHandler, this))
- {
- // We need to poke the enable mechanism to make sure that the timer
- // enters the fallback state if the fallback is always enabled.
- tryFallbackOrDisable();
- }
+ /** @brief Constructs the Watchdog object
+ *
+ * @param[in] bus - DBus bus to attach to.
+ * @param[in] objPath - Object path to attach to.
+ * @param[in] event - reference to sd_event unique pointer
+ * @param[in] actionTargets - map of systemd targets called on timeout
+ * @param[in] fallback
+ */
+ Watchdog(sdbusplus::bus::bus& bus, const char* objPath, EventPtr& event,
+ std::map<Action, TargetName>&& actionTargets =
+ std::map<Action, TargetName>(),
+ std::experimental::optional<Fallback>&& fallback =
+ std::experimental::nullopt) :
+ WatchdogInherits(bus, objPath),
+ bus(bus), actionTargets(std::move(actionTargets)),
+ fallback(std::move(fallback)),
+ timer(event, std::bind(&Watchdog::timeOutHandler, this))
+ {
+ // We need to poke the enable mechanism to make sure that the timer
+ // enters the fallback state if the fallback is always enabled.
+ tryFallbackOrDisable();
+ }
- /** @brief Resets the TimeRemaining to the configured Interval
- * Optionally enables the watchdog.
- *
- * @param[in] enableWatchdog - Should the call enable the watchdog
- */
- void resetTimeRemaining(bool enableWatchdog) override;
+ /** @brief Resets the TimeRemaining to the configured Interval
+ * Optionally enables the watchdog.
+ *
+ * @param[in] enableWatchdog - Should the call enable the watchdog
+ */
+ void resetTimeRemaining(bool enableWatchdog) override;
- /** @brief Since we are overriding the setter-enabled but not the
- * getter-enabled, we need to have this using in order to
- * allow passthrough usage of the getter-enabled.
- */
- using Base::Watchdog::enabled;
+ /** @brief Since we are overriding the setter-enabled but not the
+ * getter-enabled, we need to have this using in order to
+ * allow passthrough usage of the getter-enabled.
+ */
+ using Base::Watchdog::enabled;
- /** @brief Enable or disable watchdog
- * If a watchdog state is changed from disable to enable,
- * the watchdog timer is set with the default expiration
- * interval and it starts counting down.
- * If a watchdog is already enabled, setting @value to true
- * has no effect.
- *
- * @param[in] value - 'true' to enable. 'false' to disable
- *
- * @return : applied value if success, previous value otherwise
- */
- bool enabled(bool value) override;
+ /** @brief Enable or disable watchdog
+ * If a watchdog state is changed from disable to enable,
+ * the watchdog timer is set with the default expiration
+ * interval and it starts counting down.
+ * If a watchdog is already enabled, setting @value to true
+ * has no effect.
+ *
+ * @param[in] value - 'true' to enable. 'false' to disable
+ *
+ * @return : applied value if success, previous value otherwise
+ */
+ bool enabled(bool value) override;
- /** @brief Gets the remaining time before watchdog expires.
- *
- * @return 0 if watchdog is expired.
- * Remaining time in milliseconds otherwise.
- */
- uint64_t timeRemaining() const override;
+ /** @brief Gets the remaining time before watchdog expires.
+ *
+ * @return 0 if watchdog is expired.
+ * Remaining time in milliseconds otherwise.
+ */
+ uint64_t timeRemaining() const override;
- /** @brief Reset timer to expire after new timeout in milliseconds.
- *
- * @param[in] value - the time in milliseconds after which
- * the watchdog will expire
- *
- * @return: updated timeout value if watchdog is enabled.
- * 0 otherwise.
- */
- uint64_t timeRemaining(uint64_t value) override;
+ /** @brief Reset timer to expire after new timeout in milliseconds.
+ *
+ * @param[in] value - the time in milliseconds after which
+ * the watchdog will expire
+ *
+ * @return: updated timeout value if watchdog is enabled.
+ * 0 otherwise.
+ */
+ uint64_t timeRemaining(uint64_t value) override;
- /** @brief Tells if the referenced timer is expired or not */
- inline auto timerExpired() const
- {
- return timer.expired();
- }
+ /** @brief Tells if the referenced timer is expired or not */
+ inline auto timerExpired() const
+ {
+ return timer.expired();
+ }
- /** @brief Tells if the timer is running or not */
- inline bool timerEnabled() const
- {
- return timer.getEnabled() != SD_EVENT_OFF;
- }
+ /** @brief Tells if the timer is running or not */
+ inline bool timerEnabled() const
+ {
+ return timer.getEnabled() != SD_EVENT_OFF;
+ }
- private:
- /** @brief sdbusplus handle */
- sdbusplus::bus::bus& bus;
+ private:
+ /** @brief sdbusplus handle */
+ sdbusplus::bus::bus& bus;
- /** @brief Map of systemd units to be started when the timer expires */
- std::map<Action, TargetName> actionTargets;
+ /** @brief Map of systemd units to be started when the timer expires */
+ std::map<Action, TargetName> actionTargets;
- /** @brief Fallback timer options */
- std::experimental::optional<Fallback> fallback;
+ /** @brief Fallback timer options */
+ std::experimental::optional<Fallback> fallback;
- /** @brief Contained timer object */
- Timer timer;
+ /** @brief Contained timer object */
+ Timer timer;
- /** @brief Optional Callback handler on timer expirartion */
- void timeOutHandler();
+ /** @brief Optional Callback handler on timer expirartion */
+ void timeOutHandler();
- /** @brief Attempt to enter the fallback watchdog or disables it */
- void tryFallbackOrDisable();
+ /** @brief Attempt to enter the fallback watchdog or disables it */
+ void tryFallbackOrDisable();
};
} // namespace watchdog