-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservices_feature.py
More file actions
176 lines (141 loc) · 6.86 KB
/
services_feature.py
File metadata and controls
176 lines (141 loc) · 6.86 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
import subprocess
from flask import Blueprint, jsonify, render_template, request, session
from systemd_manager import SystemdManager
from auth import SUDO_SESSION_KEY, is_authenticated, run_sudo
from config_store import load_config, save_favorites
_socketio = None
def init_services_socketio(socketio):
global _socketio
_socketio = socketio
def build_services_blueprint() -> Blueprint:
bp = Blueprint('services', __name__)
@bp.route('/')
def index():
return render_template('services.html')
@bp.route('/journal/<service>')
def get_journal(service: str):
sudo_password = session.get(SUDO_SESSION_KEY)
logs = SystemdManager.get_journal_logs(service, sudo_password=sudo_password)
return {'logs': logs}
@bp.route('/api/devices')
def get_devices():
try:
result = subprocess.run(['ip', 'link'], capture_output=True, text=True, check=True)
output = result.stdout
devices = []
interfaces = output.strip().split('\n')
i = 0
while i < len(interfaces):
if interfaces[i].strip().startswith(tuple(str(x) + ':' for x in range(10))):
parts = interfaces[i].split(':')
if len(parts) > 2:
interface_name = parts[1].strip()
operstate_result = subprocess.run(
['cat', f'/sys/class/net/{interface_name}/operstate'],
capture_output=True,
text=True,
)
operstate = operstate_result.stdout.strip()
mac_result = subprocess.run(
['cat', f'/sys/class/net/{interface_name}/address'],
capture_output=True,
text=True,
)
mac_address = mac_result.stdout.strip()
if interface_name.startswith('wlan'):
device_type = 'Wireless'
elif interface_name.startswith(('eth', 'enp')):
device_type = 'Ethernet'
elif interface_name.startswith('docker'):
device_type = 'Docker'
elif interface_name == 'lo':
device_type = 'Loopback'
else:
device_type = 'Unknown'
devices.append(
{
'type': device_type,
'name': interface_name,
'mac': mac_address,
'operstate': operstate,
}
)
i += 1
return jsonify(devices)
except subprocess.CalledProcessError as e:
return jsonify({'error': str(e)}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
@bp.route('/favorites', methods=['GET'])
def get_favorites():
config = load_config()
return jsonify(favorites=config['services']['favorites'])
@bp.route('/favorites', methods=['POST'])
def update_favorites():
new_favorites = request.json.get('favorites', [])
save_favorites(new_favorites)
return jsonify(success=True)
@bp.route('/service/<service>', methods=['DELETE'])
def delete_service(service: str):
sudo_password = session.get(SUDO_SESSION_KEY)
if not sudo_password:
return (
jsonify({'success': False, 'error': 'sudo_required', 'message': 'Sudo password required.'}),
401,
)
success = SystemdManager.delete_service(service, sudo_password=sudo_password)
if success:
if _socketio is not None:
services = SystemdManager.get_all_services()
_socketio.emit('update_services', {'services': services})
return jsonify(success=True)
return jsonify(success=False), 400
@bp.route('/api/create_service', methods=['POST'])
def create_service():
service_content = request.json.get('serviceContent')
service_name = request.json.get('serviceName')
if not service_content or not service_name:
return jsonify(success=False, message='Service content and name are required'), 400
service_file_path = f'/etc/systemd/system/{service_name}.service'
sudo_password = session.get(SUDO_SESSION_KEY)
if not sudo_password:
return jsonify(success=False, error='sudo_required', message='Sudo password required.'), 401
try:
run_sudo(['tee', service_file_path], sudo_password, input_text=(service_content or '') + '\n', check=True)
run_sudo(['systemctl', 'enable', service_name], sudo_password, check=True)
run_sudo(['systemctl', 'start', service_name], sudo_password, check=True)
if _socketio is not None:
services = SystemdManager.get_all_services()
_socketio.emit('update_services', {'services': services})
return jsonify(success=True, message=f'Service {service_name} created and started successfully')
except subprocess.CalledProcessError as e:
return jsonify(success=False, message=f'Failed to create service: {str(e)}'), 500
except Exception as e:
return jsonify(success=False, message=f'Error creating service: {str(e)}'), 500
return bp
def register_services_socket_handlers(socketio):
@socketio.on('connect')
def handle_connect():
if not is_authenticated():
return False
services = SystemdManager.get_all_services()
socketio.emit('update_services', {'services': services})
@socketio.on('service_action')
def handle_service_action(data):
if not is_authenticated():
socketio.emit('console_output', {'output': '[ERROR] Not authenticated'}, room=request.sid)
return
service = (data or {}).get('service')
action = (data or {}).get('action')
if not service or not action:
return
sudo_password = session.get(SUDO_SESSION_KEY)
if not sudo_password:
socketio.emit('sudo_required', {'message': 'Sudo password required to control services.'}, room=request.sid)
socketio.emit('console_output', {'output': '[ERROR] Sudo password required'}, room=request.sid)
return
success = SystemdManager.control_service(service, action, sudo_password=sudo_password)
if success:
services = SystemdManager.get_all_services()
socketio.emit('update_services', {'services': services})
__all__ = ['build_services_blueprint', 'init_services_socketio', 'register_services_socket_handlers']