File size: 3,640 Bytes
f27c4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env python3
"""
Manual log cleanup script for Attestation Store.

Usage:
    python scripts/cleanup_logs.py              # Use default retention from LOG_RETENTION_DAYS
    python scripts/cleanup_logs.py --days 30    # Delete logs older than 30 days
    python scripts/cleanup_logs.py --dry-run    # Preview what would be deleted
"""

import argparse
import sys
from datetime import datetime, timedelta

# Add parent directory to path to import app modules
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import app
from models import SystemLog


def cleanup_logs(retention_days=None, dry_run=False):
    """
    Delete logs older than the specified retention period.
    
    Args:
        retention_days (int, optional): Number of days to retain logs.
            If not provided, uses LOG_RETENTION_DAYS from config.
        dry_run (bool): If True, only show what would be deleted without deleting.
    
    Returns:
        int: Number of log entries that were (or would be) deleted
    """
    with app.app_context():
        from logging_utils import cleanup_old_logs
        from flask import current_app
        
        # Get retention period from config if not specified
        if retention_days is None:
            config = current_app.config.get('STORAGE_CONFIG')
            retention_days = config.LOG_RETENTION_DAYS if config else 10
        
        # Skip cleanup if retention is 0 or negative
        if retention_days <= 0:
            print("Log cleanup disabled (retention_days <= 0)")
            return 0
        
        # Calculate cutoff date
        cutoff_date = datetime.utcnow() - timedelta(days=retention_days)
        
        # Count logs to be deleted
        count = SystemLog.query.filter(SystemLog.timestamp < cutoff_date).count()
        
        if dry_run:
            print(f"DRY RUN: Would delete {count} log entries older than {retention_days} days (before {cutoff_date.isoformat()})")
            return count
        
        # Perform actual cleanup
        deleted = cleanup_old_logs(retention_days=retention_days)
        print(f"Deleted {deleted} log entries older than {retention_days} days (before {cutoff_date.isoformat()})")
        return deleted


def main():
    parser = argparse.ArgumentParser(
        description='Clean up old logs from the Attestation Store database',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Use default retention period from LOG_RETENTION_DAYS environment variable
  python scripts/cleanup_logs.py
  
  # Delete logs older than 30 days
  python scripts/cleanup_logs.py --days 30
  
  # Preview what would be deleted without actually deleting
  python scripts/cleanup_logs.py --dry-run
  
  # Preview deletion with custom retention period
  python scripts/cleanup_logs.py --days 60 --dry-run
        """
    )
    
    parser.add_argument(
        '--days',
        type=int,
        metavar='N',
        help='Number of days to retain logs (logs older than N days will be deleted)'
    )
    
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='Show what would be deleted without actually deleting'
    )
    
    args = parser.parse_args()
    
    try:
        deleted = cleanup_logs(retention_days=args.days, dry_run=args.dry_run)
        
        if deleted == 0 and not args.dry_run:
            print("No logs were deleted.")
        
        sys.exit(0)
        
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == '__main__':
    main()