File size: 6,109 Bytes
c636ebf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#!/usr/bin/env python3
"""

Backend Health Check Script

Detects and starts FastAPI backend server, then tests all analytics endpoints

"""

import requests
import subprocess
import time
import os
import sys

BASE_URL = "http://localhost:8001"
ANALYTICS_ENDPOINTS = [
    "/api/analytics/realtime",
    "/api/analytics/trends",
    "/api/analytics/predictions",
    "/api/analytics/similarity",
    "/api/analytics/clustering",
    "/api/analytics/quality",
    "/api/analytics/health",
    "/api/analytics/performance"
]


def check_backend_running():
    """Check if FastAPI server is running on localhost:8000"""
    try:
        response = requests.get(BASE_URL + "/docs", timeout=3)
        if response.status_code == 200:
            print("βœ… FastAPI server is running on", BASE_URL)
            return True
    except requests.exceptions.RequestException:
        print("❌ Backend server is not responding.")
    return False


def check_port_usage():
    """Check if port 8000 is already in use"""
    try:
        result = subprocess.run(
            ["netstat", "-ano", "|", "findstr", ":8000"],
            shell=True, capture_output=True, text=True
        )
        if result.stdout.strip():
            print("⚠️  Port 8000 is already in use:")
            print(result.stdout)
            return True
        return False
    except Exception as e:
        print(f"⚠️  Could not check port usage: {e}")
        return False


def start_backend():
    """Start the FastAPI backend server"""
    print("πŸš€ Attempting to start FastAPI backend server...")

    # Check if we're in the right directory
    current_dir = os.getcwd()
    print(f"πŸ“ Current directory: {current_dir}")

    # Look for the main.py file
    main_py_path = os.path.join(current_dir, "app", "main.py")
    if not os.path.exists(main_py_path):
        print(f"❌ Could not find app/main.py at {main_py_path}")
        return None

    print(f"βœ… Found main.py at {main_py_path}")

    # Start the server using uvicorn
    try:
        process = subprocess.Popen(
            ["python", "-m", "uvicorn", "app.main:app",
                "--reload", "--host", "0.0.0.0", "--port", "8000"],
            cwd=current_dir,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        print("⏳ Waiting 10 seconds for server startup...")
        time.sleep(10)
        return process
    except Exception as e:
        print(f"❌ Failed to start server: {e}")
        return None


def test_endpoints():
    """Test all analytics endpoints"""
    print("\nπŸ” Testing analytics endpoints...")
    results = {}
    successful = 0

    for endpoint in ANALYTICS_ENDPOINTS:
        url = BASE_URL + endpoint
        try:
            response = requests.get(url, timeout=5)
            status = response.status_code
            if status == 200:
                print(f"βœ… {endpoint} | Status: {status}")
                results[endpoint] = "OK"
                successful += 1
            else:
                print(f"⚠️  {endpoint} | Status: {status}")
                results[endpoint] = f"FAIL ({status})"
        except requests.exceptions.RequestException as e:
            print(f"❌ {endpoint} | Error: {str(e)}")
            results[endpoint] = "ERROR"

    return results, successful


def main():
    """Main health check execution"""
    print("πŸ”§ Starting Backend Health Check...")
    print("=" * 60)

    # Check if server is already running
    server_running = check_backend_running()
    process = None

    if not server_running:
        print("\nπŸ“‘ Server not running. Starting backend...")

        # Check for port conflicts
        if check_port_usage():
            print(
                "⚠️  Port 8000 is in use. You may need to stop the conflicting process.")
            print("   Run: netstat -ano | findstr :8000")
            print("   Then: taskkill /PID <PID> /F")

        # Start the server
        process = start_backend()

        # Check if server started successfully
        if not check_backend_running():
            print("❌ Backend server failed to start. Please check:")
            print(
                "   1. Are all dependencies installed? (pip install -r requirements.txt)")
            print("   2. Is port 8000 available?")
            print("   3. Are there any import errors in app/main.py?")
            return False

    # Test all endpoints
    results, successful = test_endpoints()

    # Summary
    print("\n" + "=" * 60)
    print("πŸ“Š TEST SUMMARY")
    print("=" * 60)
    total_endpoints = len(ANALYTICS_ENDPOINTS)
    success_rate = (successful / total_endpoints) * 100

    for endpoint, status in results.items():
        icon = "βœ…" if status == "OK" else "❌"
        print(f"{icon} {endpoint}: {status}")

    print(
        f"\nπŸ“ˆ Success Rate: {successful}/{total_endpoints} ({success_rate:.1f}%)")

    # Cleanup
    if process:
        print("\nπŸ›‘ Stopping temporary backend server...")
        process.terminate()
        process.wait()

    # Final assessment
    print("\n🎯 FINAL ASSESSMENT")
    print("=" * 60)
    if success_rate >= 95:
        print("βœ… EXCELLENT: All analytics endpoints are working correctly!")
        print("   Ready for frontend integration and deployment.")
    elif success_rate >= 80:
        print("⚠️  GOOD: Most endpoints working, some issues to address.")
        print("   Review failed endpoints before deployment.")
    elif success_rate >= 50:
        print("⚠️  FAIR: Half of endpoints working, significant issues.")
        print("   Server may need restart or configuration fixes.")
    else:
        print("❌ POOR: Most endpoints failing, server likely down.")
        print("   Check server status and database connectivity.")

    return success_rate >= 80


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)