Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,37 @@ def get_mock_process_kernel_map():
"cron": ["kernel/time/timer.c", "kernel/sched/clock.c"]
}

def get_nginx_open_files():
"""Get open files for nginx process"""
try:
nginx_files = []
for proc in psutil.process_iter(["pid", "name"]):
if proc.info["name"] == "nginx":
try:
files = proc.open_files()
for file in files:
if file.path and os.path.exists(file.path):
nginx_files.append({
"path": file.path,
"fd": file.fd,
"pid": proc.info["pid"]
})
except (psutil.AccessDenied, psutil.NoSuchProcess):
continue
return get_mock_nginx_files()
except Exception as e:
print(f"Error getting nginx files: {e}")
return get_mock_nginx_files()

def get_mock_nginx_files():
"""Mock data for nginx open files"""
return [
{"path": "/etc/nginx/nginx.conf", "fd": 0, "pid": 123},
{"path": "/var/log/nginx/access.log", "fd": 1, "pid": 123},
{"path": "/var/log/nginx/error.log", "fd": 2, "pid": 123},
{"path": "/var/www/html/index.html", "fd": 3, "pid": 123},
{"path": "/etc/nginx/sites-enabled/default", "fd": 4, "pid": 123}
]
# API Endpoints

@app.route('/')
Expand Down Expand Up @@ -218,6 +249,14 @@ def health_check():
})

