9 def setup_server_io(io_db):
10 """Fill IO files DB with proper file( path)s. Write process IO test string.
12 Decide file paths. Ensure IO files directory at server/. Remove any old in
13 file if found. Set up new in file (io_db["file_in"]) for reading at
14 io_db["path_in"], and new out file (io_db["file_out"]) for writing at
15 io_db["path_out"]. Start out file with process hash line of format PID +
16 " " + floated UNIX time (io_db["teststring"]). Run detect_atomic_leftover
17 on io_db["path_record"] and io_db["path_save"].
20 io_db["path_in"] = io_dir + "in"
21 io_db["path_out"] = io_dir + "out"
22 io_db["path_worldstate"] = io_dir + "worldstate"
23 io_db["path_record"] = "record"
24 io_db["path_save"] = "save"
25 io_db["path_worldconf"] = "confserver/world"
26 io_db["tmp_suffix"] = "_tmp"
27 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
28 os.makedirs(io_dir, exist_ok=True)
29 io_db["file_out"] = open(io_db["path_out"], "w")
30 io_db["file_out"].write(io_db["teststring"] + "\n")
31 io_db["file_out"].flush()
32 if os.access(io_db["path_in"], os.F_OK):
33 os.remove(io_db["path_in"])
34 io_db["file_in"] = open(io_db["path_in"], "w")
35 io_db["file_in"].close()
36 io_db["file_in"] = open(io_db["path_in"], "r")
37 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
38 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
41 def cleanup_server_io(io_db):
42 """Close and (if io_db["kicked_by_rival"] false) remove files in io_db."""
43 def helper(file_key, path_key):
45 io_db[file_key].close()
46 if not io_db["kicked_by_rival"]:
47 os.remove(io_db[path_key])
48 helper("file_out", "path_out")
49 helper("file_in", "path_in")
50 helper("file_worldstate", "path_worldstate")
53 def detect_atomic_leftover(path, tmp_suffix):
54 """Raise explained SystemExit if file is found at path + tmp_suffix."""
55 path_tmp = path + tmp_suffix
56 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
57 "aborted previous attempt to write '" + path + "'. Aborting until " \
58 "the matter is resolved by removing it from its current path."
59 if os.access(path_tmp, os.F_OK):
63 def obey(cmd, io_db, prefix):
65 print("input " + prefix + ": " + cmd)
67 tokens = shlex.split(cmd, comments=True)
68 except ValueError as err:
69 print("Can't tokenize command string: " + str(err) + ".")
73 elif "PING" == tokens[0] and 1 == len(tokens):
74 io_db["file_out"].write("PONG\n")
75 elif "QUIT" == tokens[0] and 1 == len(tokens):
76 record("# " + cmd, path_recordfile)
77 raise SystemExit("received QUIT command")
78 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
79 print("I would generate a new world now, if only I knew how.")
82 print("Invalid command/argument, or bad number of tokens.")
85 def record(cmd, io_db):
86 """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
87 # This misses some optimizations from the original record(), namely only
88 # finishing the atomic write with expensive flush() and fsync() every 15
89 # seconds unless explicitely forced. Implement as needed.
90 path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
91 if os.access(io_db["path_record"], os.F_OK):
92 shutil.copyfile(io_db["path_record"], path_tmp)
93 file = open(path_tmp, "a")
94 file.write(cmd + "\n")
96 os.fsync(file.fileno())
98 if os.access(io_db["path_record"], os.F_OK):
99 os.remove(io_db["path_record"])
100 os.rename(path_tmp, io_db["path_record"])
103 def obey_lines_in_file(path, name, break_test=None):
104 """Call obey() on each line of path's file, use name in input prefix.
106 If break_test function is set, only read the file until it returns True.
108 file = open(path, "r")
110 for line in file.readlines():
111 if None != break_test and break_test():
113 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
118 def make_turn_tester(turn_to_compare, world_db):
119 """Return tester whether world_db["turn"] greater/equal turn_to_compare."""
121 return world_db["turn"] >= turn_to_compare
125 def parse_command_line_arguments():
126 """Return settings values read from command line arguments."""
127 parser = argparse.ArgumentParser()
128 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
130 opts, unknown = parser.parse_known_args()
134 def server_test(io_db):
135 """Ensure valid server out file belonging to current process.
137 On failure, set io_db["kicked_by_rival"] and raise SystemExit.
139 if not os.access(io_db["path_out"], os.F_OK):
140 raise SystemExit("Server output file has disappeared.")
141 file = open(io_db["path_out"], "r")
142 test = file.readline().rstrip("\n")
144 if test != io_db["teststring"]:
145 io_db["kicked_by_rival"] = True
146 msg = "Server test string in server output file does not match. This" \
147 " indicates that the current server process has been " \
148 "superseded by another one."
149 raise SystemExit(msg)
155 opts = parse_command_line_arguments()
156 setup_server_io(io_db)
157 # print("DUMMY: Run game.")
158 if None != opts.replay:
161 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
162 " (if so late a turn is to be found).")
163 if not os.access(io_db["path_record"], os.F_OK):
164 raise SystemExit("No record file found to replay.")
166 break_tester = make_turn_tester(opts.replay, world_db)
167 obey_lines_in_file(io_db["path_record"], "record ", break_tester)
170 if os.access(io_db["path_save"], os.F_OK):
171 obey_lines_in_file(io_db["path_save"], "save")
173 if not os.access(io_db["path_worldconf"], os.F_OK):
174 msg = "No world config file from which to start a new world."
175 raise SystemExit(msg)
176 obey_lines_in_file(io_db["path_worldconf"], "world config ")
177 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
180 # print("DUMMY: Run io_loop().")
181 except SystemExit as exit:
182 print("ABORTING: " + exit.args[0])
184 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
187 cleanup_server_io(io_db)
188 # print("DUMMY: (Clean up C heap.)")