Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:Added the periodically clearing serverlog function #2829

Merged
merged 10 commits into from
Aug 8, 2024

Conversation

XiaoLiang2333
Copy link
Contributor

@XiaoLiang2333 XiaoLiang2333 commented Jul 26, 2024

#2811
Configure the log-retention-time field in pika.conf. Serverlogs that exceed this time period are cleared

Summary by CodeRabbit

  • New Features

    • Introduced a configuration option for log retention time, enhancing log management capabilities.
    • Added methods for targeted log purging, allowing more precise control over server and binlog file retention.
  • Bug Fixes

    • Improved server performance with detailed log purging logic based on specified retention periods.

Copy link

coderabbitai bot commented Jul 26, 2024

Walkthrough

The recent updates introduce a log retention feature in the Pika server's configuration, enabling automatic management of log files based on a specified period. This enhancement prevents excessive disk usage. The log purging functionalities have been refined, with methods specifically separated for server logs and binary logs, promoting clearer and more efficient log handling throughout the system.

Changes

Files Change Summary
conf/pika.conf Added new configuration option log-retention-time to manage log file retention (default 7 days).
include/pika_conf.h Introduced new member variable log_retention_time_ and method log_retention_time() in PikaConf class for access.
src/pika_server.cc Replaced AutoPurge() with AutoBinlogPurge() and AutoServerlogPurge() in PikaServer class for clearer log handling; implemented logic for purging server logs based on retention time.
src/pika_conf.cc Added log-retention-time parameter to Load method with validation for non-negative values.

Poem

In the garden of logs, we tidy and sweep,
Retention time set, our storage will keep.
A hop for the server, a leap for the day,
With purging so clear, we dance and we play!
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the ✏️ Feature New feature or request label Jul 26, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (3)
src/pika_server.cc (3)

1216-1218: Consider logging when retention time is not set.

When retention_time is less than or equal to 0, consider logging a message to indicate that log purging is disabled.

  if (retention_time <= 0) {
+    LOG(INFO) << "Log purging is disabled as retention time is not set.";
    return;
  }

1225-1227: Handle potential errors in GetChildren.

The method should handle potential errors when retrieving the list of log files. Consider logging an error message if GetChildren fails.

  if (pstd::GetChildren(log_path, log_files) != 0) {
+    LOG(ERROR) << "Failed to retrieve log files from " << log_path;
    return;
  }

1247-1250: Handle potential errors in date extraction.

The method should handle potential errors when extracting the date and time from the log filenames. Consider logging an error message if the extraction fails.

  if (date_pos == std::string::npos || date_pos + 16 > file.length()) {
+    LOG(ERROR) << "Failed to extract date and time from log filename: " << file;
    continue;
  }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 394f517 and 0ab1a51.

Files selected for processing (4)
  • conf/pika.conf (1 hunks)
  • include/pika_conf.h (2 hunks)
  • include/pika_server.h (1 hunks)
  • src/pika_server.cc (2 hunks)
Files skipped from review due to trivial changes (1)
  • conf/pika.conf
Additional comments not posted (10)
include/pika_server.h (2)

516-516: Method AutoBinlogPurge looks good.

The method AutoBinlogPurge has been correctly added and is expected to handle the purging of binary logs.


517-517: Method AutoServerlogPurge looks good.

The method AutoServerlogPurge has been correctly added and is expected to handle the purging of server logs.

include/pika_conf.h (2)

80-83: Method log_retention_time looks good.

The method log_retention_time has been correctly added and ensures thread-safe access to the log_retention_time_ variable.


911-911: Member variable log_retention_time_ looks good.

The member variable log_retention_time_ has been correctly added to store the log retention time configuration.

src/pika_server.cc (6)

1088-1091: LGTM! But verify the new method calls.

The integration of AutoServerlogPurge and AutoBinlogPurge within DoTimingTask looks good.

However, ensure that these methods are correctly implemented and tested.


1211-1212: LGTM! But verify DoSameThingEveryDB functionality.

The AutoBinlogPurge method looks good.

However, ensure that DoSameThingEveryDB correctly handles the purging of binlogs.


1213-1215: Ensure log_retention_time is correctly configured.

The method relies on log_retention_time from the configuration. Ensure this value is correctly set and validated.


1221-1223: Ensure log path exists.

