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 remove all files open in IO files DB."""
43 def helper(file_key, path_key):
45 io_db[file_key].close()
46 os.remove(io_db[path_key])
47 helper("file_out", "path_out")
48 helper("file_in", "path_in")
49 helper("file_worldstate", "path_worldstate")
52 def detect_atomic_leftover(path, tmp_suffix):
53 """Raise explained SystemExit if file is found at path + tmp_suffix."""
54 path_tmp = path + tmp_suffix
55 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
56 "aborted previous attempt to write '" + path + "'. Aborting until " \
57 "the matter is resolved by removing it from its current path."
58 if os.access(path_tmp, os.F_OK):
62 def obey(cmd, io_db, prefix):
64 print("input " + prefix + ": " + cmd)
66 tokens = shlex.split(cmd, comments=True)
67 except ValueError as err:
68 print("Can't tokenize command string: " + str(err) + ".")
72 elif "PING" == tokens[0] and 1 == len(tokens):
73 io_db["file_out"].write("PONG\n")
74 elif "QUIT" == tokens[0] and 1 == len(tokens):
75 record("# " + cmd, path_recordfile)
76 raise SystemExit("received QUIT command")
77 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
78 print("I would generate a new world now, if only I knew how.")
81 print("Invalid command/argument, or bad number of tokens.")
84 def record(cmd, io_db):
85 """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
86 # This misses some optimizations from the original record(), namely only
87 # finishing the atomic write with expensive flush() and fsync() every 15
88 # seconds unless explicitely forced. Implement as needed.
89 path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
90 if os.access(io_db["path_record"], os.F_OK):
91 shutil.copyfile(io_db["path_record"], path_tmp)
92 file = open(path_tmp, "a")
93 file.write(cmd + "\n")
95 os.fsync(file.fileno())
97 if os.access(io_db["path_record"], os.F_OK):
98 os.remove(io_db["path_record"])
99 os.rename(path_tmp, io_db["path_record"])
102 def obey_lines_in_file(path, name, break_test=None):
103 """Call obey() on each line of path's file, use name in input prefix.
105 If break_test function is set, only read the file until it returns True.
107 file = open(path, "r")
109 for line in file.readlines():
110 if None != break_test and break_test():
112 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
117 def make_turn_tester(turn_to_compare, world_db):
118 """Return tester whether world_db["turn"] greater/equal turn_to_compare."""
120 return world_db["turn"] >= turn_to_compare
124 def parse_command_line_arguments():
125 """Return settings values read from command line arguments."""
126 parser = argparse.ArgumentParser()
127 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
129 opts, unknown = parser.parse_known_args()
133 def server_test(io_db):
134 """Check for valid server out file belonging to current process."""
135 if not os.access(io_db["path_out"], os.F_OK):
136 raise SystemExit("Server output file has disappeared.")
137 file = open(io_db["path_out"], "r")
138 test = file.readline().rstrip("\n")
140 print(str(test) + " == " + io_db["teststring"] + " ?")
141 if test != io_db["teststring"]:
142 msg = "Server test string in server output file does not match. This" \
143 " indicates that the current server process has been " \
144 "superseded by another one."
145 raise SystemExit(msg)
150 opts = parse_command_line_arguments()
151 setup_server_io(io_db)
152 # print("DUMMY: Run game.")
153 if None != opts.replay:
156 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
157 " (if so late a turn is to be found).")
158 if not os.access(io_db["path_record"], os.F_OK):
159 raise SystemExit("No record file found to replay.")
161 break_tester = make_turn_tester(opts.replay, world_db)
162 obey_lines_in_file(io_db["path_record"], "record ", break_tester)
165 if os.access(io_db["path_save"], os.F_OK):
166 obey_lines_in_file(io_db["path_save"], "save")
168 if not os.access(io_db["path_worldconf"], os.F_OK):
169 msg = "No world config file from which to start a new world."
170 raise SystemExit(msg)
171 obey_lines_in_file(io_db["path_worldconf"], "world config ")
172 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
173 # print("DUMMY: Run io_loop().")
174 except SystemExit as exit:
175 print("ABORTING: " + exit.args[0])
177 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
180 cleanup_server_io(io_db)
181 # print("DUMMY: (Clean up C heap.)")