sysnexa 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sysnexa/cli/main.py ADDED
@@ -0,0 +1,587 @@
1
+
2
+ from pathlib import Path
3
+
4
+ import typer
5
+ from rich.console import Console
6
+ from rich.table import Table
7
+
8
+ from sysnexa.analyzer.hardware import HardwareAnalyzer
9
+ from sysnexa.analyzer.performance import PerformanceAnalyzer
10
+ from sysnexa.analyzer.trends import PerformanceTrend
11
+ from sysnexa.core.diagnostics import SystemDiagnostics
12
+ from sysnexa.core.history import PerformanceHistory
13
+ from sysnexa.exporters.report import SystemReportExporter
14
+ from sysnexa.monitor.cpu import CPUMonitor
15
+ from sysnexa.monitor.disk import DiskMonitor
16
+ from sysnexa.monitor.network import NetworkMonitor
17
+ from sysnexa.monitor.process import ProcessMonitor
18
+ from sysnexa.monitor.ram import RAMMonitor
19
+
20
+ app = typer.Typer(
21
+ name="sysnexa",
22
+ help="Advanced system monitoring and performance analysis.",
23
+ no_args_is_help=True,
24
+ add_completion=True,
25
+ )
26
+
27
+ console = Console()
28
+
29
+
30
+ @app.command()
31
+ def info() -> None:
32
+ """Display Sysnexa application information."""
33
+ console.print("[bold cyan]Sysnexa[/bold cyan]")
34
+ console.print("System Intelligence and Performance Monitoring")
35
+ console.print("Version: 0.1.0")
36
+
37
+
38
+ @app.command()
39
+ def hello() -> None:
40
+ """Check whether Sysnexa CLI is working."""
41
+ console.print("[bold green]Sysnexa is running successfully![/bold green]")
42
+
43
+
44
+ @app.command()
45
+ def cpu() -> None:
46
+ """Display CPU performance information."""
47
+ data = CPUMonitor.get_info()
48
+
49
+ table = Table(title="Sysnexa CPU Monitor")
50
+ table.add_column("Property", style="bold cyan")
51
+ table.add_column("Value", justify="right")
52
+
53
+ table.add_row("Physical cores", str(data.physical_cores))
54
+ table.add_row("Logical cores", str(data.logical_cores))
55
+ table.add_row("CPU usage", f"{data.usage_percent:.1f}%")
56
+
57
+ table.add_row(
58
+ "Current frequency",
59
+ f"{data.frequency_current} MHz"
60
+ if data.frequency_current is not None else "Unavailable",
61
+ )
62
+ table.add_row(
63
+ "Maximum frequency",
64
+ f"{data.frequency_max} MHz"
65
+ if data.frequency_max is not None else "Unavailable",
66
+ )
67
+
68
+ console.print(table)
69
+
70
+ core_table = Table(title="Per-Core CPU Usage")
71
+ core_table.add_column("Core", style="cyan")
72
+ core_table.add_column("Usage", justify="right")
73
+
74
+ for index, usage in enumerate(data.per_core_usage, start=1):
75
+ core_table.add_row(f"Core {index}", f"{usage:.1f}%")
76
+
77
+ console.print(core_table)
78
+
79
+
80
+ @app.command()
81
+ def ram() -> None:
82
+ """Display RAM and swap memory information."""
83
+ data = RAMMonitor.get_info()
84
+
85
+ table = Table(title="Sysnexa RAM Monitor", header_style="bold cyan")
86
+ table.add_column("Property")
87
+ table.add_column("Value", justify="right")
88
+
89
+ table.add_row("Total RAM", f"{data.total_gb:.2f} GB")
90
+ table.add_row("Used RAM", f"{data.used_gb:.2f} GB")
91
+ table.add_row("Available RAM", f"{data.available_gb:.2f} GB")
92
+ table.add_row("RAM Usage", f"{data.usage_percent:.1f}%")
93
+ table.add_section()
94
+ table.add_row("Total Swap", f"{data.swap_total_gb:.2f} GB")
95
+ table.add_row("Used Swap", f"{data.swap_used_gb:.2f} GB")
96
+ table.add_row("Swap Usage", f"{data.swap_percent:.1f}%")
97
+
98
+ console.print(table)
99
+
100
+
101
+ @app.command()
102
+ def disk() -> None:
103
+ """Display disk partition and storage information."""
104
+ disks = DiskMonitor.get_info()
105
+
106
+ if not disks:
107
+ console.print("[yellow]No accessible disk partitions found.[/yellow]")
108
+ return
109
+
110
+ table = Table(
111
+ title="Sysnexa Disk Monitor",
112
+ header_style="bold cyan",
113
+ )
114
+
115
+ table.add_column("Drive")
116
+ table.add_column("Filesystem")
117
+ table.add_column("Total", justify="right")
118
+ table.add_column("Used", justify="right")
119
+ table.add_column("Free", justify="right")
120
+ table.add_column("Usage", justify="right")
121
+
122
+ for disk_info in disks:
123
+ table.add_row(
124
+ disk_info.mountpoint,
125
+ disk_info.filesystem,
126
+ f"{disk_info.total_gb:.2f} GB",
127
+ f"{disk_info.used_gb:.2f} GB",
128
+ f"{disk_info.free_gb:.2f} GB",
129
+ f"{disk_info.usage_percent:.1f}%",
130
+ )
131
+
132
+ console.print(table)
133
+
134
+
135
+ @app.command()
136
+ def network() -> None:
137
+ """Display network traffic information."""
138
+ info = NetworkMonitor.get_info(interval=1.0)
139
+
140
+ table = Table(title="Network Monitor", show_header=True)
141
+ table.add_column("Metric", style="cyan")
142
+ table.add_column("Value", style="green")
143
+
144
+ table.add_row("Upload Speed", f"{info.upload_kb:.2f} KB/s")
145
+ table.add_row("Download Speed", f"{info.download_kb:.2f} KB/s")
146
+ table.add_row("Total Uploaded", f"{info.bytes_sent / (1024 ** 2):.2f} MB")
147
+ table.add_row("Total Downloaded", f"{info.bytes_received / (1024 ** 2):.2f} MB")
148
+ table.add_row("Packets Sent", f"{info.packets_sent:,}")
149
+ table.add_row("Packets Received", f"{info.packets_received:,}")
150
+
151
+ console.print(table)
152
+
153
+
154
+
155
+ @app.command()
156
+ def process() -> None:
157
+ """Display running processes and resource usage."""
158
+ processes = ProcessMonitor.get_processes(limit=20)
159
+
160
+ if not processes:
161
+ console.print("[yellow]No running processes found.[/yellow]")
162
+ return
163
+
164
+ table = Table(
165
+ title="Sysnexa Process Monitor",
166
+ header_style="bold cyan",
167
+ )
168
+
169
+ table.add_column("PID", justify="right")
170
+ table.add_column("Process Name")
171
+ table.add_column("CPU", justify="right")
172
+ table.add_column("RAM", justify="right")
173
+ table.add_column("Status")
174
+ table.add_column("Username")
175
+
176
+ for item in processes:
177
+ table.add_row(
178
+ str(item.pid),
179
+ item.name,
180
+ f"{item.cpu_percent:.1f}%",
181
+ f"{item.memory_percent:.2f}%",
182
+ item.status,
183
+ item.username or "Unknown",
184
+ )
185
+
186
+ console.print(table)
187
+
188
+
189
+ @app.command()
190
+ def hardware() -> None:
191
+ """Analyze computer hardware specifications."""
192
+ data = HardwareAnalyzer.get_info()
193
+
194
+ table = Table(
195
+ title="Sysnexa Hardware Analyzer",
196
+ header_style="bold cyan",
197
+ )
198
+
199
+ table.add_column("Hardware Property")
200
+ table.add_column("Detected Value", justify="right")
201
+
202
+ table.add_row("Operating System", data.operating_system)
203
+ table.add_row("OS Release", data.os_release)
204
+ table.add_row("OS Version", data.os_version)
205
+ table.add_row("Architecture", data.architecture)
206
+ table.add_row("Processor", data.processor)
207
+ table.add_row(
208
+ "Physical CPU Cores",
209
+ str(data.physical_cores or "Unavailable"),
210
+ )
211
+ table.add_row(
212
+ "Logical CPU Cores",
213
+ str(data.logical_cores or "Unavailable"),
214
+ )
215
+ table.add_row("Total RAM", f"{data.total_ram_gb:.2f} GB")
216
+
217
+ console.print(table)
218
+
219
+
220
+ @app.command()
221
+ def diagnostics() -> None:
222
+ """Run a complete system health diagnostic."""
223
+ report = SystemDiagnostics.get_report()
224
+
225
+ status_colors = {
226
+ "Healthy": "green",
227
+ "Warning": "yellow",
228
+ "Critical": "red",
229
+ }
230
+
231
+ color = status_colors.get(report.status, "white")
232
+
233
+ console.print(
234
+ f"\n[bold {color}]System Status: {report.status}[/bold {color}]"
235
+ )
236
+
237
+ table = Table(
238
+ title="Sysnexa System Diagnostics",
239
+ header_style="bold cyan",
240
+ )
241
+
242
+ table.add_column("Component")
243
+ table.add_column("Usage", justify="right")
244
+
245
+ table.add_row("CPU", f"{report.cpu_usage:.1f}%")
246
+ table.add_row("RAM", f"{report.ram_usage:.1f}%")
247
+ table.add_row("Disk Partitions", str(report.disk_count))
248
+
249
+ console.print(table)
250
+
251
+ if report.issues:
252
+ issue_table = Table(
253
+ title="Detected Issues",
254
+ header_style="bold red",
255
+ )
256
+
257
+ issue_table.add_column("Component")
258
+ issue_table.add_column("Severity")
259
+ issue_table.add_column("Message")
260
+
261
+ for issue in report.issues:
262
+ issue_table.add_row(
263
+ issue.component,
264
+ issue.severity,
265
+ issue.message,
266
+ )
267
+
268
+ console.print(issue_table)
269
+ else:
270
+ console.print(
271
+ "[bold green]No system issues detected![/bold green]"
272
+ )
273
+
274
+
275
+ @app.command()
276
+ def export(
277
+ format: str = typer.Option(
278
+ "json",
279
+ "--format",
280
+ "-f",
281
+ help="Report format: json, csv, or html.",
282
+ ),
283
+ output: str | None = typer.Option(
284
+ None,
285
+ "--output",
286
+ "-o",
287
+ help="Output file path.",
288
+ ),
289
+ ) -> None:
290
+ """Export a system report to JSON, CSV, or HTML."""
291
+ selected_format = format.lower().strip()
292
+
293
+ extensions = {
294
+ "json": ".json",
295
+ "csv": ".csv",
296
+ "html": ".html",
297
+ }
298
+
299
+ if selected_format not in extensions:
300
+ console.print(
301
+ "[bold red]Unsupported format. Choose json, csv, or html.[/bold red]"
302
+ )
303
+ raise typer.Exit(code=1)
304
+
305
+ if output is None:
306
+ output = f"sysnexa-report{extensions[selected_format]}"
307
+
308
+ try:
309
+ saved_path = SystemReportExporter.export(
310
+ output=Path(output),
311
+ format=selected_format,
312
+ )
313
+
314
+ console.print(
315
+ "[bold green]Report exported successfully![/bold green]"
316
+ )
317
+ console.print(f"[cyan]Saved to:[/cyan] {saved_path}")
318
+
319
+ except Exception as exc:
320
+ console.print(f"[bold red]Export failed:[/bold red] {exc}")
321
+ raise typer.Exit(code=1) from exc
322
+
323
+
324
+ @app.command()
325
+ def performance() -> None:
326
+ """Display the overall system performance score."""
327
+ result = PerformanceAnalyzer.analyze()
328
+
329
+ history_store = PerformanceHistory()
330
+ history_store.save(result)
331
+
332
+ grade_colors = {
333
+ "Excellent": "bold green",
334
+ "Good": "bold cyan",
335
+ "Fair": "bold yellow",
336
+ "Poor": "bold red",
337
+ }
338
+
339
+ color = grade_colors.get(result.grade, "white")
340
+
341
+ console.print(
342
+ f"\n[{color}]System Performance: "
343
+ f"{result.total_score:.2f}/100 — {result.grade}[/{color}]"
344
+ )
345
+
346
+ table = Table(
347
+ title="Sysnexa Performance Analysis",
348
+ header_style="bold cyan",
349
+ )
350
+
351
+ table.add_column("Component")
352
+ table.add_column("Score", justify="right")
353
+
354
+ table.add_row("CPU", f"{result.cpu_score:.2f}/100")
355
+ table.add_row("RAM", f"{result.ram_score:.2f}/100")
356
+ table.add_row("Disk", f"{result.disk_score:.2f}/100")
357
+
358
+ console.print(table)
359
+
360
+ recommendation_table = Table(
361
+ title="Performance Recommendations",
362
+ header_style="bold yellow",
363
+ )
364
+
365
+ recommendation_table.add_column("No.", justify="right")
366
+ recommendation_table.add_column("Recommendation")
367
+
368
+ for index, recommendation in enumerate(
369
+ result.recommendations,
370
+ start=1,
371
+ ):
372
+ recommendation_table.add_row(
373
+ str(index),
374
+ recommendation,
375
+ )
376
+
377
+ console.print(recommendation_table)
378
+
379
+
380
+ @app.command()
381
+ def history(
382
+ limit: int = typer.Option(10, "--limit", "-l"),
383
+ compare: bool = typer.Option(False, "--compare", "-c"),
384
+ ) -> None:
385
+ """Display saved performance history."""
386
+ history_store = PerformanceHistory()
387
+
388
+ try:
389
+ records = history_store.get_history(limit=limit)
390
+ except (ValueError, OSError) as exc:
391
+ console.print(f"[red]Unable to read history: {exc}[/red]")
392
+ raise typer.Exit(code=1) from exc
393
+
394
+ if not records:
395
+ console.print(
396
+ "[yellow]No performance history found. "
397
+ "Run 'sysnexa performance' first.[/yellow]"
398
+ )
399
+ return
400
+
401
+ table = Table(title="Sysnexa Performance History")
402
+ table.add_column("Timestamp")
403
+ table.add_column("Score", justify="right")
404
+ table.add_column("Grade")
405
+ table.add_column("CPU", justify="right")
406
+ table.add_column("RAM", justify="right")
407
+ table.add_column("Disk", justify="right")
408
+
409
+ for record in records:
410
+ table.add_row(
411
+ record["timestamp"],
412
+ f"{record['total_score']:.2f}",
413
+ record["grade"],
414
+ f"{record['cpu_score']:.2f}",
415
+ f"{record['ram_score']:.2f}",
416
+ f"{record['disk_score']:.2f}",
417
+ )
418
+
419
+ console.print(table)
420
+
421
+ if compare:
422
+ comparison = history_store.compare_latest()
423
+
424
+ if comparison is None:
425
+ console.print("[yellow]Need at least two records.[/yellow]")
426
+ return
427
+
428
+ difference = comparison["difference"]
429
+ color = "green" if difference >= 0 else "red"
430
+
431
+ console.print(
432
+ f"[{color}]Score change: {difference:+.2f} points[/{color}]"
433
+ )
434
+
435
+
436
+ @app.command()
437
+ def trend(
438
+ limit: int = typer.Option(
439
+ 30,
440
+ "--limit",
441
+ "-l",
442
+ help="Number of recent records to analyze.",
443
+ ),
444
+ output: Path = typer.Option( # noqa: B008
445
+ Path("performance-trend.png"),
446
+ "--output",
447
+ "-o",
448
+ help="Output chart image path.",
449
+ ),
450
+ ) -> None:
451
+ """Analyze and visualize performance history."""
452
+ if limit < 1:
453
+ console.print("[red]Limit must be greater than zero.[/red]")
454
+ raise typer.Exit(code=1)
455
+
456
+ history_store = PerformanceHistory()
457
+ analyzer = PerformanceTrend()
458
+
459
+ try:
460
+ records = history_store.get_history(limit=limit)
461
+
462
+ if not records:
463
+ console.print(
464
+ "[yellow]No performance history found. "
465
+ "Run 'sysnexa performance' first.[/yellow]"
466
+ )
467
+ return
468
+
469
+ summary = analyzer.analyze(records)
470
+ chart_path = analyzer.generate_chart(records, output)
471
+
472
+ except (ValueError, OSError, KeyError, TypeError) as exc:
473
+ console.print(f"[red]Trend analysis failed: {exc}[/red]")
474
+ raise typer.Exit(code=1) from exc
475
+
476
+ table = Table(
477
+ title="Sysnexa Performance Trend",
478
+ header_style="bold cyan",
479
+ )
480
+
481
+ table.add_column("Metric")
482
+ table.add_column("Value", justify="right")
483
+
484
+ table.add_row("Total Records", str(summary.total_records))
485
+ table.add_row("Average Score", f"{summary.average_score:.2f}/100")
486
+ table.add_row("Highest Score", f"{summary.highest_score:.2f}/100")
487
+ table.add_row("Lowest Score", f"{summary.lowest_score:.2f}/100")
488
+ table.add_row("Latest Score", f"{summary.latest_score:.2f}/100")
489
+ table.add_row("Trend", summary.trend)
490
+
491
+ console.print(table)
492
+
493
+ console.print(
494
+ f"\n[bold green]Chart saved successfully:[/bold green] "
495
+ f"{chart_path.resolve()}"
496
+ )
497
+
498
+
499
+ @app.command()
500
+ def report(
501
+ output_format: str = typer.Option(
502
+ "html",
503
+ "--format",
504
+ "-f",
505
+ help="Report format: html, json, or csv.",
506
+ ),
507
+ output: Path | None = typer.Option( # noqa: B008
508
+ None,
509
+ "--output",
510
+ "-o",
511
+ help="Custom report output path.",
512
+ ),
513
+ ) -> None:
514
+ """Generate a complete Sysnexa system health report."""
515
+
516
+ output_format = output_format.lower()
517
+
518
+ if output_format not in {"html", "json", "csv"}:
519
+ console.print(
520
+ "[red]Invalid format. Choose html, json, or csv.[/red]"
521
+ )
522
+ raise typer.Exit(code=1)
523
+
524
+ if output is None:
525
+ output = Path(f"sysnexa-health-report.{output_format}")
526
+
527
+ try:
528
+ # Collect existing system information and diagnostics.
529
+ report_data = SystemReportExporter.collect_report()
530
+
531
+ # Add performance analysis.
532
+ performance_result = PerformanceAnalyzer().analyze()
533
+
534
+ report_data["performance"] = {
535
+ "total_score": performance_result.total_score,
536
+ "grade": performance_result.grade,
537
+ "cpu_score": performance_result.cpu_score,
538
+ "ram_score": performance_result.ram_score,
539
+ "disk_score": performance_result.disk_score,
540
+ "recommendations": performance_result.recommendations,
541
+ }
542
+
543
+ # Add recent performance history.
544
+ history_store = PerformanceHistory()
545
+ report_data["performance_history"] = (
546
+ history_store.get_history(limit=10)
547
+ )
548
+
549
+ # Export complete report.
550
+ exported_path = SystemReportExporter.export(
551
+ output,
552
+ format=output_format,
553
+ report=report_data,
554
+ )
555
+
556
+ except (ValueError, OSError, KeyError, TypeError) as exc:
557
+ console.print(f"[red]Report generation failed: {exc}[/red]")
558
+ raise typer.Exit(code=1) from exc
559
+
560
+ table = Table(
561
+ title="Sysnexa System Health Report",
562
+ header_style="bold cyan",
563
+ )
564
+
565
+ table.add_column("Metric")
566
+ table.add_column("Result", justify="right")
567
+
568
+ table.add_row(
569
+ "Performance Score",
570
+ f"{performance_result.total_score:.2f}/100",
571
+ )
572
+ table.add_row("Performance Grade", performance_result.grade)
573
+ table.add_row(
574
+ "History Records",
575
+ str(len(report_data["performance_history"])),
576
+ )
577
+ table.add_row("Export Format", output_format.upper())
578
+
579
+ console.print(table)
580
+ console.print(
581
+ f"\n[bold green]Report generated:[/bold green] "
582
+ f"{exported_path.resolve()}"
583
+ )
584
+
585
+
586
+ if __name__ == "__main__":
587
+ app()
File without changes