Skip to content

Commit c9e4c8e

Browse files
committed
Refactor argument handling in start.py and improve signal management; update start.sh cleanup function
1 parent 0e47168 commit c9e4c8e

File tree

2 files changed

+73
-49
lines changed

2 files changed

+73
-49
lines changed

start.py

Lines changed: 71 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
def run_server_script(args):
2020
rpc_port = args.rpc_port
21-
if args.use_random_port or args.use_different_port:
21+
if args.use_random_rpc_port or args.use_different_rpc_port:
2222
import socket
2323
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
2424
s.bind(('localhost', 0))
@@ -27,6 +27,9 @@ def run_server_script(args):
2727
# Define a wrapper function to pass the arguments to the main function
2828
def server_main():
2929
import sys
30+
# Reset signal handlers to default in the child process
31+
signal.signal(signal.SIGINT, signal.SIG_DFL)
32+
signal.signal(signal.SIGTERM, signal.SIG_DFL)
3033
sys.argv = ['server.py', '--rpc-port', str(rpc_port), '--log-dir', log_dir]
3134
if args.disable_log_file:
3235
sys.argv += ['--disable-log-file']
@@ -41,7 +44,10 @@ def run_start_script(args, rpc_port):
4144
# Start the start.sh script in its own directory as a new process group
4245
arguments = ['bash']
4346
if args.player or args.coach or args.goalie:
44-
arguments += ['start-agent.sh', '--coach' if args.coach else '--goalie' if args.goalie else '--player']
47+
if args.debug:
48+
arguments += ['start-agent-debug.sh', '--coach' if args.coach else '--goalie' if args.goalie else '--player']
49+
else:
50+
arguments += ['start-agent.sh', '--coach' if args.coach else '--goalie' if args.goalie else '--player']
4551
else:
4652
arguments += ['start.sh' if not args.debug else 'start-debug.sh']
4753

@@ -95,27 +101,47 @@ def kill_rpc_server_process(processes):
95101
pass # The process might have already exited
96102

97103
def check_args(args):
98-
pass
104+
if args.team_name != 'CLS' and args.use_random_name:
105+
raise ValueError("Cannot use both --team_name and --use-random-name")
106+
if args.rpc_port != '50051' and args.use_random_rpc_port:
107+
raise ValueError("Cannot use both --rpc-port and --use-random-rpc-port")
108+
if args.rpc_port != '50051' and args.use_different_rpc_port:
109+
raise ValueError("Cannot use both --rpc-port and --use-different-rpc-port")
110+
if args.use_random_rpc_port and args.use_different_rpc_port:
111+
raise ValueError("Cannot use both --use-random-port and --use-different-rpc-port")
112+
if args.player and args.coach:
113+
raise ValueError("Cannot use both --player and --coach")
114+
if args.player and args.goalie:
115+
raise ValueError("Cannot use both --player and --goalie")
116+
if args.coach and args.goalie:
117+
raise ValueError("Cannot use both --coach and --goalie")
118+
if (args.player or args.coach or args.goalie) and args.use_different_rpc_port:
119+
raise ValueError("Cannot use --player, --coach, or --goalie with --use-different-rpc-port")
120+
if args.disable_log_file and args.log_dir:
121+
raise ValueError("Cannot use both --disable-log-file and --log-dir")
122+
99123

100124
if __name__ == "__main__":
101125
# Set up argument parsing
102126
parser = argparse.ArgumentParser(description='Run server and team scripts.')
103127
parser.add_argument('-t', '--team_name', required=False, help='The name of the team', default='CLS')
104-
parser.add_argument('--rpc-port', required=False, help='The port of the server', default='50051')
105-
parser.add_argument('-d', '--debug', required=False, help='Enable debug mode', default=False, action='store_true')
106-
parser.add_argument('--use-random-port', required=False, help='Use a random port for the server', default=False, action='store_true')
128+
parser.add_argument('--rpc-port', required=False, help='The port of the rpc server', default='50051')
129+
parser.add_argument('-d', '--debug', required=False, help='Enable debug mode for agents', default=False, action='store_true')
130+
parser.add_argument('--use-random-rpc-port', required=False, help='Use a random port for the rpc server', default=False, action='store_true')
107131
parser.add_argument('--use-random-name', required=False, help='Use a random team name', default=False, action='store_true')
108-
parser.add_argument('--use-different-port', required=False, help='Use a different port for the rpc server', default=False, action='store_true')
109-
parser.add_argument('--server-host', required=False, help='The host of the server', default='localhost')
110-
parser.add_argument('--server-port', required=False, help='The port of the server', default='6000')
111-
parser.add_argument('--close-server', required=False, help='Close the server', default=False, action='store_true')
112-
parser.add_argument('--player', required=False, help='Use coach instead of proxy', default=False, action='store_true')
113-
parser.add_argument('--coach', required=False, help='Use coach instead of proxy', default=False, action='store_true')
114-
parser.add_argument('--goalie', required=False, help='Use goalie instead of proxy', default=False, action='store_true')
132+
parser.add_argument('--use-different-rpc-port', required=False, help='Use a different port for the rpc server', default=False, action='store_true')
133+
parser.add_argument('--server-host', required=False, help='The host of the robocup soccer server', default='localhost')
134+
parser.add_argument('--server-port', required=False, help='The port of the robocup soccer server', default='6000')
135+
parser.add_argument('--auto-close-rpc-server', required=False, help='Close the server after finished agent processing', default=False, action='store_true')
136+
parser.add_argument('--player', required=False, help='Run one agent proxy as player', default=False, action='store_true')
137+
parser.add_argument('--coach', required=False, help='Run one agent proxy as coach', default=False, action='store_true')
138+
parser.add_argument('--goalie', required=False, help='Run one agent proxy as goalie', default=False, action='store_true')
115139
parser.add_argument('--disable-log-file', required=False, help='Disable logging to a file', default=False, action='store_true')
116140
parser.add_argument('--log-dir', required=False, help='The directory to store logs', default=None)
117141
args = parser.parse_args()
118142

