-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_console.py
More file actions
149 lines (137 loc) · 4.94 KB
/
admin_console.py
File metadata and controls
149 lines (137 loc) · 4.94 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
import socket
import sys
class AdminConsole:
def __init__(self, host='localhost', port=5000):
self.host, self.port, self.socket = host, port, None
def _read_line(self):
buf = ""
try:
while True:
c = self.socket.recv(1).decode('utf-8')
if not c: return None
if c == '\n': return buf.strip()
buf += c
except: return None
def _send(self, msg):
self.socket.send((msg + '\n').encode('utf-8'))
def connect(self):
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
self._send("ADMIN")
if self._read_line() != "AUTH_REQUIRED":
return False
print("\n=== ADMIN AUTHENTICATION ===")
self._send(input("Username: "))
self._send(input("Password: "))
if self._read_line() != "AUTH_SUCCESS":
print("Authentication failed.")
return False
print("Authentication successful!\n")
return True
except ConnectionRefusedError:
print(f"Error: Could not connect to {self.host}:{self.port}")
return False
def disconnect(self):
if self.socket:
try:
self._send("quit")
except:
pass
self.socket.close()
def _get_responses(self, cmd):
self._send(cmd)
res = []
while True:
line = self._read_line()
if not line or line in ("END", "BYE"):
break
res.append(line)
return res
def cmd_status(self):
print("\n=== SYSTEM STATUS ===")
for line in self._get_responses("status"):
p = line.split(None, 1)
if len(p) == 2:
k, v = p[0].replace('_', ' ').title(), p[1]
if 'Size Bytes' in k:
k = k.replace(' Bytes', '')
v = f"{int(v)/1048576:.2f} MB"
print(f" {k}: {v}")
print()
def cmd_servers(self):
res = self._get_responses("servers")
print("\n=== CONTENT SERVERS ===")
if res and res[0] == "NO_SERVERS":
print(" No servers registered")
else:
print(f" {'ID':<10} {'IP':<15} {'Port':<6} {'Status':<6} {'Load':<5} {'Files':<5} {'Size':<10} {'Updated'}")
print(" " + "-" * 70)
for line in res:
if line.startswith("SERVER "):
p = line.split()
if len(p) >= 9:
st = "[OK]" if p[4] == "alive" else "[X]"
size_mb = f"{int(p[7])/1048576:.2f} MB"
print(f" {p[1]:<10} {p[2]:<15} {p[3]:<6} {st:<6} {p[5]:<5} {p[6]:<5} {size_mb:<10} {p[8]}s ago")
print()
def cmd_files(self):
res = self._get_responses("files")
print("\n=== FILE LOCATIONS ===")
if res and res[0] == "NO_FILES":
print(" No files registered")
else:
files = []
for line in res:
if line.startswith("FILE "):
p = line.split(None, 2)
if len(p) >= 3:
for srv in p[2].split(','):
files.append((srv.strip(), p[1]))
files.sort(key=lambda x: (x[0], x[1]))
print(f" {'Server':<12} {'Filename'}")
print(" " + "-" * 40)
prev_srv = None
for srv, fname in files:
if prev_srv and prev_srv != srv:
print()
print(f" {srv:<12} {fname}")
prev_srv = srv
print()
def run(self):
print("\n" + "=" * 40)
print(" INDEX SERVER ADMIN CONSOLE")
print("=" * 40)
print("\nCommands: status, servers, files, quit\n")
while True:
try:
cmd = input("admin> ").strip().lower()
if not cmd:
continue
elif cmd == "status":
self.cmd_status()
elif cmd == "servers":
self.cmd_servers()
elif cmd == "files":
self.cmd_files()
elif cmd in ("quit", "exit"):
break
elif cmd in ("clear", "cls"):
print("\033[H\033[J", end="")
else: print(f"Unknown: {cmd}")
except (KeyboardInterrupt, EOFError):
break
def main():
host, port = 'localhost', 5000
if len(sys.argv) > 1:
host = sys.argv[1]
if len(sys.argv) > 2:
port = int(sys.argv[2])
console = AdminConsole(host, port)
if console.connect():
try:
console.run()
finally:
console.disconnect()
if __name__ == '__main__':
main()