-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
280 lines (210 loc) · 8.09 KB
/
main.py
File metadata and controls
280 lines (210 loc) · 8.09 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""
Main entry point for AutoOps application
"""
import asyncio
import signal
import sys
import logging
import time
from contextlib import asynccontextmanager
import click
import uvicorn
from dotenv import load_dotenv
from src.dashboard.app import app
from src.utils.task_manager_simple import task_manager
from src.monitoring.tracing_simple import initialize_tracing
from config.settings import settings
# Configure logging
logging.basicConfig(
level=getattr(logging, settings.log_level.upper()),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class AutoOpsApplication:
"""Main AutoOps application class"""
def __init__(self):
self.is_running = False
self.tasks = []
async def start(self):
"""Start the AutoOps application"""
logger.info("Starting AutoOps application...")
try:
# Initialize tracing
initialize_tracing()
logger.info("OpenTelemetry tracing initialized")
# Start task manager
await task_manager.start()
logger.info("Task manager started")
self.is_running = True
logger.info("AutoOps application started successfully")
except Exception as e:
logger.error(f"Failed to start AutoOps application: {e}")
raise
async def stop(self):
"""Stop the AutoOps application"""
logger.info("Stopping AutoOps application...")
try:
self.is_running = False
# Stop task manager
await task_manager.stop()
logger.info("Task manager stopped")
logger.info("AutoOps application stopped successfully")
except Exception as e:
logger.error(f"Error stopping AutoOps application: {e}")
async def health_check(self):
"""Check application health"""
try:
metrics = await task_manager.get_metrics()
return {
"status": "healthy" if self.is_running else "unhealthy",
"task_manager": metrics,
"version": "1.0.0"
}
except Exception as e:
return {
"status": "unhealthy",
"error": str(e),
"version": "1.0.0"
}
# Global application instance
autoops_app = AutoOpsApplication()
@asynccontextmanager
async def lifespan(app):
"""FastAPI lifespan manager"""
# Startup
await autoops_app.start()
yield
# Shutdown
await autoops_app.stop()
# Update FastAPI app with lifespan
app.router.lifespan_context = lifespan
@click.group()
def cli():
"""AutoOps Multi-Agent Kubernetes Orchestrator"""
pass
@cli.command()
@click.option('--host', default=settings.dashboard_host, help='Host to bind the server to')
@click.option('--port', default=settings.dashboard_port, help='Port to bind the server to')
@click.option('--reload', is_flag=True, help='Enable auto-reload for development')
@click.option('--workers', default=1, help='Number of worker processes')
def serve(host, port, reload, workers):
"""Start the AutoOps server"""
logger.info(f"Starting AutoOps server on {host}:{port}")
# Load environment variables
load_dotenv()
uvicorn.run(
"main:app",
host=host,
port=port,
reload=reload or settings.dev_mode,
workers=workers if not reload else 1,
log_level=settings.log_level.lower()
)
@cli.command()
@click.argument('request')
@click.option('--priority', default='normal', help='Task priority (low, normal, high, critical)')
@click.option('--timeout', type=int, help='Task timeout in seconds')
def submit(request, priority, timeout):
"""Submit a task via CLI"""
async def _submit():
from src.utils.task_manager_simple import TaskPriority
await autoops_app.start()
try:
task_id = await task_manager.submit_task(
func=lambda: f"Processing request: {request}",
priority=TaskPriority(priority),
timeout=timeout
)
click.echo(f"Task submitted: {task_id}")
# Wait for completion
while True:
status = await task_manager.get_task_status(task_id)
if status and status in ['completed', 'failed', 'cancelled']:
click.echo(f"Task {status}: {task_id}")
if status == 'failed':
# Get task details for error info
task = task_manager.tasks.get(task_id)
if task and task.error:
click.echo(f"Error: {task.error}")
break
await asyncio.sleep(1)
finally:
await autoops_app.stop()
asyncio.run(_submit())
@cli.command()
@click.option('--limit', default=10, help='Number of tasks to show')
@click.option('--status', help='Filter by task status')
def list_tasks(limit, status):
"""List tasks"""
async def _list(limit_val, status_val):
from src.utils.task_manager_simple import TaskStatus
await autoops_app.start()
try:
tasks = await task_manager.get_all_tasks()
# Filter by status if provided
if status_val:
tasks = [task for task in tasks if str(task['status']) == status_val]
# Limit results
tasks = tasks[:limit_val]
if not tasks:
click.echo("No tasks found")
return
click.echo(f"{'ID':<36} {'Status':<12} {'Created':<20}")
click.echo("-" * 80)
for task in tasks:
task_id = task['task_id'][:8]
status = task['status']
created = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(task['created_at']))
click.echo(f"{task_id:<36} {status:<12} {created:<20}")
if task.get('error'):
click.echo(f" Error: {task['error']}")
finally:
await autoops_app.stop()
asyncio.run(_list(limit, status))
@cli.command()
@click.argument('task_id')
def cancel(task_id):
"""Cancel a task"""
async def _cancel():
await autoops_app.start()
try:
success = await task_manager.cancel_task(task_id)
if success:
click.echo(f"Task cancelled: {task_id}")
else:
click.echo(f"Task not found: {task_id}")
finally:
await autoops_app.stop()
asyncio.run(_cancel())
@cli.command()
def health():
"""Check application health"""
async def _health():
await autoops_app.start()
try:
health_status = await autoops_app.health_check()
click.echo(f"Status: {health_status['status']}")
click.echo(f"Version: {health_status['version']}")
if 'task_manager' in health_status:
metrics = health_status['task_manager']
click.echo(f"Total tasks: {metrics['total_tasks']}")
click.echo(f"Active tasks: {metrics['active_tasks']}")
click.echo(f"Queue size: {metrics['queue_size']}")
finally:
await autoops_app.stop()
asyncio.run(_health())
def setup_signal_handlers():
"""Setup signal handlers for graceful shutdown"""
def signal_handler(signum, frame):
logger.info(f"Received signal {signum}, shutting down...")
asyncio.create_task(autoops_app.stop())
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
if __name__ == "__main__":
# Load environment variables
load_dotenv()
# Setup signal handlers
setup_signal_handlers()
# Run CLI
cli()