9 def setup_server_io(io_db):
10 """Fill IO files DB with proper file( path)s. Write process IO test string.
12 Set io_db["kicked_by_rival"] to False. Decide file paths. Ensure IO files
13 directory at server/. Remove any old in file if found. Set up new in file
14 (io_db["file_in"]) for reading at io_db["path_in"], and new out file
15 (io_db["file_out"]) for writing at io_db["path_out"]. Start out file with
16 process hash line of format PID + " " + floated UNIX time
17 (io_db["teststring"]). Run detect_atomic_leftover on io_db["path_record"]
18 and io_db["path_save"].
21 io_db["kicked_by_rival"] = False
22 io_db["path_in"] = io_dir + "in"
23 io_db["path_out"] = io_dir + "out"
24 io_db["path_worldstate"] = io_dir + "worldstate"
25 io_db["path_record"] = "record"
26 io_db["path_save"] = "save"
27 io_db["path_worldconf"] = "confserver/world"
28 io_db["tmp_suffix"] = "_tmp"
29 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
30 os.makedirs(io_dir, exist_ok=True)
31 io_db["file_out"] = open(io_db["path_out"], "w")
32 io_db["file_out"].write(io_db["teststring"] + "\n")
33 io_db["file_out"].flush()
34 if os.access(io_db["path_in"], os.F_OK):
35 os.remove(io_db["path_in"])
36 io_db["file_in"] = open(io_db["path_in"], "w")
37 io_db["file_in"].close()
38 io_db["file_in"] = open(io_db["path_in"], "r")
39 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
40 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
43 def cleanup_server_io(io_db):
44 """Close and (if io_db["kicked_by_rival"] false) remove files in io_db."""
45 def helper(file_key, path_key):
47 io_db[file_key].close()
48 if not io_db["kicked_by_rival"] \
49 and os.access(io_db[path_key], os.F_OK):
50 os.remove(io_db[path_key])
51 helper("file_out", "path_out")
52 helper("file_in", "path_in")
53 helper("file_worldstate", "path_worldstate")
54 if "file_record" in io_db:
55 io_db["file_record"].close()
58 def detect_atomic_leftover(path, tmp_suffix):
59 """Raise explained SystemExit if file is found at path + tmp_suffix."""
60 path_tmp = path + tmp_suffix
61 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
62 "aborted previous attempt to write '" + path + "'. Aborting until " \
63 "the matter is resolved by removing it from its current path."
64 if os.access(path_tmp, os.F_OK):
68 def obey(cmd, io_db, prefix, replay=False, do_record=False):
71 print("input " + prefix + ": " + cmd)
73 tokens = shlex.split(cmd, comments=True)
74 except ValueError as err:
75 print("Can't tokenize command string: " + str(err) + ".")
79 elif "PING" == tokens[0] and 1 == len(tokens):
80 io_db["file_out"].write("PONG\n")
81 io_db["file_out"].flush()
82 elif "QUIT" == tokens[0] and 1 == len(tokens):
84 record("# " + cmd, io_db)
85 raise SystemExit("received QUIT command")
86 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
88 print("Due to replay mode, reading command as 'go on in record'.")
89 line = io_db["file_record"].readline()
91 obey(line.rstrip(), io_db, io_db["file_record"].prefix
92 + str(io_db["file_record"].line_n))
93 io_db["file_record"].line_n = io_db["file_record"].line_n + 1
95 print("Reached end of record file.")
97 print("I would generate a new world now, if only I knew how.")
101 print("Invalid command/argument, or bad number of tokens.")
104 def record(cmd, io_db):
105 """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
106 # This misses some optimizations from the original record(), namely only
107 # finishing the atomic write with expensive flush() and fsync() every 15
108 # seconds unless explicitely forced. Implement as needed.
109 path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
110 if os.access(io_db["path_record"], os.F_OK):
111 shutil.copyfile(io_db["path_record"], path_tmp)
112 file = open(path_tmp, "a")
113 file.write(cmd + "\n")
115 os.fsync(file.fileno())
117 if os.access(io_db["path_record"], os.F_OK):
118 os.remove(io_db["path_record"])
119 os.rename(path_tmp, io_db["path_record"])
122 def obey_lines_in_file(path, name, do_record=False):
123 """Call obey() on each line of path's file, use name in input prefix."""
124 file = open(path, "r")
126 for line in file.readlines():
127 obey(line.rstrip(), io_db, name + "file line " + str(line_n),
133 def parse_command_line_arguments():
134 """Return settings values read from command line arguments."""
135 parser = argparse.ArgumentParser()
136 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
138 opts, unknown = parser.parse_known_args()
142 def server_test(io_db):
143 """Ensure valid server out file belonging to current process.
145 On failure, set io_db["kicked_by_rival"] and raise SystemExit.
147 if not os.access(io_db["path_out"], os.F_OK):
148 raise SystemExit("Server output file has disappeared.")
149 file = open(io_db["path_out"], "r")
150 test = file.readline().rstrip("\n")
152 if test != io_db["teststring"]:
153 io_db["kicked_by_rival"] = True
154 msg = "Server test string in server output file does not match. This" \
155 " indicates that the current server process has been " \
156 "superseded by another one."
157 raise SystemExit(msg)
160 def read_command(io_db):
161 """Return next newline-delimited command from server in file.
163 Keep building return string until a newline is encountered. Pause between
164 unsuccessful reads, and after too much waiting, run server_test().
171 add = io_db["file_in"].readline()
173 command = command + add
174 if len(command) > 0 and "\n" == command[-1]:
175 command = command[:-1]
178 time.sleep(wait_on_fail)
179 if now + max_wait < time.time():
188 opts = parse_command_line_arguments()
189 setup_server_io(io_db)
190 # print("DUMMY: Run game.")
191 if None != opts.replay:
194 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
195 " (if so late a turn is to be found).")
196 if not os.access(io_db["path_record"], os.F_OK):
197 raise SystemExit("No record file found to replay.")
199 io_db["file_record"] = open(io_db["path_record"], "r")
200 io_db["file_record"].prefix = "recod file line "
201 io_db["file_record"].line_n = 1
202 while world_db["turn"] < opts.replay:
203 line = io_db["file_record"].readline()
206 obey(line.rstrip(), io_db, io_db["file_record"].prefix
207 + str(io_db["file_record"].line_n))
208 io_db["file_record"].line_n = io_db["file_record"].line_n + 1
210 obey(read_command(io_db), io_db, "in file", replay=True)
212 if os.access(io_db["path_save"], os.F_OK):
213 obey_lines_in_file(io_db["path_save"], "save")
215 if not os.access(io_db["path_worldconf"], os.F_OK):
216 msg = "No world config file from which to start a new world."
217 raise SystemExit(msg)
218 obey_lines_in_file(io_db["path_worldconf"], "world config ",
220 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file",
223 obey(read_command(io_db), io_db, "in file", do_record=True)
224 except SystemExit as exit:
225 print("ABORTING: " + exit.args[0])
227 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
230 cleanup_server_io(io_db)
231 # print("DUMMY: (Clean up C heap.)")