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"]).
19 io_db["path_in"] = io_dir + "in"
20 io_db["path_out"] = io_dir + "out"
21 io_db["path_worldstate"] = io_dir + "worldstate"
22 io_db["path_record"] = "record"
23 io_db["path_save"] = "save"
24 io_db["path_worldconf"] = "confserver/world"
25 io_db["tmp_suffix"] = "_tmp"
26 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
27 os.makedirs(io_dir, exist_ok=True)
28 io_db["file_out"] = open(io_db["path_out"], "w")
29 io_db["file_out"].write(io_db["teststring"] + "\n")
30 if os.access(io_db["path_in"], os.F_OK):
31 os.remove(io_db["path_in"])
32 io_db["file_in"] = open(io_db["path_in"], "w")
33 io_db["file_in"].close()
34 io_db["file_in"] = open(io_db["path_in"], "r")
37 def cleanup_server_io(io_db):
38 """Close and remove all files open in IO files DB."""
39 def helper(file_key, path_key):
41 io_db[file_key].close()
42 os.remove(io_db[path_key])
43 helper("file_out", "path_out")
44 helper("file_in", "path_in")
45 helper("file_worldstate", "path_worldstate")
48 def detect_atomic_leftover(path, tmp_suffix):
49 """Raise explained SystemExit if file is found at path + tmp_suffix."""
50 path_tmp = path + tmp_suffix
51 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
52 "aborted previous attempt to write '" + path + "'. Aborting until " \
53 "the matter is resolved by removing it from its current path."
54 if os.access(path_tmp, os.F_OK):
58 def obey(cmd, io_db, prefix):
60 print("input " + prefix + ": " + cmd)
62 tokens = shlex.split(cmd, comments=True)
63 except ValueError as err:
64 print("Can't tokenize command string: " + str(err) + ".")
68 elif "PING" == tokens[0] and 1 == len(tokens):
69 io_db["file_out"].write("PONG\n")
70 elif "QUIT" == tokens[0] and 1 == len(tokens):
71 record("# " + cmd, path_recordfile)
72 raise SystemExit("received QUIT command")
73 elif "MAKE_WORLD" == tokens[0] and 2 == len(tokens):
74 print("I would generate a new world now, if only I knew how.")
77 print("Invalid command/argument, or bad number of tokens.")
80 def record(cmd, io_db):
81 """Append cmd string plus newline to file at path_recordfile. (Atomic.)"""
82 # This misses some optimizations from the original record(), namely only
83 # finishing the atomic write with expensive flush() and fsync() every 15
84 # seconds unless explicitely forced. Implement as needed.
85 path_tmp = io_db["path_record"] + io_db["tmp_suffix"]
86 if os.access(io_db["path_record"], os.F_OK):
87 shutil.copyfile(io_db["path_record"], path_tmp)
88 file = open(path_tmp, "a")
89 file.write(cmd + "\n")
91 os.fsync(file.fileno())
93 if os.access(io_db["path_record"], os.F_OK):
94 os.remove(io_db["path_record"])
95 os.rename(path_tmp, io_db["path_record"])
98 def obey_lines_in_file(path, name, break_test = None):
99 """Call obey() on each line of path's file, use name in input prefix.
101 If break_test function is set, only read the file until it returns True.
103 file = open(path, "r")
105 for line in file.readlines():
106 if None != break_test and break_test():
108 obey(line.rstrip(), io_db, name + "file line " + str(line_n))
113 def make_turn_tester(turn_to_compare, world_db):
114 """Return tester whether world_db["turn"] greater/equal turn_to_compare."""
116 return world_db["turn"] >= turn_to_compare
123 parser = argparse.ArgumentParser()
124 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
126 setup_server_io(io_db)
127 # print("DUMMY: Run game.")
128 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
129 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
130 opts, unknown = parser.parse_known_args()
131 if None != opts.replay:
134 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
135 " (if so late a turn is to be found).")
136 if not os.access(io_db["path_record"], os.F_OK):
137 raise SystemExit("No record file found to replay.")
139 break_tester = make_turn_tester(opts.replay, world_db)
140 obey_lines_in_file(io_db["path_record"], "record ", break_tester)
142 if os.access(io_db["path_save"], os.F_OK):
143 obey_lines_in_file(io_db["path_save"], "save")
145 if not os.access(io_db["path_worldconf"], os.F_OK):
146 msg = "No world config file from which to start a new world."
147 raise SystemExit(msg)
148 obey_lines_in_file(io_db["path_worldconf"], "world config ")
149 obey("MAKE_WORLD " + str(int(time.time())), io_db, "in file")
150 # print("DUMMY: Run io_loop().")
151 except SystemExit as exit:
152 print("ABORTING: " + exit.args[0])
154 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
157 cleanup_server_io(io_db)
158 # print("DUMMY: (Clean up C heap.)")