🔍 Code Extractor

function admin_status

Maturity: 46

Flask route handler that retrieves comprehensive system status information including disk usage, session counts, analysis counts, and orphaned file detection for an admin dashboard.

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1509 - 1584
Complexity:
moderate

Purpose

This endpoint provides administrators with detailed metrics about the application's storage usage, active sessions, analyses, and potential cleanup opportunities. It calculates disk space used by session directories, identifies orphaned files/directories not associated with active sessions, and returns configuration settings for automatic cleanup. The function is designed for monitoring system health and managing storage resources.

Source Code

def admin_status():
    """Get system status including disk usage"""
    try:
        from pathlib import Path
        import shutil
        
        # Count analysis directories
        output_dir = Path(app_config.OUTPUT_DIR)
        total_analyses = 0
        session_count = 0
        total_size = 0
        session_details = []
        
        for session_dir in output_dir.iterdir():
            if session_dir.is_dir():
                session_count += 1
                analysis_dirs = [d for d in session_dir.iterdir() if d.is_dir() and d.name.startswith('analysis_')]
                session_analyses = len(analysis_dirs)
                total_analyses += session_analyses
                
                # Calculate directory size
                session_size = sum(f.stat().st_size for f in session_dir.rglob('*') if f.is_file())
                total_size += session_size
                
                session_details.append({
                    'session_id': session_dir.name,
                    'analysis_count': session_analyses,
                    'size_mb': round(session_size / (1024 * 1024), 2)
                })
        
        # Sort by size (largest first)
        session_details.sort(key=lambda x: x['size_mb'], reverse=True)
        
        # Check for orphaned files (quick check without cleanup)
        orphaned_dirs = 0
        orphaned_files = 0
        try:
            all_sessions = analysis_service.database_manager.get_all_sessions()
            active_session_ids = {session.session_id for session in all_sessions}
            
            # Quick count of orphaned items
            for session_dir in output_dir.iterdir():
                if session_dir.is_dir() and len(session_dir.name) == 36 and session_dir.name.count('-') == 4:
                    if session_dir.name not in active_session_ids:
                        orphaned_dirs += 1
            
            if app_config.UPLOAD_FOLDER.exists():
                for file_path in app_config.UPLOAD_FOLDER.iterdir():
                    if file_path.is_file():
                        has_active_session = any(sid in file_path.name for sid in active_session_ids)
                        if not has_active_session and ('_' in file_path.name or len(file_path.name) > 30):
                            orphaned_files += 1
        except Exception as orphan_check_error:
            logger.warning(f"Could not check orphaned files: {str(orphan_check_error)}")
        
        return jsonify({
            'success': True,
            'total_sessions': session_count,
            'total_analyses': total_analyses,
            'total_size_mb': round(total_size / (1024 * 1024), 2),
            'orphaned_dirs': orphaned_dirs,
            'orphaned_files': orphaned_files,
            'cleanup_config': {
                'auto_cleanup_enabled': app_config.AUTO_CLEANUP_ENABLED,
                'keep_recent_analyses': app_config.KEEP_RECENT_ANALYSES,
                'cleanup_old_sessions_days': app_config.CLEANUP_OLD_SESSIONS_DAYS
            },
            'session_details': session_details[:10]  # Top 10 largest sessions
        })
        
    except Exception as e:
        logger.error(f"Error getting admin status: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

Return Value

Returns a Flask JSON response with status code 200 on success or 500 on error. Success response contains: 'success' (bool), 'total_sessions' (int - count of session directories), 'total_analyses' (int - total analysis directories across all sessions), 'total_size_mb' (float - total disk space used in MB), 'orphaned_dirs' (int - count of session directories without active database records), 'orphaned_files' (int - count of upload files not associated with active sessions), 'cleanup_config' (dict with auto_cleanup_enabled, keep_recent_analyses, cleanup_old_sessions_days settings), and 'session_details' (list of top 10 largest sessions with session_id, analysis_count, and size_mb). Error response contains 'success' (False) and 'error' (string).

Dependencies

  • flask
  • pathlib
  • shutil
  • logging

Required Imports

from flask import Flask, jsonify
from pathlib import Path
import shutil
import logging

Conditional/Optional Imports

These imports are only needed under specific conditions:

from pathlib import Path

Condition: imported inside the function for file system operations

Required (conditional)
import shutil

Condition: imported inside the function but not actively used in current implementation

Optional

Usage Example

# Assuming Flask app is configured with route
# GET request to /admin/status endpoint

import requests

# Make request to admin status endpoint
response = requests.get('http://localhost:5000/admin/status')
data = response.json()

if data['success']:
    print(f"Total Sessions: {data['total_sessions']}")
    print(f"Total Analyses: {data['total_analyses']}")
    print(f"Total Size: {data['total_size_mb']} MB")
    print(f"Orphaned Directories: {data['orphaned_dirs']}")
    print(f"Orphaned Files: {data['orphaned_files']}")
    print(f"Auto Cleanup Enabled: {data['cleanup_config']['auto_cleanup_enabled']}")
    
    print("\nTop 10 Largest Sessions:")
    for session in data['session_details']:
        print(f"  {session['session_id']}: {session['analysis_count']} analyses, {session['size_mb']} MB")
else:
    print(f"Error: {data['error']}")

Best Practices

  • This endpoint should be protected with authentication/authorization middleware to prevent unauthorized access to system information
  • The function performs file system traversal which can be slow for large directories - consider implementing caching or background processing for production systems
  • Orphaned file detection uses heuristics (UUID format, filename patterns) which may produce false positives - verify before cleanup
  • The function limits session_details to top 10 largest sessions to prevent large response payloads
  • Error handling is implemented with try-except blocks, but orphaned file checking has its own nested exception handling to prevent failures from blocking the main response
  • Consider adding pagination for session_details if more than 10 sessions need to be displayed
  • The function calculates sizes by recursively traversing directories - this can be I/O intensive on systems with many files
  • Session ID validation assumes UUID format (36 characters with 4 hyphens) - ensure this matches your session ID generation strategy

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function admin_cleanup_orphaned 75.7% similar

    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.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function admin_cleanup 68.3% similar

    Flask route handler that provides an admin endpoint to manually trigger cleanup of old analysis sessions based on a configurable age threshold.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function system_status 68.0% similar

    Flask API endpoint that returns comprehensive system status information including database connectivity, authentication state, and feature availability.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_analysis_progress 64.3% similar

    Flask route handler that retrieves the progress status of a running analysis task and performs cleanup of completed/failed analyses after a timeout period.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_session_status 62.5% similar

    Flask API endpoint that retrieves the current status and summary of an analysis session by its ID.

    From: /tf/active/vicechatdev/full_smartstat/app.py
← Back to Browse