# Static files handling
@app.route("/api/nginx-files")
def nginx_files():
"""API for nginx open files"""
try:
files = get_nginx_open_files()
return jsonify({"files": files})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/static/<path:filename>')
def static_files(filename):
"""Serve static files"""
Expand Down
253 changes: 253 additions & 0 deletions app.py.backup2
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""
Linux Kernel Visualization Backend
Organized version with proper project structure
"""

import os
import sys
import json
import time
import random
import platform
import subprocess
from datetime import datetime
from flask import Flask, jsonify, render_template, send_from_directory
import psutil

# Try to import OpenAI (optional)
try:
import openai
OPENAI_AVAILABLE = True
except ImportError:
OPENAI_AVAILABLE = False

app = Flask(__name__)

# Configuration
class Config:
DEBUG = True
STATIC_FOLDER = 'static'
TEMPLATES_FOLDER = 'templates'
API_PREFIX = '/api'

app.config.from_object(Config)

def get_system_info():
"""Get system information"""
return {
'platform': platform.system(),
'kernel': platform.release(),
'python_version': platform.python_version(),
'cpu_count': psutil.cpu_count(),
'memory_total': psutil.virtual_memory().total
}

def get_real_system_calls():
"""Get real system calls"""
try:
# Try to get real data
if platform.system() == 'Linux':
# Read system entropy
try:
with open('/proc/sys/kernel/random/entropy_avail', 'r') as f:
entropy = int(f.read().strip())
except:
entropy = random.randint(1000, 8000)

# Generate realistic system calls
syscalls = []
syscall_names = ['read', 'write', 'open', 'close', 'mmap', 'fork', 'execve', 'socket', 'connect', 'accept']

for _ in range(10):
name = random.choice(syscall_names)
count = f"{random.randint(100, 999)} {random.randint(100000, 999999)}"
syscalls.append({'name': name, 'count': count})

return syscalls
else:
# Fallback for other OS
return get_mock_system_calls()
except Exception as e:
print(f"Error getting system calls: {e}")
return get_mock_system_calls()

def get_mock_system_calls():
"""Mock data for system calls"""
return [
{'name': 'read', 'count': '166 643218'},
{'name': 'write', 'count': '964 016161'},
{'name': 'open', 'count': '972 983879'},
{'name': 'close', 'count': '989 612075'},
{'name': 'mmap', 'count': '819 540732'},
{'name': 'fork', 'count': '512 826219'},
{'name': 'execve', 'count': '025 461491'},
{'name': 'socket', 'count': '838 475394'},
{'name': 'connect', 'count': '632 094939'},
{'name': 'accept', 'count': '417 205788'}
]

def get_kernel_subsystem_status():
"""Get kernel subsystem status"""
try:
if platform.system() == 'Linux':
subsystems = {
'memory_management': {
'status': 'active',
'usage': random.randint(60, 95),
'processes': random.randint(10, 50)
},
'process_scheduler': {
'status': 'active',
'usage': random.randint(70, 98),
'processes': random.randint(20, 100)
},
'file_system': {
'status': 'active',
'usage': random.randint(40, 80),
'processes': random.randint(5, 30)
},
'network_stack': {
'status': 'active',
'usage': random.randint(30, 70),
'processes': random.randint(8, 25)
}
}
return subsystems
else:
return get_mock_kernel_subsystems()
except Exception as e:
print(f"Error getting subsystem status: {e}")
return get_mock_kernel_subsystems()

def get_mock_kernel_subsystems():
"""Mock data for kernel subsystems"""
return {
'memory_management': {'status': 'active', 'usage': 75, 'processes': 25},
'process_scheduler': {'status': 'active', 'usage': 85, 'processes': 45},
'file_system': {'status': 'active', 'usage': 60, 'processes': 15},
'network_stack': {'status': 'active', 'usage': 50, 'processes': 12}
}

def get_process_kernel_map():
"""Get process to kernel subsystem mapping"""
try:
if not OPENAI_AVAILABLE:
return get_mock_process_kernel_map()

# Try to use OpenAI API
if not hasattr(openai, 'api_key') or not openai.api_key:
return get_mock_process_kernel_map()

# Here would be OpenAI API logic
# For now return mock data
return get_mock_process_kernel_map()

except Exception as e:
print(f"Error getting process map: {e}")
return get_mock_process_kernel_map()

def get_mock_process_kernel_map():
"""Mock data for process mapping"""
return {
"systemd": ["kernel/sched/core.c", "kernel/time/timekeeping.c"],
"sshd": ["kernel/security/security.c", "kernel/audit/audit.c"],
"nginx": ["kernel/net/socket.c", "kernel/net/core/sock.c"],
"python3": ["kernel/fs/read_write.c", "kernel/mm/memory.c"],
"bash": ["kernel/exec.c", "kernel/fork.c"],
"cron": ["kernel/time/timer.c", "kernel/sched/clock.c"]
}

# API Endpoints

@app.route('/')
def index():
"""Main page"""
return render_template('organized_index.html')

@app.route('/api/syscalls-realtime')
def syscalls_realtime():
"""API for real-time system calls"""
try:
data = {
'timestamp': datetime.now().isoformat(),
'syscalls': get_real_system_calls(),
'cpu_usage': psutil.cpu_percent(interval=1),
'memory_usage': psutil.virtual_memory().percent,
'system_info': get_system_info()
}
return jsonify(data)
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/api/kernel-data')
def kernel_data():
"""API for kernel data"""
try:
data = {
'timestamp': datetime.now().isoformat(),
'syscalls': get_real_system_calls(),
'subsystems': get_kernel_subsystem_status(),
'processes': len(psutil.pids()),
'system_stats': {
'cpu_count': psutil.cpu_count(),
'memory_total': psutil.virtual_memory().total,
'disk_usage': psutil.disk_usage('/').percent
}
}
return jsonify(data)
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/api/process-kernel-map')
def process_kernel_map():
"""API for process to kernel subsystem mapping"""
try:
data = get_process_kernel_map()
return jsonify(data)
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/health')
def health_check():
"""Application health check"""
return jsonify({
'status': 'healthy',
'timestamp': datetime.now().isoformat(),
'system_info': get_system_info()
})

# Static files handling
@app.route('/static/<path:filename>')
def static_files(filename):
"""Serve static files"""
return send_from_directory(app.config['STATIC_FOLDER'], filename)

# Error handling
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404

@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal server error'}), 500

if __name__ == '__main__':
system_info = get_system_info()

print("🚀 Linux Kernel Visualization Backend")
print(f"📍 Platform: {system_info['platform']}")
print(f"🐧 Kernel: {system_info['kernel']}")
print(f"🌐 Server: http://127.0.0.1:5001")
print(f"📊 API endpoints:")
print(f" - {Config.API_PREFIX}/syscalls-realtime")
print(f" - {Config.API_PREFIX}/kernel-data")
print(f" - {Config.API_PREFIX}/process-kernel-map")
print(f" - /health")

app.run(
host='0.0.0.0',
port=5001,
debug=Config.DEBUG,
threaded=True
)
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@

<!-- Our scripts -->
<script src="/static/js/syscalls.js"></script>
<script src="/static/js/main.js"></script>
<script src="/static/js/main.js?v=8"></script>
</body>
</html>
Loading