Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-25 08:29:13

0001 #!/usr/bin/env python3
0002 """
0003 System Status Reporter for SWF Testbed
0004 Reports actual status of required system services.
0005 Simple service status check - no deep connectivity testing.
0006 """
0007 
0008 import subprocess
0009 import sys
0010 import os
0011 import requests
0012 from pathlib import Path
0013 
0014 # Auto-restart with project venv Python if not already using it
0015 def ensure_venv_python():
0016     """Ensure we're running with the project venv Python, restart if not."""
0017     # Use SWF_HOME if set, otherwise derive from script location
0018     if 'SWF_HOME' in os.environ:
0019         swf_home = Path(os.environ['SWF_HOME'])
0020         venv_path = swf_home / 'swf-testbed' / '.venv'
0021     else:
0022         # Derive from script location
0023         venv_path = Path(__file__).resolve().parent / '.venv'
0024     
0025     venv_python = venv_path / 'bin' / 'python'
0026     
0027     # Check if venv exists
0028     if not venv_python.exists():
0029         print(f"āŒ Error: Virtual environment not found at {venv_path}")
0030         sys.exit(1)
0031     
0032     # Check if we're already using the venv Python
0033     current_python = Path(sys.executable).resolve()
0034     expected_python = venv_python.resolve()
0035     
0036     try:
0037         # If not the same file, restart with correct Python
0038         if not current_python.samefile(expected_python):
0039             print(f"šŸ”„ Restarting with project venv Python...")
0040             os.execv(str(venv_python), [str(venv_python)] + sys.argv)
0041     except (OSError, FileNotFoundError):
0042         # If we can't verify samefile, compare paths
0043         if current_python != expected_python:
0044             print(f"šŸ”„ Restarting with project venv Python...")
0045             os.execv(str(venv_python), [str(venv_python)] + sys.argv)
0046 
0047 # Ensure we're using venv Python before doing anything else
0048 ensure_venv_python()
0049 
0050 def setup_environment():
0051     """Auto-activate venv and load environment variables - same pattern as run_tests."""
0052     script_dir = Path(__file__).resolve().parent
0053     
0054     # Auto-activate virtual environment if not already active
0055     if "VIRTUAL_ENV" not in os.environ:
0056         venv_path = script_dir / ".venv"
0057         if venv_path.exists():
0058             print("šŸ”§ Auto-activating virtual environment...")
0059             venv_python = venv_path / "bin" / "python"
0060             if venv_python.exists():
0061                 os.environ["VIRTUAL_ENV"] = str(venv_path)
0062                 os.environ["PATH"] = f"{venv_path}/bin:{os.environ['PATH']}"
0063                 sys.executable = str(venv_python)
0064         else:
0065             print("āŒ Error: No Python virtual environment found")
0066             return False
0067     
0068     # Load ~/.env environment variables (they're already exported)
0069     env_file = Path.home() / ".env"
0070     if env_file.exists():
0071         print("šŸ”§ Loading environment variables from ~/.env...")
0072         with open(env_file) as f:
0073             for line in f:
0074                 line = line.strip()
0075                 if line and not line.startswith('#') and '=' in line:
0076                     if line.startswith('export '):
0077                         line = line[7:]  # Remove 'export '
0078                     key, value = line.split('=', 1)
0079                     value = value.strip('"\'')
0080                     # Skip entries with unexpanded shell variables
0081                     if '$' in value:
0082                         continue
0083                     os.environ[key] = value
0084 
0085     return True
0086 
0087 def get_active_services():
0088     """Get list of all active systemd services."""
0089     try:
0090         result = subprocess.run(['/usr/bin/systemctl', 'list-units', '--type=service', '--state=active', '--no-legend'], 
0091                               capture_output=True, text=True, timeout=10)
0092         if result.returncode == 0:
0093             services = []
0094             for line in result.stdout.strip().split('\n'):
0095                 if line.strip():
0096                     service_name = line.split()[0]
0097                     services.append(service_name)
0098             return services
0099         return []
0100     except Exception as e:
0101         print(f"    DEBUG: Failed to get active services: {e}")
0102         return []
0103 
0104 def find_service_by_pattern(active_services, patterns):
0105     """Find service matching any of the given patterns."""
0106     for service in active_services:
0107         for pattern in patterns:
0108             if pattern in service.lower():
0109                 return service
0110     return None
0111 
0112 def check_django_status():
0113     """Check if Django monitor is running and responding."""
0114     monitor_urls = [
0115         'https://pandaserver02.sdcc.bnl.gov/swf-monitor',
0116         'http://pandaserver02.sdcc.bnl.gov/swf-monitor',
0117         os.getenv('SWF_MONITOR_URL', 'https://localhost:8443'),
0118         os.getenv('SWF_MONITOR_HTTP_URL', 'http://localhost:8002')
0119     ]
0120     
0121     session = requests.Session()
0122     session.verify = False  # Allow self-signed certs
0123     session.proxies = {'http': None, 'https': None}
0124     session.timeout = 5
0125     
0126     # Suppress SSL warnings
0127     import urllib3
0128     urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
0129     
0130     results = []
0131     seen_urls = set()
0132     for url in monitor_urls:
0133         if url not in seen_urls:  # Remove duplicates while preserving order
0134             seen_urls.add(url)
0135             try:
0136                 response = session.get(f"{url}/api/systemagents/")
0137                 results.append((url, {
0138                     'status': response.status_code,
0139                     'reachable': True,
0140                     'response_time': response.elapsed.total_seconds()
0141                 }))
0142             except Exception as e:
0143                 results.append((url, {
0144                     'status': None,
0145                     'reachable': False,
0146                     'error': str(e)
0147                 }))
0148     
0149     return results
0150 
0151 def main():
0152     """Main status report."""
0153     print("=" * 60)
0154     print("SWF TESTBED SYSTEM STATUS REPORT")
0155     print("=" * 60)
0156     
0157     # Setup environment (we're already guaranteed to be using venv Python)
0158     if not setup_environment():
0159         print("āŒ Failed to setup environment")
0160         return 1
0161     
0162     # Check system services we expect
0163     print("\nšŸ”§ SYSTEM SERVICES:")
0164     
0165     # Get all active services
0166     all_active_services = get_active_services()
0167     
0168     # Find PostgreSQL service (any version)
0169     postgres_service = find_service_by_pattern(all_active_services, ['postgresql'])
0170     if postgres_service:
0171         print(f"  āœ… PostgreSQL ({postgres_service}) - ACTIVE")
0172     else:
0173         print(f"  āŒ PostgreSQL - INACTIVE")
0174     
0175     # Find ActiveMQ service (artemis, activemq, etc.)
0176     activemq_service = find_service_by_pattern(all_active_services, ['artemis', 'activemq'])
0177     if activemq_service:
0178         print(f"  āœ… ActiveMQ ({activemq_service}) - ACTIVE")
0179     else:
0180         print(f"  āŒ ActiveMQ - INACTIVE")
0181     
0182     # Find Redis service
0183     redis_service = find_service_by_pattern(all_active_services, ['redis'])
0184     if redis_service:
0185         print(f"  āœ… Redis ({redis_service}) - ACTIVE")
0186     else:
0187         print(f"  āŒ Redis - INACTIVE")
0188     
0189     # Keep track of what's running for final assessment
0190     active_services = []
0191     if postgres_service:
0192         active_services.append(postgres_service)
0193     if activemq_service:
0194         active_services.append(activemq_service)
0195     if redis_service:
0196         active_services.append(redis_service)
0197     
0198     # Check Django monitor status
0199     print("\n🌐 DJANGO MONITOR STATUS:")
0200     django_results = check_django_status()
0201     
0202     for url, result in django_results:
0203         if result['reachable']:
0204             print(f"  āœ… {url} - HTTP {result['status']} ({result['response_time']:.2f}s)")
0205         else:
0206             print(f"  āŒ {url} - UNREACHABLE: {result.get('error', 'Unknown error')}")
0207     
0208     # Environment check
0209     print("\nšŸŒ ENVIRONMENT VARIABLES:")
0210     env_vars = [
0211         'SWF_MONITOR_URL',
0212         'SWF_MONITOR_HTTP_URL',
0213         'SWF_API_TOKEN', 
0214         'ACTIVEMQ_HOST',
0215         'ACTIVEMQ_PORT',
0216         'DB_HOST',
0217         'DB_NAME',
0218         'DB_USER'
0219     ]
0220     
0221     for var in env_vars:
0222         value = os.getenv(var)
0223         if value:
0224             # Mask sensitive values
0225             if 'TOKEN' in var:
0226                 display_value = value[:10] + "..." if len(value) > 10 else "***"
0227             else:
0228                 display_value = value
0229             print(f"  āœ… {var} = {display_value}")
0230         else:
0231             print(f"  āŒ {var} = NOT SET")
0232     
0233     print("\n" + "=" * 60)
0234     print("READY TO RUN daq_simulator.py?" )
0235     
0236     # Final readiness check
0237     has_activemq = activemq_service is not None
0238     has_postgres = postgres_service is not None
0239     has_redis = redis_service is not None
0240     has_env = os.getenv('SWF_API_TOKEN') and os.getenv('ACTIVEMQ_HOST')
0241     has_django = any(result['reachable'] and result['status'] in [200, 403] 
0242                     for url, result in django_results)
0243     
0244     if has_activemq and has_postgres and has_redis and has_env and has_django:
0245         print("āœ… YES - All required services appear ready")
0246         return 0
0247     else:
0248         print("āŒ NO - Missing required services or configuration")
0249         if not has_activemq:
0250             print("  - Missing ActiveMQ service")
0251         if not has_postgres:
0252             print("  - Missing PostgreSQL service")
0253         if not has_redis:
0254             print("  - Missing Redis service")
0255         if not has_env:
0256             print("  - Missing environment variables")  
0257         if not has_django:
0258             print("  - Django monitor not responding")
0259         return 1
0260 
0261 if __name__ == "__main__":
0262     sys.exit(main())