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:


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

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

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

4. Cron Job Setup

echo "{{ LOG_ROTATE_SPEC }} * * * /bin/chmod 755 /logsdir; /usr/sbin/logrotate -v /etc/logrotate.conf" > /etc/crontabs/root

5. Starting Cron Daemon

echo "Starting crond"

crond -f

Template Variables

These variables are expected to be passed during template rendering.


Implementation Details and Algorithms


Interaction with Other System Components


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.