-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
249 lines (209 loc) · 8.28 KB
/
server.py
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
import socket
import logging
from pathlib import Path
from typing import List, Tuple
import multiprocessing as mp
import connectn.utils as cu
cu.parse_arguments()
def run_server():
from connectn.tournament import run_tournament_process
from multiprocessing.managers import SyncManager
cu.configure_logging(cu.SERVER_PROCESS_LOG)
logger = logging.getLogger(__name__)
cu.start_stunnel(True)
manager = SyncManager()
manager.start(_process_init)
sq = mp.Queue()
rq = manager.Queue()
shutdown = manager.Event()
rg = mp.Process(
target=_process_init,
args=(run_tournament_process, sq, rq, shutdown, cu.PLAY_ALL),
name="RunGames",
)
rg.start()
logger.info("Started run_games process")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as ls:
try:
ls.settimeout(5.0)
ls.bind(("localhost", cu.LISTEN_PORT))
ls.listen(5)
logger.info("Started server listening socket")
except Exception:
logger.exception("Failure when binding to the listening port.")
else:
updated_agent_archives = []
running = True
while running:
try:
(cs, addr) = ls.accept()
logger.info("Accepted connection.")
handle_client(cs, updated_agent_archives)
except socket.timeout:
if len(updated_agent_archives):
logger.info(
f"Server sending {len(updated_agent_archives)} new agents for game-play."
)
logger.info(f"{updated_agent_archives}")
sq.put(updated_agent_archives)
updated_agent_archives = []
except cu.InactiveSocket:
logger.exception("Connection failed")
except KeyboardInterrupt:
inp = input("Shutdown? y/[n] ").lower()
while inp not in ("", "y", "n"):
inp = input("Shutdown? y/[n] ").lower()
if inp == "y":
logger.info("KeyboardInterrupt: Shutting down")
running = False
else:
inp = input("Play all games? y/[n] ").lower()
while inp not in ("", "y", "n"):
inp = input("Play all games? y/[n] ").lower()
if inp == "y":
sq.put("PLAY_ALL")
except Exception:
logger.exception("Unexpected error, will try to keep running.")
store_results_local(rq)
finally:
"""
If the port is orphaned use:
fuser -kn tcp <port>
"""
ls.shutdown(socket.SHUT_RDWR)
logger.info("Closed server socket")
logger.info("Telling run_games process to shutdown.")
shutdown.set()
rg.join()
logger.info("Finished server shutdown.")
def store_results_local(rq: mp.Queue):
from queue import Empty as EmptyQueue
logger = logging.getLogger(__name__)
try:
updated_results = rq.get(block=False)
except EmptyQueue:
pass
else:
if updated_results:
logger.info(f"Storing {len(updated_results)} result files.")
for file_name, results_data in updated_results.items():
with open(f"{results_file_name_local(file_name)!s}", "wb") as f:
f.write(results_data)
logger.info("Finished storing the result files.")
def results_file_name_local(file_name: str) -> Path:
return (cu.SERVER_PROCESS_DATA_DIR / file_name).with_suffix(".h5")
def handle_client(cs: socket.socket, updated_agent_archives: list):
from time import sleep
from connectn.users import authenticate_user
logger = logging.getLogger(__name__)
with cu.ComfyStockings(cs) as scs:
scs.handshake_wait()
try:
client_protocol = int(scs.read_wait())
except ValueError:
client_protocol = -1
if client_protocol < cu.PROTOCOL_VERSION:
scs.write("PROTOCOL VERSION FAILURE")
else:
scs.write("OK")
uid_pw = scs.read_wait().split(",")
logger.info(f"Authentication attempt by: {uid_pw[0]}")
login_valid = len(uid_pw) == 2 and authenticate_user(*uid_pw)
msg = "OK" if login_valid else "FAIL"
scs.write(msg)
if login_valid:
logger.info("Authentication successful.")
# User is prompted to choose upload or download
up_or_down = scs.read_wait()
if up_or_down == "UPLOAD":
msg = handle_upload(scs, uid_pw[0], updated_agent_archives)
elif up_or_down == "DOWNLOAD":
msg = handle_download(scs, uid_pw[0])
else:
msg = "FAIL"
scs.write(msg)
else:
logger.info("Authentication failed.")
sleep(0.5)
while scs.active:
logger.info("Waiting for socket to become inactive")
sleep(1.0)
def handle_upload(
scs: cu.ComfyStockings, username: str, updated_agent_archives: List[Tuple[str, str]]
) -> str:
import os
import tempfile
logger = logging.getLogger(__name__)
scs.write("READY")
bytes_expected = int(scs.read_wait())
logger.info(f"Now starting transfer of {bytes_expected} bytes")
data = scs.read_wait(timeout=60.)
bytes_received = len(data)
logger.info(f"Received bytes {bytes_received}, expected {bytes_expected}")
msg = "FAIL"
if bytes_received == bytes_expected:
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(data)
exists = None
for pending in updated_agent_archives:
if pending[0] == username:
logger.warning(
f"Found pending update. It will be overwritten {pending}"
)
exists = pending
os.remove(pending[1])
if exists is not None:
updated_agent_archives.remove(exists)
updated_agent_archives.append((username, f.name))
msg = "OK"
return msg
def handle_download(scs: cu.ComfyStockings, username: str) -> str:
import os
import time
logger = logging.getLogger(__name__)
# Client is asked whether to download their agent file, or all matches (tournament)
msg = scs.read_wait()
if msg == "TOURNAMENT":
results_path = results_file_name_local(cu.TOURNAMENT_FILE)
else:
results_path = results_file_name_local(username)
t = time.gmtime(os.path.getmtime(f"{results_path!s}"))
scs.write(time.strftime("%Y-%m-%d-%Hh%Mm%Ss", t))
response = scs.read_wait()
logger.info(f"Response to prompt: {response}")
# Client is shown date/time of file creation and prompted whether to download
if response == "GO":
logger.info(f"User {username} chose to proceed with download.")
file_size = os.path.getsize(f"{results_path!s}")
scs.write(f"{file_size!s}")
with open(f"{results_path!s}", "rb") as f:
scs.write(f.read())
msg = scs.read_wait(timeout=60.0)
if msg == "OK":
logger.info(f"User {username} successfully received results file.")
else:
logger.error(f"User {username} failed to receive results file: {msg}")
else:
logger.info(f"User {username} chose to skip download.")
msg = "OK"
return msg
def _process_init(func=None, *args):
"""
This function is used to initialize processes that need to ignore
the KeyboardInterrupt / SIGINT signal. This includes the
multiprocessing SyncManager and the run_games process.
Parameters
----------
func : Callable, optional
args : Positional arguments for func
"""
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)
if func is not None:
func(*args)
if __name__ == "__main__":
if not cu.ROOT_DATA_DIR.exists():
cu.ROOT_DATA_DIR.mkdir()
if not cu.SERVER_PROCESS_DATA_DIR.exists():
cu.SERVER_PROCESS_DATA_DIR.mkdir()
run_server()