Add .clang-format for automated style
Add a .clang-format style to enable automated style check to align code
format with rest of OpenBmc.
Change-Id: Ieace2b9135fa29a47be1aea21766a87b4e0b29b1
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/src/dbus_server.cpp b/src/dbus_server.cpp
index 53a2087..aba7694 100644
--- a/src/dbus_server.cpp
+++ b/src/dbus_server.cpp
@@ -19,16 +19,16 @@
*/
#include "dbus_server.hpp"
+
#include <xyz/openbmc_project/Common/File/error.hpp>
-
-DbusServer::DbusServer(LogManager& logManager, sdbusplus::bus::bus& bus, const char* path /*= HOSTLOGGER_DBUS_PATH*/)
-: server_inherit(bus, path),
- logManager_(logManager)
+DbusServer::DbusServer(LogManager& logManager, sdbusplus::bus::bus& bus,
+ const char* path /*= HOSTLOGGER_DBUS_PATH*/) :
+ server_inherit(bus, path),
+ logManager_(logManager)
{
}
-
void DbusServer::flush()
{
const int rc = logManager_.flush();
diff --git a/src/dbus_server.hpp b/src/dbus_server.hpp
index 1e6d47c..e058edf 100644
--- a/src/dbus_server.hpp
+++ b/src/dbus_server.hpp
@@ -21,12 +21,13 @@
#pragma once
#include "log_manager.hpp"
+
#include <xyz/openbmc_project/HostLogger/server.hpp>
/** @brief D-Bus interface name. */
#define HOSTLOGGER_DBUS_IFACE "xyz.openbmc_project.HostLogger"
/** @brief D-Bus path. */
-#define HOSTLOGGER_DBUS_PATH "/xyz/openbmc_project/HostLogger"
+#define HOSTLOGGER_DBUS_PATH "/xyz/openbmc_project/HostLogger"
/** @brief unique_ptr functor to release an event reference. */
struct EventDeleter
@@ -41,27 +42,29 @@
using EventPtr = std::unique_ptr<sd_event, EventDeleter>;
// Typedef for super class
-using server_inherit = sdbusplus::server::object_t<sdbusplus::xyz::openbmc_project::server::HostLogger>;
-
+using server_inherit = sdbusplus::server::object_t<
+ sdbusplus::xyz::openbmc_project::server::HostLogger>;
/** @class DbusServer
* @brief D-Bus service by host logger.
*/
-class DbusServer: public server_inherit
+class DbusServer : public server_inherit
{
-public:
+ public:
/** @brief Constructor.
*
* @param[in] logManager - log manager
* @param[in] bus - bus to attach to
- * @param[in] path - bath to attach at, optional, default is HOSTLOGGER_DBUS_PATH
+ * @param[in] path - bath to attach at, optional, default is
+ * HOSTLOGGER_DBUS_PATH
*/
- DbusServer(LogManager& logManager, sdbusplus::bus::bus& bus, const char* path = HOSTLOGGER_DBUS_PATH);
+ DbusServer(LogManager& logManager, sdbusplus::bus::bus& bus,
+ const char* path = HOSTLOGGER_DBUS_PATH);
// From server_inherit
void flush();
-private:
+ private:
/** @brief Log manager instance. */
LogManager& logManager_;
};
diff --git a/src/dbus_watch.cpp b/src/dbus_watch.cpp
index ca5118e..f97c33b 100644
--- a/src/dbus_watch.cpp
+++ b/src/dbus_watch.cpp
@@ -18,11 +18,13 @@
* limitations under the License.
*/
-#include "config.hpp"
#include "dbus_watch.hpp"
+
+#include "config.hpp"
+
+#include <chrono>
#include <set>
#include <string>
-#include <chrono>
// D-Bus path to the host state object
#define DBUS_HOST_OBJECT_PATH "/xyz/openbmc_project/state/host0"
@@ -31,25 +33,21 @@
// positive code is not an error in the systemd dbus implementation.
#define DBUS_RC_TO_ERR(c) (c = (c <= 0 ? -c : 0))
-
-DbusWatcher::DbusWatcher(LogManager& logManager, sdbusplus::bus::bus& bus)
-: logManager_(logManager),
- bus_(bus)
+DbusWatcher::DbusWatcher(LogManager& logManager, sdbusplus::bus::bus& bus) :
+ logManager_(logManager), bus_(bus)
{
}
-
int DbusWatcher::initialize()
{
int rc;
// Add IO callback for host's log stream socket
- rc = sd_event_add_io(bus_.get_event(), NULL,
- logManager_.getHostLogFd(),
+ rc = sd_event_add_io(bus_.get_event(), NULL, logManager_.getHostLogFd(),
EPOLLIN, &DbusWatcher::ioCallback, this);
- if (DBUS_RC_TO_ERR(rc)) {
- fprintf(stderr, "Unable to add IO handler: %i %s\n",
- rc, strerror(rc));
+ if (DBUS_RC_TO_ERR(rc))
+ {
+ fprintf(stderr, "Unable to add IO handler: %i %s\n", rc, strerror(rc));
return rc;
}
@@ -62,71 +60,70 @@
return rc;
}
-
void DbusWatcher::registerEventHandler()
{
conds_["xyz.openbmc_project.State.Host"] = {
.property = "RequestedHostTransition",
- .values = {
- "xyz.openbmc_project.State.Host.Transition.On"
- }
- };
+ .values = {"xyz.openbmc_project.State.Host.Transition.On"}};
conds_["xyz.openbmc_project.State.OperatingSystem.Status"] = {
.property = "OperatingSystemState",
- .values = {
- "xyz.openbmc_project.State.OperatingSystem.Status.OSStatus.BootComplete",
- "xyz.openbmc_project.State.OperatingSystem.Status.OSStatus.Inactive"
- }
- };
- for (auto& cond: conds_) {
- cond.second.match = std::make_unique<sdbusplus::bus::match_t>(bus_,
- sdbusplus::bus::match::rules::propertiesChanged(
- DBUS_HOST_OBJECT_PATH, cond.first),
- [this](auto& msg){ this->hostStateHandler(msg); });
+ .values = {"xyz.openbmc_project.State.OperatingSystem.Status.OSStatus."
+ "BootComplete",
+ "xyz.openbmc_project.State.OperatingSystem.Status.OSStatus."
+ "Inactive"}};
+ for (auto& cond : conds_)
+ {
+ cond.second.match = std::make_unique<sdbusplus::bus::match_t>(
+ bus_,
+ sdbusplus::bus::match::rules::propertiesChanged(
+ DBUS_HOST_OBJECT_PATH, cond.first),
+ [this](auto& msg) { this->hostStateHandler(msg); });
}
}
-
int DbusWatcher::registerTimerHandler()
{
int rc;
sd_event_source* ev = NULL;
- rc = sd_event_add_time(bus_.get_event(), &ev, CLOCK_MONOTONIC,
- UINT64_MAX, 0, &DbusWatcher::timerCallback, this);
- if (DBUS_RC_TO_ERR(rc)) {
- fprintf(stderr, "Unable to add timer handler: %i %s\n", rc, strerror(rc));
+ rc = sd_event_add_time(bus_.get_event(), &ev, CLOCK_MONOTONIC, UINT64_MAX,
+ 0, &DbusWatcher::timerCallback, this);
+ if (DBUS_RC_TO_ERR(rc))
+ {
+ fprintf(stderr, "Unable to add timer handler: %i %s\n", rc,
+ strerror(rc));
return rc;
}
rc = sd_event_source_set_enabled(ev, SD_EVENT_ON);
- if (DBUS_RC_TO_ERR(rc)) {
- fprintf(stderr, "Unable to enable timer handler: %i %s\n", rc, strerror(rc));
+ if (DBUS_RC_TO_ERR(rc))
+ {
+ fprintf(stderr, "Unable to enable timer handler: %i %s\n", rc,
+ strerror(rc));
return rc;
}
return setupTimer(ev);
}
-
int DbusWatcher::setupTimer(sd_event_source* event)
{
// Get the current time and add the delta (flush period)
using namespace std::chrono;
auto now = steady_clock::now().time_since_epoch();
hours timeOut(loggerConfig.flushPeriod);
- auto expireTime = duration_cast<microseconds>(now) +
- duration_cast<microseconds>(timeOut);
+ auto expireTime =
+ duration_cast<microseconds>(now) + duration_cast<microseconds>(timeOut);
- //Set the time
+ // Set the time
int rc = sd_event_source_set_time(event, expireTime.count());
if (DBUS_RC_TO_ERR(rc))
- fprintf(stderr, "Unable to set timer handler: %i %s\n", rc, strerror(rc));
+ fprintf(stderr, "Unable to set timer handler: %i %s\n", rc,
+ strerror(rc));
return rc;
}
-
void DbusWatcher::hostStateHandler(sdbusplus::message::message& msg)
{
std::map<std::string, sdbusplus::message::variant<std::string>> properties;
@@ -136,11 +133,15 @@
bool needFlush = false;
const auto itc = conds_.find(interface);
- if (itc != conds_.end()) {
+ if (itc != conds_.end())
+ {
const auto itp = properties.find(itc->second.property);
- if (itp != properties.end()) {
- const auto& propVal = sdbusplus::message::variant_ns::get<std::string>(itp->second);
- needFlush = itc->second.values.find(propVal) != itc->second.values.end();
+ if (itp != properties.end())
+ {
+ const auto& propVal =
+ sdbusplus::message::variant_ns::get<std::string>(itp->second);
+ needFlush =
+ itc->second.values.find(propVal) != itc->second.values.end();
}
}
@@ -148,16 +149,16 @@
logManager_.flush();
}
-
-int DbusWatcher::ioCallback(sd_event_source* /*event*/, int /*fd*/, uint32_t /*revents*/, void* data)
+int DbusWatcher::ioCallback(sd_event_source* /*event*/, int /*fd*/,
+ uint32_t /*revents*/, void* data)
{
DbusWatcher* instance = static_cast<DbusWatcher*>(data);
instance->logManager_.handleHostLog();
return 0;
}
-
-int DbusWatcher::timerCallback(sd_event_source* event, uint64_t /*usec*/, void* data)
+int DbusWatcher::timerCallback(sd_event_source* event, uint64_t /*usec*/,
+ void* data)
{
DbusWatcher* instance = static_cast<DbusWatcher*>(data);
instance->logManager_.flush();
diff --git a/src/dbus_watch.hpp b/src/dbus_watch.hpp
index 1f5201f..6a284b4 100644
--- a/src/dbus_watch.hpp
+++ b/src/dbus_watch.hpp
@@ -22,20 +22,17 @@
#include "log_manager.hpp"
-#include <set>
#include <map>
-#include <string>
-
#include <sdbusplus/bus/match.hpp>
-
-
+#include <set>
+#include <string>
/** @class DbusServer
* @brief D-Bus service by host logger.
*/
class DbusWatcher
{
-public:
+ public:
/** @brief Constructor.
*
* @param[in] logManager - log manager
@@ -49,7 +46,7 @@
*/
int initialize();
-private:
+ private:
/** @brief Register D-Bus event handler. */
void registerEventHandler();
@@ -73,19 +70,21 @@
*/
void hostStateHandler(sdbusplus::message::message& msg);
- /** @brief D-Bus IO callback used to handle incoming data on the opened file.
- * See sd_event_io_handler_t for details.
+ /** @brief D-Bus IO callback used to handle incoming data on the opened
+ * file. See sd_event_io_handler_t for details.
*/
- static int ioCallback(sd_event_source* event, int fd, uint32_t revents, void* data);
+ static int ioCallback(sd_event_source* event, int fd, uint32_t revents,
+ void* data);
/** @brief D-Bus timer callback used to flush log store.
* See sd_event_add_time for details.
*/
static int timerCallback(sd_event_source* event, uint64_t usec, void* data);
-private:
+ private:
/** @struct FlushCondition
- * @brief Describes flush conditions for log manager based on host state event.
+ * @brief Describes flush conditions for log manager based on host state
+ * event.
*/
struct FlushCondition
{
@@ -97,7 +96,7 @@
std::unique_ptr<sdbusplus::bus::match_t> match;
};
-private:
+ private:
/** @brief Log manager instance. */
LogManager& logManager_;
diff --git a/src/log_manager.cpp b/src/log_manager.cpp
index b78b7e8..506e586 100644
--- a/src/log_manager.cpp
+++ b/src/log_manager.cpp
@@ -18,68 +18,75 @@
* limitations under the License.
*/
-#include "config.hpp"
#include "log_manager.hpp"
-#include <set>
-#include <vector>
-#include <cstring>
-#include <unistd.h>
+#include "config.hpp"
+
#include <dirent.h>
+#include <sys/ioctl.h>
#include <sys/socket.h>
-#include <sys/un.h>
#include <sys/stat.h>
#include <sys/types.h>
-#include <sys/ioctl.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+#include <cstring>
+#include <set>
+#include <vector>
// Path to the Unix Domain socket file used to read host's logs
-#define HOSTLOG_SOCKET_PATH "\0obmc-console"
+#define HOSTLOG_SOCKET_PATH "\0obmc-console"
// Number of connection attempts
#define HOSTLOG_SOCKET_ATTEMPTS 60
// Pause between connection attempts in seconds
-#define HOSTLOG_SOCKET_PAUSE 1
+#define HOSTLOG_SOCKET_PAUSE 1
// Max buffer size to read from socket
-#define MAX_SOCKET_BUFFER_SIZE 512
+#define MAX_SOCKET_BUFFER_SIZE 512
-
-LogManager::LogManager()
-: fd_(-1)
+LogManager::LogManager() : fd_(-1)
{
}
-
LogManager::~LogManager()
{
closeHostLog();
}
-
int LogManager::openHostLog()
{
int rc;
- do {
+ do
+ {
// Create socket
fd_ = socket(AF_UNIX, SOCK_STREAM, 0);
- if (fd_ == -1) {
+ if (fd_ == -1)
+ {
rc = errno;
- fprintf(stderr, "Unable to create socket: error [%i] %s\n", rc, strerror(rc));
+ fprintf(stderr, "Unable to create socket: error [%i] %s\n", rc,
+ strerror(rc));
break;
}
// Set non-blocking mode for socket
int opt = 1;
rc = ioctl(fd_, FIONBIO, &opt);
- if (rc != 0) {
+ if (rc != 0)
+ {
rc = errno;
- fprintf(stderr, "Unable to set non-blocking mode for log socket: error [%i] %s\n", rc, strerror(rc));
+ fprintf(stderr,
+ "Unable to set non-blocking mode for log socket: error "
+ "[%i] %s\n",
+ rc, strerror(rc));
break;
}
- sockaddr_un sa = { 0 };
+ sockaddr_un sa = {0};
sa.sun_family = AF_UNIX;
- constexpr int min_path = sizeof(HOSTLOG_SOCKET_PATH) < sizeof(sa.sun_path) ?
- sizeof(HOSTLOG_SOCKET_PATH) : sizeof(sa.sun_path);
+ constexpr int min_path =
+ sizeof(HOSTLOG_SOCKET_PATH) < sizeof(sa.sun_path)
+ ? sizeof(HOSTLOG_SOCKET_PATH)
+ : sizeof(sa.sun_path);
memcpy(&sa.sun_path, HOSTLOG_SOCKET_PATH, min_path);
// Connect to host's log stream via socket.
@@ -87,16 +94,21 @@
// we have a dependency on it written in the systemd unit file, but
// we can't guarantee that the socket is initialized at the moment.
rc = -1;
- for (int attempt = 0; rc != 0 && attempt < HOSTLOG_SOCKET_ATTEMPTS; ++attempt) {
- rc = connect(fd_, reinterpret_cast<const sockaddr*>(&sa), sizeof(sa));
+ for (int attempt = 0; rc != 0 && attempt < HOSTLOG_SOCKET_ATTEMPTS;
+ ++attempt)
+ {
+ rc = connect(fd_, reinterpret_cast<const sockaddr*>(&sa),
+ sizeof(sa));
sleep(HOSTLOG_SOCKET_PAUSE);
}
- if (rc < 0) {
+ if (rc < 0)
+ {
rc = errno;
- fprintf(stderr, "Unable to connect to host log socket: error [%i] %s\n", rc, strerror(rc));
+ fprintf(stderr,
+ "Unable to connect to host log socket: error [%i] %s\n", rc,
+ strerror(rc));
}
- }
- while (false);
+ } while (false);
if (rc != 0)
closeHostLog();
@@ -104,22 +116,20 @@
return rc;
}
-
void LogManager::closeHostLog()
{
- if (fd_ != -1) {
+ if (fd_ != -1)
+ {
::close(fd_);
fd_ = -1;
}
}
-
int LogManager::getHostLogFd() const
{
return fd_;
}
-
int LogManager::handleHostLog()
{
int rc = 0;
@@ -127,7 +137,8 @@
size_t readLen = MAX_SOCKET_BUFFER_SIZE;
// Read all existing data from log stream
- while (rc == 0 && readLen != 0) {
+ while (rc == 0 && readLen != 0)
+ {
rc = readHostLog(&buff[0], buff.size(), readLen);
if (rc == 0 && readLen != 0)
storage_.parse(&buff[0], readLen);
@@ -136,7 +147,6 @@
return rc;
}
-
int LogManager::flush()
{
int rc;
@@ -160,39 +170,47 @@
return 0;
}
-
-int LogManager::readHostLog(char* buffer, size_t bufferLen, size_t& readLen) const
+int LogManager::readHostLog(char* buffer, size_t bufferLen,
+ size_t& readLen) const
{
int rc = 0;
const ssize_t rsz = ::read(fd_, buffer, bufferLen);
if (rsz >= 0)
readLen = static_cast<size_t>(rsz);
- else {
+ else
+ {
readLen = 0;
- if (errno != EAGAIN && errno != EWOULDBLOCK) {
+ if (errno != EAGAIN && errno != EWOULDBLOCK)
+ {
rc = errno;
- fprintf(stderr, "Unable to read host log: error [%i] %s\n", rc, strerror(rc));
+ fprintf(stderr, "Unable to read host log: error [%i] %s\n", rc,
+ strerror(rc));
}
}
return rc;
}
-
std::string LogManager::prepareLogPath() const
{
// Create path for logs
- if (::access(loggerConfig.path, F_OK) != 0) {
+ if (::access(loggerConfig.path, F_OK) != 0)
+ {
const std::string logPath(loggerConfig.path);
const size_t len = logPath.length();
size_t pos = 0;
- while (pos < len - 1) {
+ while (pos < len - 1)
+ {
pos = logPath.find('/', pos + 1);
const std::string createPath = logPath.substr(0, pos);
- if (::mkdir(createPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0 && errno != EEXIST) {
+ if (::mkdir(createPath.c_str(),
+ S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0 &&
+ errno != EEXIST)
+ {
const int rc = errno;
- fprintf(stderr, "Unable to create dir %s: error [%i] %s\n", createPath.c_str(), rc, strerror(rc));
+ fprintf(stderr, "Unable to create dir %s: error [%i] %s\n",
+ createPath.c_str(), rc, strerror(rc));
return std::string();
}
}
@@ -201,17 +219,16 @@
// Construct log file name
time_t ts;
time(&ts);
- tm lt = { 0 };
+ tm lt = {0};
localtime_r(&ts, <);
char fileName[64];
snprintf(fileName, sizeof(fileName), "/host_%i%02i%02i_%02i%02i%02i.log.gz",
- lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday,
- lt.tm_hour, lt.tm_min, lt.tm_sec);
+ lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday, lt.tm_hour,
+ lt.tm_min, lt.tm_sec);
return std::string(loggerConfig.path) + fileName;
}
-
int LogManager::rotateLogFiles() const
{
if (loggerConfig.rotationLimit == 0)
@@ -222,13 +239,16 @@
// Get file list to std::set
std::set<std::string> logFiles;
DIR* dh = opendir(loggerConfig.path);
- if (!dh) {
+ if (!dh)
+ {
rc = errno;
- fprintf(stderr, "Unable to open directory %s: error [%i] %s\n", loggerConfig.path, rc, strerror(rc));
+ fprintf(stderr, "Unable to open directory %s: error [%i] %s\n",
+ loggerConfig.path, rc, strerror(rc));
return rc;
}
- dirent *dir;
- while ((dir = readdir(dh))) {
+ dirent* dir;
+ while ((dir = readdir(dh)))
+ {
if (dir->d_type != DT_DIR)
logFiles.insert(dir->d_name);
}
@@ -238,14 +258,18 @@
// The sorted array of names (std::set) will contain the oldest file on the
// top.
// Remove oldest files.
- int filesToRemove = static_cast<int>(logFiles.size()) - loggerConfig.rotationLimit;
- while (rc == 0 && --filesToRemove >= 0) {
+ int filesToRemove =
+ static_cast<int>(logFiles.size()) - loggerConfig.rotationLimit;
+ while (rc == 0 && --filesToRemove >= 0)
+ {
std::string fileToRemove = loggerConfig.path;
fileToRemove += '/';
fileToRemove += *logFiles.begin();
- if (::unlink(fileToRemove.c_str()) == -1) {
+ if (::unlink(fileToRemove.c_str()) == -1)
+ {
rc = errno;
- fprintf(stderr, "Unable to delete file %s: error [%i] %s\n", fileToRemove.c_str(), rc, strerror(rc));
+ fprintf(stderr, "Unable to delete file %s: error [%i] %s\n",
+ fileToRemove.c_str(), rc, strerror(rc));
}
logFiles.erase(fileToRemove);
}
diff --git a/src/log_manager.hpp b/src/log_manager.hpp
index 5dac0f9..3513dac 100644
--- a/src/log_manager.hpp
+++ b/src/log_manager.hpp
@@ -22,14 +22,13 @@
#include "log_storage.hpp"
-
/** @class LogManager
* @brief Log manager.
* All functions within this class are not thread-safe.
*/
class LogManager
{
-public:
+ public:
/** @brief Constructor. */
LogManager();
@@ -43,11 +42,12 @@
int openHostLog();
/** @brief Close the host's log stream.
- */
+ */
void closeHostLog();
/** @brief Get file descriptor by host's log stream.
- * Descriptor can be used to register it in an external polling manager.
+ * Descriptor can be used to register it in an external polling
+ * manager.
*
* @return file descriptor (actually it is an opened socket)
*/
@@ -66,7 +66,7 @@
*/
int flush();
-private:
+ private:
/** @brief Read incoming data from host's log stream.
*
* @param[out] buffer - buffer to write incoming data
@@ -98,7 +98,7 @@
*/
int rotateLogFiles() const;
-private:
+ private:
/** @brief Log storage. */
LogStorage storage_;
/** @brief File descriptor of the input log stream. */
diff --git a/src/log_storage.cpp b/src/log_storage.cpp
index 1ada1c3..96b0b12 100644
--- a/src/log_storage.cpp
+++ b/src/log_storage.cpp
@@ -18,28 +18,27 @@
* limitations under the License.
*/
-#include "config.hpp"
#include "log_storage.hpp"
-#include <sys/stat.h>
+#include "config.hpp"
+
#include <fcntl.h>
-#include <unistd.h>
#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
-
-LogStorage::LogStorage()
-: last_complete_(true)
+LogStorage::LogStorage() : last_complete_(true)
{
}
-
void LogStorage::parse(const char* data, size_t len)
{
// Split log stream to separate messages.
// Stream may not be ended with EOL, so we handle this situation by
// last_complete_ flag.
size_t pos = 0;
- while (pos < len) {
+ while (pos < len)
+ {
// Search for EOL ('\n')
size_t eol = pos;
while (eol < len && data[eol] != '\n')
@@ -61,17 +60,19 @@
}
}
-
void LogStorage::append(const char* msg, size_t len)
{
- if (!last_complete_) {
+ if (!last_complete_)
+ {
// The last message is incomplete, add msg as part of it
- if (!messages_.empty()) {
+ if (!messages_.empty())
+ {
Message& last_msg = *messages_.rbegin();
last_msg.text.append(msg, len);
}
}
- else {
+ else
+ {
Message new_msg;
time(&new_msg.timeStamp);
new_msg.text.assign(msg, len);
@@ -80,47 +81,46 @@
}
}
-
void LogStorage::clear()
{
messages_.clear();
last_complete_ = true;
}
-
bool LogStorage::empty() const
{
return messages_.empty();
}
-
int LogStorage::write(const char* fileName) const
{
int rc = 0;
- if (empty()) {
+ if (empty())
+ {
printf("No messages to write\n");
return 0;
}
const gzFile fd = gzopen(fileName, "w");
- if (fd == Z_NULL) {
+ if (fd == Z_NULL)
+ {
rc = errno;
- fprintf(stderr, "Unable to open file %s: error [%i] %s\n",
- fileName, rc, strerror(rc));
+ fprintf(stderr, "Unable to open file %s: error [%i] %s\n", fileName, rc,
+ strerror(rc));
return rc;
}
// Write full datetime stamp as the first record
const time_t& logStartTime = messages_.begin()->timeStamp;
- tm localTime = { 0 };
+ tm localTime = {0};
localtime_r(&logStartTime, &localTime);
char msgText[64];
snprintf(msgText, sizeof(msgText),
">>> Log collection started at %02i.%02i.%i %02i:%02i:%02i",
localTime.tm_mday, localTime.tm_mon + 1, localTime.tm_year + 1900,
localTime.tm_hour, localTime.tm_min, localTime.tm_sec);
- const Message startMsg = { logStartTime, msgText };
+ const Message startMsg = {logStartTime, msgText};
rc |= write(fd, startMsg);
// Write messages
@@ -134,20 +134,18 @@
return rc;
}
-
int LogStorage::write(gzFile fd, const Message& msg) const
{
// Convert timestamp to local time
- tm localTime = { 0 };
+ tm localTime = {0};
localtime_r(&msg.timeStamp, &localTime);
// Write message to the file
- const int rc = gzprintf(fd, "[ %02i:%02i:%02i ]: %s\n",
- localTime.tm_hour,
- localTime.tm_min,
- localTime.tm_sec,
- msg.text.c_str());
- if (rc <= 0) {
+ const int rc =
+ gzprintf(fd, "[ %02i:%02i:%02i ]: %s\n", localTime.tm_hour,
+ localTime.tm_min, localTime.tm_sec, msg.text.c_str());
+ if (rc <= 0)
+ {
fprintf(stderr, "Unable to write file: error [%i]\n", -rc);
return EIO;
}
@@ -155,19 +153,22 @@
return 0;
}
-
void LogStorage::shrink()
{
- if (loggerConfig.storageSizeLimit) {
- while (messages_.size() > static_cast<size_t>(loggerConfig.storageSizeLimit))
+ if (loggerConfig.storageSizeLimit)
+ {
+ while (messages_.size() >
+ static_cast<size_t>(loggerConfig.storageSizeLimit))
messages_.pop_front();
}
- if (loggerConfig.storageTimeLimit) {
+ if (loggerConfig.storageTimeLimit)
+ {
// Get time for N hours ago
time_t oldestTimeStamp;
time(&oldestTimeStamp);
oldestTimeStamp -= loggerConfig.storageTimeLimit * 60 * 60;
- while (!messages_.empty() && messages_.begin()->timeStamp < oldestTimeStamp)
+ while (!messages_.empty() &&
+ messages_.begin()->timeStamp < oldestTimeStamp)
messages_.pop_front();
}
}
diff --git a/src/log_storage.hpp b/src/log_storage.hpp
index b2a6271..550afd9 100644
--- a/src/log_storage.hpp
+++ b/src/log_storage.hpp
@@ -20,11 +20,11 @@
#pragma once
+#include <zlib.h>
+
#include <ctime>
#include <list>
#include <string>
-#include <zlib.h>
-
/** @class LogStorage
* @brief Log storage implementation.
@@ -32,7 +32,7 @@
*/
class LogStorage
{
-public:
+ public:
/** @brief Constructor. */
LogStorage();
@@ -60,7 +60,7 @@
*/
int write(const char* fileName) const;
-private:
+ private:
/** @struct Message
* @brief Represent log message (single line from host log).
*/
@@ -91,7 +91,7 @@
/** @brief Shrink storage by removing oldest messages. */
void shrink();
-private:
+ private:
/** @brief List of messages. */
std::list<Message> messages_;
/** @brief Flag to indicate that the last message is incomplete. */
diff --git a/src/main.cpp b/src/main.cpp
index 7f58ef0..89b4f58 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -22,21 +22,19 @@
#include "dbus_server.hpp"
#include "dbus_watch.hpp"
#include "log_manager.hpp"
+
#include <getopt.h>
+
+#include <climits>
#include <cstdio>
#include <cstdlib>
-#include <climits>
-
// Global logger configuration instance
-Config loggerConfig = {
- .path = LOG_OUTPUT_PATH,
- .storageSizeLimit = LOG_STORAGE_SIZE_LIMIT,
- .storageTimeLimit = LOG_STORAGE_TIME_LIMIT,
- .flushPeriod = LOG_FLUSH_PERIOD,
- .rotationLimit = LOG_ROTATION_LIMIT
-};
-
+Config loggerConfig = {.path = LOG_OUTPUT_PATH,
+ .storageSizeLimit = LOG_STORAGE_SIZE_LIMIT,
+ .storageTimeLimit = LOG_STORAGE_TIME_LIMIT,
+ .flushPeriod = LOG_FLUSH_PERIOD,
+ .rotationLimit = LOG_ROTATION_LIMIT};
/** @brief Print title with version info. */
static void printTitle()
@@ -44,7 +42,6 @@
printf("Host logger service " PACKAGE_VERSION ".\n");
}
-
/** @brief Print help usage info.
*
* @param[in] app - application's file name
@@ -54,29 +51,29 @@
printTitle();
printf("Copyright (c) 2018 YADRO.\n");
printf("Usage: %s [options]\n", app);
- printf("Options (defaults are specified in brackets):\n"
- " -p, --path=PATH Path used to store logs [%s]\n"
- "Intermediate storage buffer capacity setup:\n"
- " -s, --szlimit=N Store up to N last messages [%i], 0=unlimited\n"
- " -t, --tmlimit=N Store messages for last N hours [%i], 0=unlimited\n"
- "Flush storage buffer policy:\n"
- " -f, --flush=N Flush logs every N hours [%i]\n"
- " If this option is set to 0 flush will be called at\n"
- " every host state change event from D-Bus.\n"
- "Log files rotation policy:\n"
- " -r, --rotate=N Store up to N files in the log directory [%i],\n"
- " 0=unlimited\n"
- "Common options:\n"
- " -v, --version Print version and exit\n"
- " -h, --help Print this help and exit\n",
- loggerConfig.path,
- loggerConfig.storageSizeLimit,
- loggerConfig.storageTimeLimit,
- loggerConfig.flushPeriod,
- loggerConfig.rotationLimit);
+ printf(
+ "Options (defaults are specified in brackets):\n"
+ " -p, --path=PATH Path used to store logs [%s]\n"
+ "Intermediate storage buffer capacity setup:\n"
+ " -s, --szlimit=N Store up to N last messages [%i], 0=unlimited\n"
+ " -t, --tmlimit=N Store messages for last N hours [%i], "
+ "0=unlimited\n"
+ "Flush storage buffer policy:\n"
+ " -f, --flush=N Flush logs every N hours [%i]\n"
+ " If this option is set to 0 flush will be called "
+ "at\n"
+ " every host state change event from D-Bus.\n"
+ "Log files rotation policy:\n"
+ " -r, --rotate=N Store up to N files in the log directory [%i],\n"
+ " 0=unlimited\n"
+ "Common options:\n"
+ " -v, --version Print version and exit\n"
+ " -h, --help Print this help and exit\n",
+ loggerConfig.path, loggerConfig.storageSizeLimit,
+ loggerConfig.storageTimeLimit, loggerConfig.flushPeriod,
+ loggerConfig.rotationLimit);
}
-
/** @brief Get numeric positive value from string argument.
*
* @param[in] param - parameter name
@@ -88,19 +85,20 @@
{
char* ep = nullptr;
const unsigned long val = strtoul(arg, &ep, 0);
- if (val > INT_MAX || !ep || ep == arg || *ep != 0) {
- fprintf(stderr, "Invalid %s param: %s, expected 0<=N<=%i\n",
- param, arg, INT_MAX);
+ if (val > INT_MAX || !ep || ep == arg || *ep != 0)
+ {
+ fprintf(stderr, "Invalid %s param: %s, expected 0<=N<=%i\n", param, arg,
+ INT_MAX);
return -1;
}
return static_cast<int>(val);
}
-
/** @brief Application entry point. */
-int main(int argc, char *argv[])
+int main(int argc, char* argv[])
{
int opt_val;
+ // clang-format off
const struct option opts[] = {
{ "path", required_argument, 0, 'p' },
{ "szlimit", required_argument, 0, 's' },
@@ -111,34 +109,45 @@
{ "help", no_argument, 0, 'h' },
{ 0, 0, 0, 0 }
};
+ // clang-format on
opterr = 0;
- while ((opt_val = getopt_long(argc, argv, "p:s:t:f:r:vh", opts, NULL)) != -1) {
- switch (opt_val) {
+ while ((opt_val = getopt_long(argc, argv, "p:s:t:f:r:vh", opts, NULL)) !=
+ -1)
+ {
+ switch (opt_val)
+ {
case 'p':
loggerConfig.path = optarg;
- if (*loggerConfig.path != '/') {
- fprintf(stderr, "Invalid directory: %s, expected absolute path\n", loggerConfig.path);
+ if (*loggerConfig.path != '/')
+ {
+ fprintf(stderr,
+ "Invalid directory: %s, expected absolute path\n",
+ loggerConfig.path);
return EXIT_FAILURE;
}
break;
case 's':
- loggerConfig.storageSizeLimit = getNumericArg(opts[optind - 1].name, optarg);
+ loggerConfig.storageSizeLimit =
+ getNumericArg(opts[optind - 1].name, optarg);
if (loggerConfig.storageSizeLimit < 0)
return EXIT_FAILURE;
break;
case 't':
- loggerConfig.storageTimeLimit = getNumericArg(opts[optind - 1].name, optarg);
+ loggerConfig.storageTimeLimit =
+ getNumericArg(opts[optind - 1].name, optarg);
if (loggerConfig.storageTimeLimit < 0)
return EXIT_FAILURE;
break;
case 'f':
- loggerConfig.flushPeriod = getNumericArg(opts[optind - 1].name, optarg);
+ loggerConfig.flushPeriod =
+ getNumericArg(opts[optind - 1].name, optarg);
if (loggerConfig.flushPeriod < 0)
return EXIT_FAILURE;
break;
case 'r':
- loggerConfig.rotationLimit = getNumericArg(opts[optind - 1].name, optarg);
+ loggerConfig.rotationLimit =
+ getNumericArg(opts[optind - 1].name, optarg);
if (loggerConfig.rotationLimit < 0)
return EXIT_FAILURE;
break;
@@ -166,7 +175,8 @@
sdbusplus::bus::bus bus = sdbusplus::bus::new_default();
sd_event* event = nullptr;
rc = sd_event_default(&event);
- if (rc < 0) {
+ if (rc < 0)
+ {
fprintf(stderr, "Error occurred during the sd_event_default: %i\n", rc);
return EXIT_FAILURE;
}