The method checks if the log path exists. Ensure that the log path is correctly configured and accessible.


1235-1238: Verify log filename format.

Ensure that the log filenames follow the expected format (pika.[hostname].[user name].log.[severity level].[date].[time].[pid]).


1280-1284: LGTM! Ensure proper testing.

The logic for deleting outdated log files looks good.

Ensure that this functionality is thoroughly tested to avoid accidental deletion of important log files.

if (interval_days > retention_time) {
std::string log_file = log_path + "/" + file;
LOG(INFO) << "Deleting out of date log file: " << log_file;
pstd::DeleteFile(log_file);
Copy link
Collaborator

@cheniujh cheniujh Jul 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pls check return value and print Error Log if deleteFile failed

int64_t now_timestamp = mktime(&now_time);
int64_t interval_days = (now_timestamp - log_timestamp) / 86400;

if (interval_days > retention_time) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A logic is needed to guarantee that the latest log(which is in use) will not be deleted even if it's logically expired.
The time extracted from log file name is the time of it's creation. thus it's possible that a log has logically expired but still in use if the pika server is inactive.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do your mean that assuming a Pika instance has been running continuously for 8 days, a server log created 8 days ago should logically have expired, but in reality, it is the most recent and currently used server log?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, that's what i mean

Check return value and print Error Log if deleteFile failed
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0ab1a51 and b432ca8.

Files selected for processing (1)
  • src/pika_server.cc (2 hunks)

Comment on lines +1088 to +1091
// Purge serverlog
AutoServerlogPurge();
// Purge binlog
AutoBinlogPurge();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper error handling for purging tasks.

Consider adding error handling and logging for AutoServerlogPurge and AutoBinlogPurge to capture any issues during log purging.

// Purge serverlog
if (!AutoServerlogPurge()) {
  LOG(ERROR) << "Failed to purge server logs";
}
// Purge binlog
if (!AutoBinlogPurge()) {
  LOG(ERROR) << "Failed to purge binlogs";
}

src/pika_server.cc Show resolved Hide resolved
Comment on lines 1213 to 1288
void PikaServer::AutoServerlogPurge(){
std::string log_path = g_pika_conf->log_path();
int retention_time = g_pika_conf->log_retention_time();
if (retention_time <= 0) {
return;
}
std::vector<std::string> log_files;

if (!pstd::FileExists(log_path)) {
return;
}

if (pstd::GetChildren(log_path, log_files) != 0) {
return;
}

time_t t = time(nullptr);
struct tm* now = localtime(&t);
int now_year = now->tm_year + 1900;
int now_month = now->tm_mon + 1;
int now_day = now->tm_mday;

//logformat: pika.[hostname].[user name].log.[severity level].[date].[time].[pid]
for (const auto& file : log_files) {
if (file.substr(0, 5) != "pika.") {
continue;
}

size_t log_pos = file.find(".log.");
if (log_pos == std::string::npos) {
continue;
}

// Start at the end of ".log." to find the date and time
size_t date_pos = file.find('.', log_pos + 5);
if (date_pos == std::string::npos || date_pos + 16 > file.length()) {
continue;
}

std::string date = file.substr(date_pos + 1, 8);
std::string time = file.substr(date_pos + 10, 6);

int log_year = std::atoi(date.substr(0, 4).c_str());
int log_month = std::atoi(date.substr(4, 2).c_str());
int log_day = std::atoi(date.substr(6, 2).c_str());

struct tm log_time;
struct tm now_time;

log_time.tm_year = log_year - 1900;
log_time.tm_mon = log_month - 1;
log_time.tm_mday = log_day;
log_time.tm_hour = 0;
log_time.tm_min = 0;
log_time.tm_sec = 0;

now_time.tm_year = now_year - 1900;
now_time.tm_mon = now_month - 1;
now_time.tm_mday = now_day;
now_time.tm_hour = 0;
now_time.tm_min = 0;
now_time.tm_sec = 0;

int64_t log_timestamp = mktime(&log_time);
int64_t now_timestamp = mktime(&now_time);
int64_t interval_days = (now_timestamp - log_timestamp) / 86400;

if (interval_days > retention_time) {
std::string log_file = log_path + "/" + file;
LOG(INFO) << "Deleting out of date log file: " << log_file;
if (!pstd::DeleteFile(log_file)) {
LOG(ERROR) << "Failed to delete log file: " << log_file;
}
}
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add error handling and logging for file operations.

Ensure that all file operations have proper error handling and logging.

void PikaServer::AutoServerlogPurge() {
  std::string log_path = g_pika_conf->log_path();
  int retention_time = g_pika_conf->log_retention_time();
  if (retention_time <= 0) {
    return;
  }
  std::vector<std::string> log_files;

  if (!pstd::FileExists(log_path)) {
    LOG(WARNING) << "Log path does not exist: " << log_path;
    return;
  }

  if (pstd::GetChildren(log_path, log_files) != 0) {
    LOG(ERROR) << "Failed to retrieve log files from: " << log_path;
    return;
  }

  time_t t = time(nullptr);
  struct tm* now = localtime(&t);
  int now_year = now->tm_year + 1900;
  int now_month = now->tm_mon + 1;
  int now_day = now->tm_mday;

  // log format: pika.[hostname].[user name].log.[severity level].[date].[time].[pid]
  for (const auto& file : log_files) {
    if (file.substr(0, 5) != "pika.") {
      continue;
    }

    size_t log_pos = file.find(".log.");
    if (log_pos == std::string::npos) {
      continue;
    }

    // Start at the end of ".log." to find the date and time
    size_t date_pos = file.find('.', log_pos + 5);
    if (date_pos == std::string::npos || date_pos + 16 > file.length()) {
      continue;
    }

    std::string date = file.substr(date_pos + 1, 8);
    std::string time = file.substr(date_pos + 10, 6);

    int log_year = std::atoi(date.substr(0, 4).c_str());
    int log_month = std::atoi(date.substr(4, 2).c_str());
    int log_day = std::atoi(date.substr(6, 2).c_str());

    struct tm log_time;
    struct tm now_time;

    log_time.tm_year = log_year - 1900;
    log_time.tm_mon = log_month - 1;
    log_time.tm_mday = log_day;
    log_time.tm_hour = 0;
    log_time.tm_min = 0;
    log_time.tm_sec = 0;

    now_time.tm_year = now_year - 1900;
    now_time.tm_mon = now_month - 1;
    now_time.tm_mday = now_day;
    now_time.tm_hour = 0;
    now_time.tm_min = 0;
    now_time.tm_sec = 0;

    int64_t log_timestamp = mktime(&log_time);
    int64_t now_timestamp = mktime(&now_time);
    int64_t interval_days = (now_timestamp - log_timestamp) / 86400;

    if (interval_days > retention_time) {
      std::string log_file = log_path + "/" + file;
      LOG(INFO) << "Deleting out of date log file: " << log_file;
      if (!pstd::DeleteFile(log_file)) {
        LOG(ERROR) << "Failed to delete log file: " << log_file;
      }
    }
  }
}

int64_t now_timestamp = mktime(&now_time);
int64_t interval_days = (now_timestamp - log_timestamp) / 86400;

if (interval_days > retention_time) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure the latest log file is not deleted if still in use.

Add logic to guarantee that the latest log file, which might still be in use, is not deleted even if it is logically expired.

if (interval_days > retention_time && !IsLogFileInUse(file)) {
  std::string log_file = log_path + "/" + file;
  LOG(INFO) << "Deleting out of date log file: " << log_file;
  if (!pstd::DeleteFile(log_file)) {
    LOG(ERROR) << "Failed to delete log file: " << log_file;
  }
}

1. retain the newest serverlog file even if it has been expired
2. Make sure that serverlogs of [INFO],[ERROR], and [WARNING] levels are retained
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b432ca8 and 973f9fa.

Files selected for processing (1)
  • src/pika_server.cc (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/pika_server.cc

@cheniujh
Copy link
Collaborator

cheniujh commented Aug 6, 2024

目前看着代码是OK的,能否辛苦实测一下呢,可以先手动mock一下代码,把过期时间改成10分钟,临时添加一些日志输出(比如每条指令都打一次日志,然后用benchmark压,很快就会累计大量日志,并且发生切换),主要测试一下功能正确性。

因为要上实际生产,所以需要稳妥一些,辛苦了!

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


At present, the code seems to be OK. Can you test it manually? You can manually mock the code first, change the expiration time to 10 minutes, and temporarily add some log output (for example, log each instruction once, and then use benchmark to press it. A large amount of logs will accumulate soon, and switching will occur), mainly to test the correctness of the function.

Because we have to go into actual production, we need to be more cautious. Thank you for your hard work!

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 973f9fa and 2584699.

Files selected for processing (3)
  • conf/pika.conf (1 hunks)
  • include/pika_conf.h (2 hunks)
  • src/pika_server.cc (2 hunks)
Files skipped from review due to trivial changes (1)
  • conf/pika.conf
Files skipped from review as they are similar to previous changes (1)
  • include/pika_conf.h
Additional comments not posted (4)
src/pika_server.cc (4)

1090-1093: Ensure proper error handling for purging tasks.

Consider adding error handling and logging for AutoServerlogPurge and AutoBinlogPurge to capture any issues during log purging.

// Purge serverlog
if (!AutoServerlogPurge()) {
  LOG(ERROR) << "Failed to purge server logs";
}
// Purge binlog
if (!AutoBinlogPurge()) {
  LOG(ERROR) << "Failed to purge binlogs";
}

1213-1214: Add error handling and logging.

Consider adding error handling and logging to capture any issues during binlog purging.

void PikaServer::AutoBinlogPurge() {
  Status s = DoSameThingEveryDB(TaskType::kPurgeLog);
  if (!s.ok()) {
    LOG(ERROR) << "Failed to purge binlogs: " << s.ToString();
  }
}

1215-1297: Add error handling and logging for file operations.

Ensure that all file operations have proper error handling and logging.

void PikaServer::AutoServerlogPurge() {
  std::string log_path = g_pika_conf->log_path();
  int retention_time = g_pika_conf->log_retention_time();
  if (retention_time <= 0) {
    return;
  }
  std::vector<std::string> log_files;

  if (!pstd::FileExists(log_path)) {
    LOG(WARNING) << "Log path does not exist: " << log_path;
    return;
  }

  if (pstd::GetChildren(log_path, log_files) != 0) {
    LOG(ERROR) << "Failed to retrieve log files from: " << log_path;
    return;
  }

  time_t t = time(nullptr);
  struct tm* now = localtime(&t);
  int now_year = now->tm_year + 1900;
  int now_month = now->tm_mon + 1;
  int now_day = now->tm_mday;

  // log format: pika.[hostname].[user name].log.[severity level].[date].[time].[pid]
  for (const auto& file : log_files) {
    if (file.substr(0, 5) != "pika.") {
      continue;
    }

    size_t log_pos = file.find(".log.");
    if (log_pos == std::string::npos) {
      continue;
    }

    // Start at the end of ".log." to find the date and time
    size_t date_pos = file.find('.', log_pos + 5);
    if (date_pos == std::string::npos || date_pos + 16 > file.length()) {
      continue;
    }

    std::string date = file.substr(date_pos + 1, 8);
    std::string time = file.substr(date_pos + 10, 6);

    int log_year = std::atoi(date.substr(0, 4).c_str());
    int log_month = std::atoi(date.substr(4, 2).c_str());
    int log_day = std::atoi(date.substr(6, 2).c_str());

    struct tm log_time;
    struct tm now_time;

    log_time.tm_year = log_year - 1900;
    log_time.tm_mon = log_month - 1;
    log_time.tm_mday = log_day;
    log_time.tm_hour = 0;
    log_time.tm_min = 0;
    log_time.tm_sec = 0;

    now_time.tm_year = now_year - 1900;
    now_time.tm_mon = now_month - 1;
    now_time.tm_mday = now_day;
    now_time.tm_hour = 0;
    now_time.tm_min = 0;
    now_time.tm_sec = 0;

    int64_t log_timestamp = mktime(&log_time);
    int64_t now_timestamp = mktime(&now_time);
    int64_t interval_days = (now_timestamp - log_timestamp) / 86400;

    if (interval_days > retention_time) {
      std::string log_file = log_path + "/" + file;
      LOG(INFO) << "Deleting out of date log file: " << log_file;
      if (!pstd::DeleteFile(log_file)) {
        LOG(ERROR) << "Failed to delete log file: " << log_file;
      }
    }
  }
}

1215-1297: Ensure the latest log file is not deleted if still in use.

Add logic to guarantee that the latest log file, which might still be in use, is not deleted even if it is logically expired.

if (interval_days > retention_time && !IsLogFileInUse(file)) {
  std::string log_file = log_path + "/" + file;
  LOG(INFO) << "Deleting out of date log file: " << log_file;
  if (!pstd::DeleteFile(log_file)) {
    LOG(ERROR) << "Failed to delete log file: " << log_file;
  }
}

@XiaoLiang2333
Copy link
Contributor Author

目前看着代码是OK的,能否辛苦实测一下呢,可以先手动mock一下代码,把过期时间改成10分钟,临时添加一些日志输出(比如每条指令都打一次日志,然后用benchmark压,很快就会累计大量日志,并且发生切换),主要测试一下功能正确性。

因为要上实际生产,所以需要稳妥一些,辛苦了!

ok,I got it.I have done a simple test before, and I will do a more detailed test according to the procedure you described

Adjust the time calculation method
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2584699 and a6934fa.

Files selected for processing (1)
  • src/pika_server.cc (2 hunks)
Additional comments not posted (4)
src/pika_server.cc (4)

1090-1093: Ensure proper error handling for purging tasks.

Consider adding error handling and logging for AutoServerlogPurge and AutoBinlogPurge to capture any issues during log purging.

// Purge serverlog
if (!AutoServerlogPurge()) {
  LOG(ERROR) << "Failed to purge server logs";
}
// Purge binlog
if (!AutoBinlogPurge()) {
  LOG(ERROR) << "Failed to purge binlogs";
}

1213-1214: Add error handling and logging.

Consider adding error handling and logging to capture any issues during binlog purging.

void PikaServer::AutoBinlogPurge() {
  Status s = DoSameThingEveryDB(TaskType::kPurgeLog);
  if (!s.ok()) {
    LOG(ERROR) << "Failed to purge binlogs: " << s.ToString();
  }
}

1215-1289: Add error handling and logging for file operations.

Ensure that all file operations have proper error handling and logging.

void PikaServer::AutoServerlogPurge() {
  std::string log_path = g_pika_conf->log_path();
  int retention_time = g_pika_conf->log_retention_time();
  if (retention_time <= 0) {
    return;
  }
  std::vector<std::string> log_files;

  if (!pstd::FileExists(log_path)) {
    LOG(WARNING) << "Log path does not exist: " << log_path;
    return;
  }

  if (pstd::GetChildren(log_path, log_files) != 0) {
    LOG(ERROR) << "Failed to retrieve log files from: " << log_path;
    return;
  }

  time_t t = time(nullptr);
  struct tm* now = localtime(&t);
  int now_year = now->tm_year + 1900;
  int now_month = now->tm_mon + 1;
  int now_day = now->tm_mday;

  // log format: pika.[hostname].[user name].log.[severity level].[date].[time].[pid]
  for (const auto& file : log_files) {
    if (file.substr(0, 5) != "pika.") {
      continue;
    }

    size_t log_pos = file.find(".log.");
    if (log_pos == std::string::npos) {
      continue;
    }

    // Start at the end of ".log." to find the date and time
    size_t date_pos = file.find('.', log_pos + 5);
    if (date_pos == std::string::npos || date_pos + 16 > file.length()) {
      continue;
    }

    std::string date = file.substr(date_pos + 1, 8);
    std::string time = file.substr(date_pos + 10, 6);

    int log_year = std::atoi(date.substr(0, 4).c_str());
    int log_month = std::atoi(date.substr(4, 2).c_str());
    int log_day = std::atoi(date.substr(6, 2).c_str());

    struct tm log_time;
    struct tm now_time;

    log_time.tm_year = log_year - 1900;
    log_time.tm_mon = log_month - 1;
    log_time.tm_mday = log_day;
    log_time.tm_hour = 0;
    log_time.tm_min = 0;
    log_time.tm_sec = 0;

    now_time.tm_year = now_year - 1900;
    now_time.tm_mon = now_month - 1;
    now_time.tm_mday = now_day;
    now_time.tm_hour = 0;
    now_time.tm_min = 0;
    now_time.tm_sec = 0;

    int64_t log_timestamp = mktime(&log_time);
    int64_t now_timestamp = mktime(&now_time);
    int64_t interval_days = (now_timestamp - log_timestamp) / 86400;

    if (interval_days > retention_time) {
      std::string log_file = log_path + "/" + file;
      LOG(INFO) << "Deleting out of date log file: " << log_file;
      if (!pstd::DeleteFile(log_file)) {
        LOG(ERROR) << "Failed to delete log file: " << log_file;
      }
    }
  }
}

1215-1289: Ensure the latest log file is not deleted if still in use.

Add logic to guarantee that the latest log file, which might still be in use, is not deleted even if it is logically expired.

if (interval_days > retention_time && !IsLogFileInUse(file)) {
  std::string log_file = log_path + "/" + file;
  LOG(INFO) << "Deleting out of date log file: " << log_file;
  if (!pstd::DeleteFile(log_file)) {
    LOG(ERROR) << "Failed to delete log file: " << log_file;
  }
}

@XiaoLiang2333
Copy link
Contributor Author

I ran more detailed tests,It seems to be working rightly.

Test approach:

  1. Change the automatic clean-up time to 5 min.
  2. Modify FLAGS_max_log_size of PikaGlogInit to 1(MB).
  3. Add a lot of logging output to DispatchThread::HandleNewConn.
  4. Run pika_benchmark

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (1)
src/pika_server.cc (1)

1215-1218: Add error handling for negative retention time.

Currently, the function returns if retention_time is less than 0. Consider logging a warning message to indicate that the retention time is invalid.

if (retention_time < 0) {
  LOG(WARNING) << "Invalid log retention time: " << retention_time;
  return;
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a6934fa and 9b4d63a.

Files selected for processing (1)
  • src/pika_server.cc (2 hunks)
Additional comments not posted (3)
src/pika_server.cc (3)

1090-1093: Ensure proper error handling for purging tasks.

Consider adding error handling and logging for AutoServerlogPurge and AutoBinlogPurge to capture any issues during log purging.

// Purge serverlog
if (!AutoServerlogPurge()) {
  LOG(ERROR) << "Failed to purge server logs";
}
// Purge binlog
if (!AutoBinlogPurge()) {
  LOG(ERROR) << "Failed to purge binlogs";
}

1223-1229: Add error handling and logging for file operations.

Ensure that all file operations have proper error handling and logging to capture any issues during log file retrieval.

if (!pstd::FileExists(log_path)) {
  LOG(WARNING) << "Log path does not exist: " << log_path;
  return;
}

if (pstd::GetChildren(log_path, log_files) != 0) {
  LOG(ERROR) << "Failed to retrieve log files from: " << log_path;
  return;
}

1285-1288: Ensure the latest log file is not deleted if still in use.

Add logic to guarantee that the latest log file, which might still be in use, is not deleted even if it is logically expired.

if (interval_days > retention_time && !IsLogFileInUse(file)) {
  std::string log_file = log_path + "/" + file;
  LOG(INFO) << "Deleting out of date log file: " << log_file;
  if (!pstd::DeleteFile(log_file)) {
    LOG(ERROR) << "Failed to delete log file: " << log_file;
  }
}

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (1)
src/pika_conf.cc (1)

131-133: Enhance error message for invalid log-retention-time.

The error message could be more descriptive to aid debugging and user understanding. Consider including the invalid value in the log message.

-	LOG(FATAL) << "log-retention-time invalid";
+	LOG(FATAL) << "log-retention-time invalid: " << log_retention_time_;
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9b4d63a and 42f5cd9.

Files selected for processing (1)
  • src/pika_conf.cc (1 hunks)

@chejinge chejinge merged commit 85f19d7 into OpenAtomFoundation:unstable Aug 8, 2024
13 checks passed
chejinge pushed a commit that referenced this pull request Aug 8, 2024
* Added the serverlog periodic reclamation function


---------

Co-authored-by: cheniujh <[email protected]>
cheniujh added a commit to cheniujh/pika that referenced this pull request Sep 24, 2024
…dation#2829)

* Added the serverlog periodic reclamation function


---------

Co-authored-by: cheniujh <[email protected]>
cheniujh added a commit to cheniujh/pika that referenced this pull request Sep 24, 2024
…dation#2829)

* Added the serverlog periodic reclamation function


---------

Co-authored-by: cheniujh <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.5.5 4.0.1 ✏️ Feature New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants