logrotate.j2
Overview
logrotate.j2 is a shell script template designed to configure and run log rotation inside a Docker container environment. It ensures that log files under a specified directory are rotated based on configured size and rotation count limits, maintaining log file management within containerized applications. The script also sets appropriate permissions and schedules log rotation via a cron job.
Detailed Explanation
Script Purpose
The script's main goal is to:
Verify execution is within a Docker or container environment.
Set up a logrotate configuration file to rotate logs located at
/logsdir/*.log.Adjust file and directory ownership and permissions.
Schedule periodic execution of the logrotate command using
crond.
Step-by-step Breakdown
1. Container Environment Check
if [[ -f /.dockerenv ]] || grep -Eq '(lxc|docker)' /proc/1/cgroup; then
echo -n
else
echo "Docker only!"
exit 1
fi
Checks if the script is running inside a Docker container.
It looks for the presence of the special file
/.dockerenvor inspects/proc/1/cgroupfor container-related keywords.If not running in a container, it outputs
"Docker only!"and exits with status code 1, preventing execution outside the intended environment.
2. Logrotate Configuration Setup
rm /etc/logrotate.d/*
cat >/etc/logrotate.d/node <<EOF
/logsdir/*.log {
missingok
rotate {{ LOG_ROTATE_AMOUNT }}
size {{ LOG_ROTATE_SIZE }}
notifempty
copytruncate
}
EOF
Removes all existing logrotate configurations under
/etc/logrotate.d/.Creates a new configuration file
/etc/logrotate.d/nodewith templated parameters:LOG_ROTATE_AMOUNT: Number of rotated log files to keep.LOG_ROTATE_SIZE: The size threshold that triggers a log rotation.
Configuration options explained:
missingok: Don't error if the log file is missing.rotate: How many rotation files to keep.size: Rotate logs only if they reach the specified size.notifempty: Do not rotate empty logs.copytruncate: Truncate the original log file after copying it, useful for programs that keep file handles open.
3. Permissions Management
chown 0:0 /etc/logrotate.d
chown 0:0 /etc/logrotate.d/node
chmod 755 /etc/logrotate.d
chmod 644 /etc/logrotate.d/node
chmod 755 /logsdir
Ensures ownership of
/etc/logrotate.ddirectory andnodeconfig file is root (user ID 0, group ID 0).Sets directory permissions to
755(read/write/execute for owner, read/execute for group and others).Sets config file permissions to
644(read/write for owner, read-only for others).Sets
/logsdirdirectory to755permissions to allow access for log rotation.
4. Cron Job Setup
echo "{{ LOG_ROTATE_SPEC }} * * * /bin/chmod 755 /logsdir; /usr/sbin/logrotate -v /etc/logrotate.conf" > /etc/crontabs/root
Writes a cron job entry into the root user's crontab.
LOG_ROTATE_SPECis a templated cron schedule expression (e.g.,0 * * * *for hourly).The cron job:
Ensures
/logsdirhas755permissions before logrotate runs.Executes
logrotatewith verbose output using the main config/etc/logrotate.conf.
5. Starting Cron Daemon
echo "Starting crond"
crond -f
Prints a startup message.
Runs the cron daemon (
crond) in the foreground (-f), which is typical for container processes to keep the container running and manage scheduled tasks.
Template Variables
LOG_ROTATE_AMOUNT: Integer specifying how many rotated log files are retained.LOG_ROTATE_SIZE: Size threshold (e.g., "100M") for rotating logs.LOG_ROTATE_SPEC: Cron timing specification string to schedule the rotation job.
These variables are expected to be passed during template rendering.
Implementation Details and Algorithms
The script uses a simple, robust method to detect containerized environments, leveraging standard Docker and LXC indicators.
Log rotation is configured with the
copytruncateoption, which allows rotation without restarting the application writing logs, avoiding interruptions.The cron job ensures that log rotation happens regularly and that permissions remain correct, preventing issues with log file access in long-running containers.
Running
crondin the foreground aligns with container best practices where the main process runs in the foreground.
Interaction with Other System Components
Log Directory (
/logsdir): The source directory where application logs are stored and rotated.Logrotate Configuration Directory (
/etc/logrotate.d/): This script manages the logrotate config files here, replacing any existing configs.Cron Daemon: This script sets a cron job and starts the cron service to schedule log rotation.
Logrotate Binary (
/usr/sbin/logrotate): The script invokes this utility to perform the actual log rotation based on the generated configuration.Container Environment: The script enforces execution only inside containers, making it part of container lifecycle tools.
Usage Example
When rendered with the following variables:
LOG_ROTATE_AMOUNT: 5
LOG_ROTATE_SIZE: 100M
LOG_ROTATE_SPEC: "0 * * * *"
The resulting /etc/logrotate.d/node would contain:
/logsdir/*.log {
missingok
rotate 5
size 100M
notifempty
copytruncate
}
The crontab for root would be:
0 * * * * /bin/chmod 755 /logsdir; /usr/sbin/logrotate -v /etc/logrotate.conf
This configuration rotates logs hourly if they exceed 100MB, keeping 5 old rotated files.
Diagram: Workflow of logrotate.j2
flowchart TD
A[Start Script] --> B{Inside Container?}
B -- No --> C[Print "Docker only!" and exit]
B -- Yes --> D[Remove existing logrotate configs]
D --> E[Create new logrotate config file]
E --> F[Set ownership and permissions]
F --> G[Write cron job for logrotate]
G --> H[Start cron daemon in foreground]
H --> I[Log rotation occurs per schedule]
This diagram illustrates the main workflow of the script from start to scheduling and running logrotate in the container environment.