143+
check_args(args)
144+
119145
# Set up logging
120146
if not args.log_dir:
121147
log_dir = os.path.join(os.getcwd(), 'logs', f"{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}_{random.randint(100000, 999999)}")
@@ -125,6 +151,12 @@ def check_args(args):
125151

126152
start_team_logger.debug(f"Arguments: {args=}")
127153

154+
def signal_handler(sig, frame):
155+
raise KeyboardInterrupt
156+
157+
signal.signal(signal.SIGTERM, signal_handler)
158+
signal.signal(signal.SIGINT, signal_handler)
159+
128160
try:
129161
if args.use_random_name:
130162
import random
@@ -134,7 +166,7 @@ def check_args(args):
134166
# Run the server.py script first
135167
all_server_processes = []
136168
all_start_processes = []
137-
if args.use_different_port:
169+
if args.use_different_rpc_port:
138170
for i in range(13):
139171
server_process, rpc_port = run_server_script(args)
140172
all_server_processes.append(server_process)
@@ -168,42 +200,12 @@ def check_args(args):
168200
start_threads.append(threading.Thread(target=stream_output_to_file, args=(start_process, 'proxy' if len(all_start_processes) == 1 else f'porxy_{i}', args)))
169201
start_threads[-1].start()
170202

171-
def signal_handler(sig, frame):
172-
start_team_logger.info('Received signal to terminate. Cleaning up...')
173-
kill_rpc_server_process(all_server_processes)
174-
for server_process in all_server_processes:
175-
server_process.join()
176-
start_team_logger.debug(f"server.py ended with PID: {server_process.pid}")
177-
178-
start_team_logger.debug("all_server_processes has finished.")
179-
180-
kill_process_group(all_start_processes)
181-
for start_process in all_start_processes:
182-
start_process.wait()
183-
start_team_logger.debug(f"start.sh ended with PID: {start_process.pid}")
184-
185-
start_team_logger.debug("all_start_processes has finished.")
186-
187-
stop_thread.set()
188-
189-
start_team_logger.debug("Waiting for start_thread to finish...")
190-
for start_thread in start_threads:
191-
start_thread.join()
192-
193-
start_team_logger.debug("start_thread has finished.")
194-
195-
start_team_logger.info('All processes have been killed.')
196-
raise KeyboardInterrupt
197-
# os._exit(0)
198-
signal.signal(signal.SIGTERM, signal_handler)
199-
signal.signal(signal.SIGINT, signal_handler)
200-
201203
# Wait for both threads to finish
202204
for start_thread in start_threads:
203205
start_thread.join()
204206
start_team_logger.debug("agents has been exited.")
205207

206-
if args.close_server:
208+
if args.auto_close_rpc_server:
207209
start_team_logger.debug("Closing rpc server ...")
208210
kill_rpc_server_process(all_server_processes)
209211
start_team_logger.debug("rpc Server has been closed.")
@@ -215,12 +217,33 @@ def signal_handler(sig, frame):
215217

216218
start_team_logger.info("Both processes have exited.")
217219
except KeyboardInterrupt:
218-
start_team_logger.debug("Interrupted! Killing all processes.")
220+
start_team_logger.info('Received signal to terminate. Cleaning up...')
221+
# Perform cleanup operations here
219222
kill_rpc_server_process(all_server_processes)
223+
for server_process in all_server_processes:
224+
server_process.join()
225+
start_team_logger.debug(f"server.py ended with PID: {server_process.pid}")
226+
227+
start_team_logger.debug("All server processes have finished.")
228+
220229
kill_process_group(all_start_processes)
221-
230+
for start_process in all_start_processes:
231+
start_process.wait()
232+
start_team_logger.debug(f"start.sh ended with PID: {start_process.pid}")
233+
234+
start_team_logger.debug("All start processes have finished.")
235+
236+
stop_thread.set()
237+
238+
start_team_logger.debug("Waiting for start threads to finish...")
239+
for start_thread in start_threads:
240+
start_thread.join()
241+
242+
start_team_logger.debug("Start threads have finished.")
243+
244+
start_team_logger.info('All processes have been killed.')
222245
finally:
223246
# Ensure all processes are killed on exit
224-
start_team_logger.debug("Final Cleaning up...")
247+
start_team_logger.debug("Final cleanup...")
225248
kill_rpc_server_process(all_server_processes)
226249
kill_process_group(all_start_processes)

start.sh

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ echo "Options: $options"
1111
# Function to handle termination
1212
cleanup() {
1313
echo "Terminating all start_agent.py processes..."
14-
kill $pid
14+
sleep 2
15+
# kill $pid
1516
exit 0
1617
}
1718

0 commit comments

Comments
 (0)