function admin_cleanup_orphaned
Flask route handler that cleans up orphaned files and directories from deleted analysis sessions by calling the analysis service's cleanup method and returning detailed results.
/tf/active/vicechatdev/full_smartstat/app.py
1587 - 1614
moderate
Purpose
This admin endpoint provides a way to manually trigger cleanup of orphaned files that remain on the filesystem after their associated sessions have been deleted from the database. It returns statistics about removed directories, files, freed disk space, and any errors encountered during the cleanup process. This is useful for maintaining storage hygiene and preventing disk space accumulation from abandoned session data.
Source Code
def admin_cleanup_orphaned():
"""Admin endpoint to clean up orphaned files from deleted sessions"""
try:
# Clean up orphaned files
cleanup_result = analysis_service.cleanup_orphaned_files()
if cleanup_result['success']:
results = cleanup_result['results']
return jsonify({
'success': True,
'message': f"Orphaned cleanup completed: {results['orphaned_dirs_removed']} directories and {results['orphaned_files_removed']} files removed",
'orphaned_dirs_removed': results['orphaned_dirs_removed'],
'orphaned_files_removed': results['orphaned_files_removed'],
'size_freed_mb': results['total_size_freed_mb'],
'errors': results['errors']
})
else:
return jsonify({
'success': False,
'error': cleanup_result['error']
}), 500
except Exception as e:
logger.error(f"Error in orphaned cleanup: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 500
Return Value
Returns a Flask JSON response with status code. On success (200): {'success': True, 'message': str, 'orphaned_dirs_removed': int, 'orphaned_files_removed': int, 'size_freed_mb': float, 'errors': list}. On failure (500): {'success': False, 'error': str}. The success response includes counts of removed directories and files, total disk space freed in megabytes, and a list of any errors encountered during cleanup.
Dependencies
flaskloggingpathlibshutil
Required Imports
from flask import Flask
from flask import jsonify
import logging
Usage Example
# Assuming Flask app is set up with this route
# Make a POST request to trigger cleanup
import requests
response = requests.post('http://localhost:5000/admin/cleanup/orphaned')
result = response.json()
if result['success']:
print(f"Cleanup completed: {result['message']}")
print(f"Directories removed: {result['orphaned_dirs_removed']}")
print(f"Files removed: {result['orphaned_files_removed']}")
print(f"Space freed: {result['size_freed_mb']} MB")
if result['errors']:
print(f"Errors encountered: {result['errors']}")
else:
print(f"Cleanup failed: {result['error']}")
Best Practices
- This endpoint should be protected with authentication/authorization middleware to prevent unauthorized access to admin functions
- Consider implementing rate limiting to prevent abuse of this potentially resource-intensive operation
- The cleanup operation may take significant time for large numbers of orphaned files - consider implementing as an async background task for production use
- Monitor the 'errors' field in the response to identify persistent cleanup issues
- Schedule regular automated calls to this endpoint or implement automatic cleanup triggers
- Ensure proper logging is configured to track cleanup operations for audit purposes
- Test the cleanup operation in a staging environment before running in production
- Consider implementing a dry-run mode that reports what would be deleted without actually deleting
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function admin_cleanup 83.7% similar
-
function admin_status 75.7% similar
-
function delete_session 73.4% similar
-
function get_analysis_progress 70.3% similar
-
function get_analysis_files 66.4% similar